source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Is it rated?
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.
It's known that if at least one participant's rating has changed, then the round was rated for sure.
It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.
In this problem, you should not make any other assumptions about the rating system.
Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
|
```python
n=int(input())
l=0
r=0
ll=[]
ll1=[]
for i in range(n):
a=input().split(" ")
l+=int(a[0])
r+=int(a[1])
ll.append(list(map(int,a)))
ll1=list(ll)
flag=0
if(l!=r):
print("rated")
else:
ll.sort(reverse=True)
for j in range(n):
#print(ll[j],ll1[j])
if(ll[j]==ll1[j]):
flag=1
else:
flag=0
break
if(flag==0):
print("unrated")
else:
print("maybe")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*):
- point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=<<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=<<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=><=*y*
We'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.
Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
|
```python
def process(A):
d_x = {}
d_y = {}
for x,y in A:
if x not in d_x:
d_x[x] = [y, y]
else:
d_x[x][0] = min(d_x[x][0], y)
d_x[x][1] = max(d_x[x][1], y)
if y not in d_y:
d_y[y] = [x, x]
else:
d_y[y][0] = min(d_y[y][0], x)
d_y[y][1] = max(d_y[y][1], x)
answer = 0
for x, y in A:
if d_x[x][0] < y < d_x[x][1]:
if d_y[y][0] < x < d_y[y][1]:
answer+=1
return answer
n = int(input())
A = []
for i in range(n):
x, y = [int(x) for x in input().split()]
A.append([x, y])
print(process(A))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
|
```python
from bisect import *
N = int(input())
a = sorted(list(map(int, input().split())))
Q = int(input())
for _ in range(Q):
budget = int(input())
print(bisect_right(a, budget))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
|
```python
players = input()
if "1" * 7 in players or "0" * 7 in players:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.
For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.
Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
|
```python
import sys
num = int(sys.stdin.readline().strip())
lst = sys.stdin.readline().strip().split()
# print(lst)
lst1 = map(int, lst)
mp = list(lst1)
# print(mp)
maxi = max(mp)
mini = min(mp)
# print(maxi)
# print(mini)
maxi_inx = []
mini_inx = []
for i in range(len(mp)):
if mp[i] == maxi:
maxi_inx.append(i)
if mp[i] == mini:
mini_inx.append(i)
# print(maxi_inx)
# print(mini_inx)
if min(maxi_inx) < max(mini_inx):
summ = min(maxi_inx) + len(lst) - (max(mini_inx) + 1)
print(summ)
else:
summ = min(maxi_inx) + len(lst) - (max(mini_inx) + 1) - 1
print(summ)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* students living in the campus. Every morning all students wake up at the same time and go to wash. There are *m* rooms with wash basins. The *i*-th of these rooms contains *a**i* wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
|
```python
import functools,math,itertools,time
u=functools.lru_cache(maxsize=None)
n,m=map(int,input().split())
s=[*map(int,input().split())]
t=u(lambda x:1 if x<2 else x*t(x-1))
c=u(lambda r,n:t(n)/t(r)/t(n-r))
p=u(lambda n,k:n**k)
w=u(lambda n,k:math.ceil(n/k))
r=u(lambda k,n:max(k,n))
h=u(lambda i,j,l:c(l,i)*p(j-1,i-l)/p(j,i))
for i,j in itertools.product(range(1,n+1),range(1,m+1)):
for l in range(i+1):
h(i,j,l)
@u
def d(i,j,k):
if j:
q=0
for l in range(i + 1):
q+=h(i,j,l)*d(i-l,j-1,r(k,w(l,s[j-1])))
return q
return k
print(d(n,m,0))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
|
```python
l=list(map(int,input().split()))
l.sort(reverse=True)
a=l[0]
b=l[1]
c=l[2]
d=l[3]
if(b+c>a or b+d>a or c+d>a or c+d>b):
print("TRIANGLE")
elif(b+c==a or b+d==a or c+d==a or c+d==b):
print("SEGMENT")
else:
print("IMPOSSIBLE")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
|
```python
# https://codeforces.com/problemset/problem/996/A
def main():
n = int(input())
sum = 0
bills = [100, 20, 10, 5, 1]
for i in bills:
sum += n // i
n %= i
print(sum)
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.
Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
|
```python
planksAmount, k = map(int, input().split())
planksHeight = list(map(int, input().split()))
planksHeight.sort()
if len(planksAmount) == 1:
print(1)
else:
print(sum(planksHeight[:k]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).
Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.
For each city calculate two values *min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city
|
```python
n = int(input()) # number of cities
x = list(map(int, input().split())) # list of city coordinates
mini = [0]*n
maxi = [0]*n
# calculate mini values
for i in range(n):
if i == 0:
mini[i] = x[1] - x[0]
elif i == n-1:
mini[i] = x[n-1] - x[n-2]
else:
mini[i] = min(x[i]-x[i-1], x[i+1]-x[i])
# calculate maxi values
for i in range(n):
maxi[i] = max(x[i]-x[0], x[n-1]-x[i])
# print mini and maxi values
for i in range(n):
print(mini[i], maxi[i])
This code first reads the input values, calculates the mini and maxi values using the algorithm discussed above, and then prints these values in the required format. The output will consist of n lines, where the i-th line contains the mini and maxi values for the i-th city separated by a space.
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.
Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.
|
```python
a = int(input())
b = int(input())
c = int(input())
if (b < 2*a):
# Constraint is b, rather than a
if (c < 2*b):
# Constraint is c, not a or b
a = c//4
b = 2*a
c = 2*b
else:
# c >= 2b, so constraint is b, not a or c
a = b//2
b = 2*a
c = 2*b
else:
# b >= 2a, constraint is a, rather than b
if (c < 4*a):
# Constraint is c, not a or b
a = c//4
b = 2*a
c = 2*b
else:
# c >= 4a, so constraint is a, not b or c
a = a
b = 2*a
c = 2*b
print(a+b+c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.
The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.
|
```python
a = int(input())
b = int(input())
b, a = max(a, b), min(a, b)
if (b - a) % 2 == 0:
print((1 + (b - a) // 2) * (b - a) // 2)
else:
print((1 + (b - a + 1) // 2) * ((b - a + 1) // 2) // 2 + (1 + (b - a - 1) // 2) * ((b - a - 1) // 2) // 2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
n=input()
c=0
for i in n:
if i.isupper():
c=c+1
if c>len(n)//2:
n=n.upper()
else:
n=n.lower()
print(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
|
```python
# https://codeforces.com/problemset/problem/189/A
from functools import lru_cache
import sys
sys.setrecursionlimit(4000)
def helper() -> int:
n, a, b, c = [int(s) for s in input().split(" ")]
a, b, c = sorted([a, b, c])
dp = [0] * n
dp[-a] = 1
dp[-b] = 1
dp[-c] = 1
for i in range(len(dp) - 1, -1, -1):
for value in [a,b,c]:
if i + value < len(dp) and dp[i + value] > 0:
dp[i] = max(dp[i], 1 + dp[i + value])
return dp[0]
print(helper())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sean is trying to save a large file to a USB flash drive. He has *n* USB flash drives with capacities equal to *a*1,<=*a*2,<=...,<=*a**n* megabytes. The file size is equal to *m* megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
|
```python
n = int(input())
file_size = int(input())
flash_size = [int(input()) for i in range(n)]
flash_size.sort(reverse=True)
i = 0
s = 0
while i < n:
s += flash_size[i]
i += 1
if s >= file_size:
break
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has *n* rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
|
```python
n=int(input())
li_st=[]
for i in range(0,n-1):
m=input()
li_st.append(m)
ans = "NO"
for i in range(0,n-1):
m = li_st[i]
if ans=="NO":
for j in range(0,4):
if m[j]==m[j+1] and m[j]=='O':
m=m.replace("OO","++")
ans = "YES"
break
li_st[i] = m
print(ans)
if ans=="YES":
for x in (li_st):
print(x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
|
```python
s=input()
t=s.split()
n=int(t[0])
h=int(t[1])
s=input()
t=s.split()
w=0
for i in t:
if int(i)>h:
w+=2
else:
w+=1
print(w)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gennady is one of the best child dentists in Berland. Today *n* children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to *n* in the order they go in the line. Every child is associated with the value of his cofidence *p**i*. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.
While Gennady treats the teeth of the *i*-th child, the child is crying with the volume of *v**i*. At that the confidence of the first child in the line is reduced by the amount of *v**i*, the second one — by value *v**i*<=-<=1, and so on. The children in the queue after the *v**i*-th child almost do not hear the crying, so their confidence remains unchanged.
If at any point in time the confidence of the *j*-th child is less than zero, he begins to cry with the volume of *d**j* and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the *j*-th one in the line is reduced by the amount of *d**j*.
All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.
Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.
|
```python
n = int(input())
list_child = []
list_output = []
for i in range(n):
s = [int(j) for j in input().split()]
list_child.append([s[0],s[1],s[2],i+1])
t = 0
while t < n:
if list_child[t][2] >= 0:
for i in range(list_child[t][0]):
if t+i < n-1:
list_child[t+i+1][2] -= list_child[t][0]-i
list_output.append(list_child[t][3])
elif t < n-1:
for j in range(t+1,n):
list_child[j][2] -= list_child[t][1]
t += 1
print (len(list_output))
for i in range(len(list_output)-1):
print (list_output[i],end=' ')
print (list_output[len(list_output)-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
|
```python
n , m = map(int,input().split())
arr = input().split()
x = arr.count('1')
y = n - x
ans = ''
for j in range(m):
l , r = map(int,input().split())
if (r - l + 1) % 2 == 0 and min(x , y) >= (r - l + 1)//2 :
ans += '1\n'
else:
ans += '0\n'
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
|
```python
#!/usr/bin/env python3
# coding:utf-8
if __name__ == "__main__":
n, m = [int(item) for item in input().split()]
for i in n:
arr = input().split()
if "C" in arr or "Y" in arr or "M" in arr:
print("#Color")
exit(0)
print("#Black&White")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.
The potato pie is located in the *n*-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.
Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
|
```python
n = int(input())
p = []
a = list(input())
sum = 0
for i in range(len(a)):
if i % 2 == 0:
p.append((chr(ord(a[i]) - 32)))
else:
if a[i] in p:
p.remove(a[i])
else:
sum += 1
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
|
```python
a, b = map(int,input().split(" "))
print(str(a+b))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw *n* distinct points and *m* segments on the *OX* axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment [*l**i*,<=*r**i*] consider all the red points belong to it (*r**i* points), and all the blue points belong to it (*b**i* points); each segment *i* should satisfy the inequality |*r**i*<=-<=*b**i*|<=≤<=1.
Iahub thinks that point *x* belongs to segment [*l*,<=*r*], if inequality *l*<=≤<=*x*<=≤<=*r* holds.
Iahub gives to you all coordinates of points and segments. Please, help him to find any good drawing.
|
```python
#input
n,m=map(int,input().split())
xlist=[int(x) for x in input().split()]
for i in range(m):
segment=[int(x) for x in input().split()]
#variables
color=''
#main
for i in range(n):
if i%2==0:
color+='0 '
else:
color+='1 '
print(color)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
|
```python
from sys import stdin,stdout
from math import gcd,sqrt,floor,ceil
# Fast I/O
input = stdin.readline
print = stdout.write
def list_inp(x):return list(map(x,input().split()))
def map_inp(x):return map(x,input().split())
def lcm(a,b): return (a*b)/gcd(a,b)
def solve(x):
return x[len(x)//2]-x[(len(x)-1)//2]+1
t = int(input())
cnt = 0
for _ in range(t):
a,b = map_inp(int)
if a == b:
continue
elif a == 0 and b == 1:
cnt+=1
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
|
```python
import sys, threading
import math
from math import log2,floor
import heapq
from collections import defaultdict,deque
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
n = str(inp())
s = ""
for i in range(len(n)):
if 9 - int(n[i]) < int(n[i]):
if 9 - int(n[i]) == 0 and len(s) == 0:
s += n[i]
else:
s += str(9 - int(n[i]))
else:
s += n[i]
print(int(s))
# def main():
# threading.stack_size(1 << 27)
# sys.setrecursionlimit(1 << 30)
# main_thread = threading.Thread(target=main)
# main_thread.start()
# main_thread.join()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya and Vasya are playing a game. Petya's got *n* non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to *n* from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position *s*. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position *p*1, the glass from the second position to position *p*2 and so on. That is, a glass goes from position *i* to position *p**i*. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.
After all shuffling operations Petya shows Vasya that the ball has moved to position *t*. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position *s* to position *t*.
|
```python
#B. Find Marble
n,s,t = map(int,input().split())
p = list(map(int,input().split()))
a = list(range(1,n+1))
m = a[s-1]
x = 0
if s == t:
print(0)
else:
while True:
tmp = [0]*n
for i in range(n):
tmp[p[i]-1] = a[i]
x += 1
if tmp[t-1] == m:
print(x)
break
elif tmp[s-1] == m:
print(-1)
break
a = tmp
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
|
```python
from sys import stdin
from collections import Counter,defaultdict,deque
import sys
import math
import os
import operator
import random
from fractions import Fraction
import functools
import bisect
import itertools
from heapq import *
import copy
ans = []
for _ in range(int(input())):
ans.append(input())
ans = ans[::-1]
visit = set()
for i in ans:
if i not in visit:
print(i)
visit.add(i)
'''
n = int(input())
arr = list(map(int,input().split()))
dp = [[0 for i in range(11)] for j in range(n+2)]
print(dp)
dp[1][arr[1]] = 1
for i in range(1,n):
for j in range(10):
dp[i+1][(j+arr[i+1])%10]+=dp[i][j]
dp[i+1][(j*arr[i+1])%10]+=dp[i][j]
for i in range(10):
print(dp[n][i])
def error(n):
return (n - int(n))<1
a = [5,4,3,2,1]
k = 300
left,right = 0,k
mid = (left + right) / 2
while left<=right:
square = (mid*mid)
if int(square) == k and error(square) == True:
print(mid)
break
elif square <= k:
left = mid
else:
right = mid
mid = (left + right) / 2
'''
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
|
```python
import sys
import math
def scan(input_type='int'):
return list(map(int, sys.stdin.readline().strip().split()))
def solution():
# for _ in range(int(input())):
n, k = scan()
s = input()
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
c = {}
for i in range(26):
c[a[i]] = i+1
b = [i for i in s]
b.sort()
s = 1000000000
for i in range(n):
e = k
j = i+1
w = c[b[i]]
q = b[i]
p = 0
while e > 1 and j < n:
if c[b[j]] - c[q[p]] > 2:
w += c[b[j]]
q += b[j]
p += 1
e -= 1
j += 1
if e == 1:
s = min(s, w)
break
if s == 1000000000:
print(-1)
else:
print(s)
if __name__ == '__main__':
solution()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.
The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23.
Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.
Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
|
```python
t = int(input())
l = []
for i in range(t):
m = input()
l.append(m)
for i in range(len(l) , 0 , -1):
print(l[i-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day *n* cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move *i*-th cell can exchange it's value with the value of some other *j*-th cell, if |*i*<=-<=*j*|<==<=*d**i*, where *d**i* is a favourite number of *i*-th cell. Cells make moves in any order, the number of moves is unlimited.
The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to *n*. You are to determine whether the game could move to this state.
|
```python
from __future__ import division
from sys import stdin, stdout
from queue import PriorityQueue
from heapq import *
from collections import deque, defaultdict, Counter
from bitarray import bitarray
input_int = lambda: int(stdin.readline())
input_1D_int = lambda: [int(x) for x in stdin.readline().split()]
input_2D_int = lambda n: [input_1D_int() for _ in range(n)]
input_string = lambda: stdin.readline().strip()
input_1D_string = lambda: [str(x) for x in stdin.readline().split()]
input_2D_string = lambda n: [input_1D_string() for _ in range(n)]
pr = lambda args, sep: stdout.write(sep.join(map(str, args)) + '\n')
chars, oo = 'abcdefghijklmnopqrstuvwxyz', int(1000000000000000000)
class DSU:
def __init__(self, n):
self.groupSize = [0] * (n + 1)
self.parent = [0] * (n + 1)
self.rank = [0] * (n + 1)
self.mx = [0] * (n + 1)
self.mn = [0] * (n + 1)
for i in range(n + 1):
self.parent[i] = i
self.mx[i] = self.mn[i] = i
self.groupSize[i] = 1
self.rank[i] = 0
def make_set(self, u):
self.parent[u] = u
self.groupSize[u] = 1
def find_set(self, x):
if self.parent[x] == x: return x
self.parent[x] = self.find_set(self.parent[x])
return self.parent[x]
def union_set(self, u, v):
leader1 = self.find_set(u)
leader2 = self.find_set(v)
if leader1 == leader2: return
if self.groupSize[leader1] < self.groupSize[leader2]:
leader1, leader2 = leader2, leader1
self.parent[leader2] = leader1
self.groupSize[leader1] += self.groupSize[leader2]
if self.rank[leader1] == self.rank[leader2]:
self.rank[leader1] += 1
self.mx[leader1] = max(self.mx[leader1], self.mx[leader2])
self.mn[leader1] = min(self.mn[leader1], self.mn[leader2])
def samegroup(self, u, v):
leader1 = self.find_set(u)
leader2 = self.find_set(v)
return leader1 == leader2
def sizeGroup(self, u):
leader = self.find_set(u)
return self.groupSize[leader]
def get_max(self, u):
return self.mx[self.find_set(u)]
def get_min(self, u):
return self.mn[self.find_set(u)]
n = input_int()
a = input_1D_int()
b = input_1D_int()
dsu = DSU(n + 10)
for i in range(0, n):
r = (i + 1) + b[i]
l = (i + 1) - b[i]
if r > 0 and r <= n:dsu.union_set(r, i + 1)
if l <= n and l > 0:dsu.union_set(l, i + 1)
for i in range(0, n):
if dsu.find_set(a[i]) != dsu.find_set(i + 1):
print("NO")
exit()
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
- either it only contains uppercase letters; - or all letters except for the first one are uppercase.
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
|
```python
s = input()
s1 = ''
if s.isupper():
s1 += s[0]
s= s[1:].lower()
s1 += s
print(s1)
elif s[0] >= 'a' and s[0] <= 'z':
s1 += s[0]
s1 = s1.upper()
if s[1:].isupper():
s = s[1:].lower()
s1 += s
print(s1)
else:
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.
The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.
|
```python
a = int(input())
b = int(input())
c = abs(a - b)
ans = 0
for i in range(c // 2 + 1):
ans += 2 * i
if c % 2 == 1:
ans += i + 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where
Now DZY has a string *s*. He wants to insert *k* lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
|
```python
n = input()
k = int(input())
a = list(map(int , input().split()))
s = 0
for i in range(len(n)):
s+=(a[ord(n[i])-97])*(i+1)
x = max(a)
j = len(n)+1
for i in range(k):
s+=j*x
j+=1
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
|
```python
def ii(): return int(input())
def mi(): return map(int,input().split())
def li(): return list(mi())
def main():
n=ii()
v=li()
c=0
ans=v[0]
for i in range(0,n-1):
c+=v[i]-v[i+1]
if(c<=0):
ans+=(-c)
c=0
print(ans)
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*).
|
```python
n,k=map(int,input().split())
c=0
for i in range (n):
a = input()
m = 0
for j in range (k+7):
if str(j) in a:
m = m+1
if m == k+1:
c=c+1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.
Please output the maximum number of cake cells that the cakeminator can eat.
|
```python
r, c = map(int, input().split())
cake = []
cc = [True for i in range(c)]
cr = [True for i in range(r)]
t = 0
for i in range(r):
cake.append(input())
for row in range(r):
for col in range(c):
if cake[row][col] == 'S':
cc[col] = False
cr[row] = False
for i in range(r):
for j in range(c):
if cc[j] or cr[i]:
t += 1
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Calculate the minimum number of characters you need to change in the string *s*, so that it contains at least *k* different letters, or print that it is impossible.
String *s* consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
|
```python
a = input()
b = int(input())
if len(a) >= b and b - len(set(list(a))) <= 0 and len(set(list(a))) < 26:
if b - len(set(list(a))) > 0:
print(b - len(set(list(a))))
else:
print(0)
else:
print("impossible")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
|
```python
n,m=map(int,input().split())
li=list(map(int,input().split()))
li.sort()
t=0
for x in range(m):
if li[x]<0:
t+=-li[x]
else:
t-=li[x]
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
An African crossword is a rectangular table *n*<=×<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.
When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.
You are suggested to solve an African crossword and print the word encrypted there.
|
```python
from collections import defaultdict
def main():
n, m = map(int, input().split())
matrix = []
for i in range(n):
matrix.append(input())
row_freq = defaultdict(dict)
col_freq = defaultdict(dict)
for i in range(n):
for j in range(m):
letter = matrix[i][j]
if letter not in row_freq[i]:
row_freq[i][letter] = 0
if letter not in col_freq[j]:
col_freq[j][letter] = 0
row_freq[i][letter] += 1
col_freq[j][letter] += 1
encrypted = []
for i in range(n):
for j in range(m):
letter = matrix[i][j]
if row_freq[i][letter] == 1 and col_freq[j][letter] == 1:
encrypted.append(letter)
print(''.join(encrypted))
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.
The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.
Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
|
```python
s1 = input()
s2 = input()
s3 = input()
s11 = s1+s2
def checking(s1,s2):
count1 = {}
count2 = {}
for char in s1:
count1[char] = count1.get(char,0) + 1
for char in s2:
count2[char] = count2.get(char,0) +1
if count2 == count1:
print('YES')
else:
print("NO")
checking(s11,s3)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of *n* digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it *d*. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation *k* times: find the minimum *x* (1<=≤<=*x*<=<<=*n*) such that *d**x*<==<=4 and *d**x*<=+<=1<==<=7, if *x* is odd, then to assign *d**x*<==<=*d**x*<=+<=1<==<=4, otherwise to assign *d**x*<==<=*d**x*<=+<=1<==<=7. Note that if no *x* was found, then the operation counts as completed and the array doesn't change at all.
You are given the initial number as an array of digits and the number *k*. Help Petya find the result of completing *k* operations.
|
```python
n,k = map(int,input().split())
arr = list(input())
while k>0:
flag=True
for i in range(n-1):
if arr[i]=='4' and arr[i+1]=='7':
if (i+1)%2==1:
arr[i]='4'
arr[i+1]='4'
else:
arr[i]='7'
arr[i+1]='7'
flag=False
break
if flag:
break
k-=1
print (''.join(arr))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the *n*-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
|
```python
n = int(input())
c = input()[::-1]
nc = format(int(c, 2)+1, f"0{len(c)}b")[::-1]
o = 0
print(nc)
for cb, ncb in zip(c, nc):
if cb != ncb:
o += 1
print(o)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
|
```python
a,b=map(int,input().split())
c=list(map(int,input().split()))
l=0
for i in range(a):
if b>=c[i]:
l=l+1
else:
l=l+(c[i]//b)
print(l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
|
```python
n = int(input())
l = [int(i) for i in input().split()]
total = n+1
s = sum(l)
ans = 0
for i in range(5):
s+=1
if(s%(n+1)==1):
pass
else:
ans+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A newspaper is published in Walrusland. Its heading is *s*1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word *s*2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".
Which least number of newspaper headings *s*1 will Fangy need to glue them, erase several letters and get word *s*2?
|
```python
from math import *
from sys import stdin, stdout, setrecursionlimit
from bisect import *
from collections import *
input = lambda: stdin.readline().strip()
print = stdout.write
s1=input()
s2=input()
al=defaultdict(list)
count=1;index=0;count=0
for i in range(len(s1)):
al[s1[i]].append(i)
for i in range(len(s2)):
if(len(al[s2[i]])==0):
print(str(-1))
exit()
for i in range(len(s2)):
r=bisect_left(al[s2[i]],index)
if(r==len(al[s2[i]])):
count+=1
index=al[s2[i]][0]+1
else:
index=al[s2[i]][r]+1
print(str(count))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
|
```python
import math
cnt=0
st=""
from itertools import combinations
def powerset(string):
global cnt
for i in range(0,len(string)+1):
for element in combinations(string,i):
if(''.join(element)=="QAQ"):
cnt+=1
def powerSet(arr, n) :
global cnt
global st
opsize = math.pow(2, n)
for counter in range( 1, (int)(opsize)) :
st=""
for j in range(0, n) :
if (counter & (1<<j)) :
st+=arr[j]
print(st)
if(st=="QAQ"):
cnt+=1
if(__name__=='__main__'):
s1=input()
index=0
curr=""
powerset(s1)
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.
You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.
Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
|
```python
# Author : //- kibrom Hailu -\\
from sys import stdin,stdout
from collections import Counter,defaultdict , deque
from bisect import bisect , bisect_left ,bisect_right
from itertools import accumulate
from heapq import heapify , heappop , heappush , heappushpop , heapreplace
def I(): return int(stdin.readline())
def II(): return map(int, stdin.readline().split())
def IL(): return list(map(int, stdin.readline().split()))
def SIL(): return sorted(map(int, stdin.readline().split()))
def solve():
# write your code here
n = I()
dir = input()
nums = IL()
min_diff = float("inf")
for i in range(1,n):
a , b = nums[i-1], nums[i]
al , bl = dir[i-1], dir[i]
if al == "R" and bl == "L":
min_diff = min(min_diff,max(a,b)-min(a,b))
return min_diff//2 if min_diff != float("inf") else -1
print(solve())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
word = list(str(input()))
count_caps = 0
for letter in word:
if letter.upper() == letter:
count_caps += 1
if count_caps > len(word) - count_caps:
for i in range(len(word)):
char = word[i].upper()
word[i] = char
else:
for i in range(len(word)):
char = word[i].lower()
word[i] = char
word = ''.join(word)
print(word)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
|
```python
n=int(input())
res=0
arr=[int(x) for x in str(n)]
for i in range(0,len(arr)-1):
if(i==0 and arr[i]==9):
continue
elif(arr[i]>=5):
arr[i]=9-arr[i]
for i in range(0,len(arr)):
res=res+(10**(len(arr)-1-i))*arr[i]
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array *a*1,<=*a*2,<=...,<=*a**n* consisting of *n* integers, and an integer *k*. You have to split the array into exactly *k* non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the *k* obtained minimums. What is the maximum possible integer you can get?
Definitions of subsegment and array splitting are given in notes.
|
```python
n,k=map(int,input().split())
ip=list(map(int,input().split()))
a=max(ip)
b=min(ip)
if k==1:
print(b)
elif k>2:
print(a)
else:
if ip[0]==a or ip[-1]==a:
print(a)
else:
if ip[0]>ip[-1]:
print(max(ip[0], min(ip[1:])))
else:
print(max(ip[-1], min(ip[:-1])))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
|
```python
n = int(input())
a = 0
m = []
for i in range(n):
x, d = map(int, input().split())
a = x + d
m.append(a)
if m.count(d) == True:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set *S*:
- its elements were distinct integers from 1 to *limit*; - the value of was equal to *sum*; here *lowbit*(*x*) equals 2*k* where *k* is the position of the first one in the binary representation of *x*. For example, *lowbit*(100102)<==<=102,<=*lowbit*(100012)<==<=12,<=*lowbit*(100002)<==<=100002 (binary representation).
Can you help Picks and find any set *S*, that satisfies all the above conditions?
|
```python
s,t = map(int,input().split())
c = {}
for i in range(1,t+1):
l = 0
tmp = i
while tmp%2==0:
tmp /= 2
l += 1
if l in c:
c[l] += 1
else:
c[l] = 1
b = bin(s)[2:][::-1]
used = {}
for i in range(len(b)):
if b[i] == '1':
if i in c and c[i] > 0:
c[i] -= 1
if i in used:
used[i] += 1
else:
used[i] = 1
else:
sm = 0
for j in range(i):
if j in c and c[j] > 0:
sm += c[j]*(2**j)
if sm < 2**i:
print(-1)
break
else:
sm = 0
for j in range(i-1,-1,-1):
if j in c and c[j] > 0:
if sm+c[j]*(2**j) == 2**i:
if j in used:
used[j] += c[j]
else:
used[j] = c[j]
c[j] = 0
sm += c[j]*(2**j)
break
elif sm+c[j]*(2**j)<2**i:
if j in used:
used[j] += c[j]
else:
used[j] = c[j]
c[j] = 0
sm += c[j]*(2**j)
else:
d = (2**i-sm)//(2**j)
if j in used:
used[j] += d
else:
used[j] = d
c[j] -= d
sm += d*(2**j)
else:
lst = []
nonz = sum([used[i] for i in used])
for i in range(1,t+1):
if nonz == 0:
break
l = 0
tmp = i
while tmp%2==0:
tmp /= 2
l += 1
if l in used and used[l] >0:
used[l] -= 1
nonz -= 1
lst.append(i)
print(len(lst))
print(*lst)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
s = input()
check = False
while s.count("h") > 1:
s = s.replace("h", "",1)
while s.count("h") == 1:
for i in s:
if i == "h":
a , b = s.split(i)
s = b
if s[0] == "e":
while s.count("e") > 1:
s = s.replace("e", "",1)
while s.count("e") == 1:
for i in s:
if i == "e":
a , b = s.split(i)
s = b
if s[0] == "l" and s[1] == "l" :
while s.count("l") > 1:
s = s.replace("l", "",1)
while s.count("l") == 1:
for i in s:
if i == "l":
a , b = s.split(i)
s = b
if s[0] == "o" :
while s.count("o") > 1:
s = s.replace("o", "",1)
while s.count("o") == 1:
for i in s:
if i == "o":
a , b = s.split(i)
s = b
check = True
if check:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The last stage of Football World Cup is played using the play-off system.
There are *n* teams left in this stage, they are enumerated from 1 to *n*. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.
Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids *a* and *b* can meet.
|
```python
n, a, b = map(int, input().split())
ans = 0
a -= 1
b -= 1
while n > 2:
n //= 2
a //= 2
b //= 2
ans += 1
if a == b:
print(ans)
break
else:
print("Final!")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole *n* ordered piles of worms such that *i*-th pile contains *a**i* worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to *a*1, worms in second pile are labeled with numbers *a*1<=+<=1 to *a*1<=+<=*a*2 and so on. See the example for a better understanding.
Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.
Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
|
```python
def solucion(num_W, label_j_W):
lista_int = []
valor = 0
lista_2 = []
for i in range(len(num_W)):
lista_int.append(valor+num_W[i])
valor += num_W[i]
label_j_W_2 = sorted(label_j_W)
for i in range(len(label_j_W_2)):
contador = lista_int[0]
for j in range(len(lista_int)):
if label_j_W_2[i] <= contador:
lista_2.append(j+1)
break
else:
if j+1 < len(lista_int):
contador = lista_int[j+1]
else:
break
for i in range(len(lista_2)):
if label_j_W[i] != label_j_W_2[i]:
print(lista_2[label_j_W_2.index(label_j_W[i])])
else:
print(lista_2[i])
def main():
'''Funcion principal'''
input()
num_W = [int(x) for x in input().split()]
input()
label_j_W = [int(x) for x in input().split()]
solucion(num_W, label_j_W)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
Now Petya is on the first stair of the staircase, consisting of *n* stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number *n* without touching a dirty stair once.
One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.
|
```python
n,m=map(int,input().split())
x=list(map(int,input().split()))
if n in x:
print("NO")
else:
for i in range(1,len(x)):
if x[i]-x[i-1]>3:
print("NO")
break
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two positive integers *a* and *b* have a sum of *s* and a bitwise XOR of *x*. How many possible values are there for the ordered pair (*a*,<=*b*)?
|
```python
for _ in range(1):
add,xor_n=map(int,input().split())
if add < xor_n:
print(0)
continue
d=add-xor_n
if d % 2==1:
print(0)
continue
d//=2
xor=bin(xor_n).replace("0b","")
sub=0
if xor_n & d==0:
if add==xor_n:
sub=2
print(2**xor.count('1')-sub)
else:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
An African crossword is a rectangular table *n*<=×<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.
When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.
You are suggested to solve an African crossword and print the word encrypted there.
|
```python
n,m=map(int,input().split()) ; arr=[]
for i in range(n):
x=input()
arr.append(x)
for h in range(n):
for i in range(m):
c=0
let=arr[h][i]
if let.isalpha():
for j in range(h+1,n):
if arr[j][i]==let:
arr[j]=arr[j].replace(let,"0") ; c+=1
if c>0:
arr[h]=arr[h].replace(let,"0")
s=""
for i in range(n):
for j in range(m):
let=arr[i][j]
if let.isalpha():
if arr[i].count(let)>1:
arr[i]=arr[i].replace(let,'0')
else:
s+=let
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
|
```python
import sys
def parse_line(line):
line = line.strip().split()
name = line[0]
score = int(line[1])
return name, score
def update_scores(name, score, scores, winner):
if name not in scores:
scores[name] = score
else:
scores[name] += score
if winner == '':
winner = name
else:
if scores[name] > scores[winner]:
winner = name
return winner
lines = sys.stdin.readlines()
rounds = int(lines[0].strip())
scores = {}
winner = ''
for round in range(1, rounds+1):
name, score = parse_line(lines[round])
winner = update_scores(name, score, scores, winner)
print(winner)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
|
```python
n = int(input())
def dd(n):
if len(str(n)) != len(set(list(str(n)))):
return False
else:
return True
n += 1
while not dd(n):
n += 1
print(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
|
```python
from sys import stdin
_input = stdin.readline
_int = int
count, cnt = [_int(i) for i in _input().split()]
k, m = [_int(i) for i in _input().split()]
a = [_int(i) for i in _input().split()]
b = [_int(i) for i in _input().split()]
a = a[k-1]
b = b[cnt - m]
if a < b:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*.
|
```python
n,m=map(int,input().split())
f=list(map(int,input().split()))
f.sort()
least=f[n-1]-f[0]
for i in range(1,m-n+1):
dif=f[i+n-1]-f[i]
if dif<least:
least=dif
print(least)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Imp likes his plush toy a lot.
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly *x* copied toys and *y* original toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies.
|
```python
# -*- coding:utf-8 -*-
if __name__ == '__main__':
x, y = map(int, input().split())
def get_res(x, y):
if y < 0:
return "No"
r = x - y + 1
if r < 0:
return "No"
if r % 2 != 0:
return "No"
return "Yes"
print(get_res(x, y))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly *x* Roman soldiers, where *x* is a prime number, and next day they beat exactly *y* Roman soldiers, where *y* is the next prime number after *x*, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat *n* Roman soldiers and it turned out that the number *n* was prime! Today their victims were a troop of *m* Romans (*m*<=><=*n*). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
|
```python
n,m=map(int,input().split())
ans=m-n
sum=0
if n==2 and m==3:
print('YES')
else:
for i in range(1,m+1):
if m%i==0:
sum+=1
if sum>2:
print('NO')
else:
if ans==2 or ans==4:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions."
Could you pass the interview in the machine vision company in IT City?
|
```python
a=input()
b=5**int(a)
lasttwodigit=b%100
print(lasttwodigit)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*.
As Petya is older, he wants to take the chores with complexity larger than some value *x* (*h**i*<=><=*x*) to leave to Vasya the chores with complexity less than or equal to *x* (*h**i*<=≤<=*x*). The brothers have already decided that Petya will do exactly *a* chores and Vasya will do exactly *b* chores (*a*<=+<=*b*<==<=*n*).
In how many ways can they choose an integer *x* so that Petya got exactly *a* chores and Vasya got exactly *b* chores?
|
```python
# Wadea #
n,a,b=map(int ,input().split())
arr=list(map(int ,input().split()))
arr.sort()
k=arr[b-1]
g=arr[b]
print(int(abs(k-g)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
N,M = input().split()
print(int(N)*int(M)//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.
Your task is to find the number of successful students in the group.
|
```python
n,m = map(int,input().split())
ll = []
l = [0] * m
for i in range(n):
ll.append(input().strip())
for j in range(m):
l[j] = max(l[j],int(ll[-1][j]))
ans = 0
for i in ll:
for j in range(m):
if int(i[j]) == l[j]:
ans += 1
break
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.
The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.
Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
|
```python
a=input()
a=list(a)
b=input()
b=list(b)
c=input()
l=list(c)
for i in a:
if i in l:
l.remove(i)
a.remove(i)
for i in b:
if i in l:
l.remove(i)
b.remove(i)
print('YES' if len(l)==0 and len(a)==0 and len(b)==0 else 'NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
|
```python
# -*- coding: utf-8 -*-
"""Codeforce
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1vkqd1IDYYeIi4VIH6yqQEhbS4qcGMzLO
"""
n , m = map(int , input().split())
tv_price = list(map(int , input().split()))
tv_price = sorted(tv_price)
earning = 0
for i in range(m):
if tv_price[i] < 0:
earning += tv_price[i]
else:
break
print(earning)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers.
Unfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array *a* (in increasing order) by reversing exactly one segment of *a*? See definitions of segment and reversing in the notes.
|
```python
n=int(input())
A=input().split()
N={}
for x in range(n):
N[int(A[x])]=x
M=sorted(N.items())
P=[]
Q=[]
for x in range(n):
if x!=M[x][1]:
P.append(M[x][1])
Q.append(x)
if P==sorted(Q, reverse=True):
print('yes')
else:
print('no')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
Now Petya is on the first stair of the staircase, consisting of *n* stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number *n* without touching a dirty stair once.
One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.
|
```python
n, m=map (int, input ().split ())
l=[]
if m>0:
k=list(map (int, input ().split ()))
l=k
if (1 in l) or (n in l):
print ('NO')
elif m==0:
print ('YES' )
else:
l.sort()
flag =0
for i in range(m-2):
if l[i+1]-l[i] ==1 and l[i+2]-l[i+1] ==1:
flag=1
break
if flag ==1:
print ('NO')
else:
print ('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time *x* (in seconds), so he asked you to tell him if it's gonna bark at that time.
|
```python
t,s,x=map(int,input().split())
i=1
while i<x:
if t==x or t+s==x or t+s+1==x or t+(i*s)==x or t+(i*s)+1)==x:
print("YES")
else:
print("NO")
i=i+1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.
|
```python
m, d = map(int, input().split())
lst = [4,6,9,11]
lst1 = [1,3,5,7,8,10,12]
lst2 = [2]
if m in lst:
if d == 7:
print(6)
else:
print(5)
elif m in lst1:
if d >= 6:
print(6)
else:
print(5)
elif m in lst2:
if d == 1:
print(4)
else:
print(5)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?
|
```python
n=int(input())
a=list(map(int,input().split()))
k=sum(a)%2
c=0
for i in range(n):
if a[i]%2==k:
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...
|
```python
x = input()
if ("h" in x):
if ("e" in x):
if ("i" in x):
if ("d" in x):
if ("i" in x):
print ("YES")
else:
print ("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The following problem is well-known: given integers *n* and *m*, calculate
where 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*.
You are asked to solve the "reverse" problem. Given integers *n* and *m*, calculate
|
```python
n = int(input())
m = int(input())
if m == 1:
print(1)
else:
x = str(bin(m))
print(int(x[-n:],2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
|
```python
s = input()
c = len(s)-1
if (s[c].isalpha()):
if (s[c].upper()=='A' or s[c].upper()=='E' or s[c].upper()=='I' or s[c].upper()=='O' or s[c].upper()=='U' or s[c].upper()=='Y'):
print("YES")
exit()
else:
print("NO")
exit()
else:
if (s[c-1].upper()=='A' or s[c-1].upper()=='E' or s[c-1].upper()=='I' or s[c-1].upper()=='O' or s[c-1].upper()=='U'or s[c-1].upper()=='Y'):
print("YES")
exit()
else:
print("NO")
exit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's and Eeyore's house is *b* meters, between Owl's and Eeyore's house is *c* meters.
For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal *n* times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).
Winnie-the-Pooh does not like physical activity. He wants to have a meal *n* times, traveling minimum possible distance. Help him to find this distance.
|
```python
from sys import stdin, stdout
from functools import reduce
def main():
n=int(stdin.readline().strip())-1
a=int(stdin.readline().strip())
b=int(stdin.readline().strip())
c=int(stdin.readline().strip())
if n<=0: return 0
x=min(a, min(b, c))
if x==a or x==b: return x*n
else: return min(a,b)+c*n-1
stdout.write(str(main()))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
|
```python
n = int(input())
a = [int(x) for x in input().split()]
ans = 0
mn = mx = a[0]
for x in a:
if x > mx:
ans += 1
mx = x
if x < mn:
ans += 1
mn = x
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?
|
```python
n, k = map(int, input().split())
arr= list(map(int, input().split()))
count = 0
for i in arr:
if 5-i >= k:
count += 1
ans= count // 3
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky.
|
```python
s=input()
c=0
for i in s:
if i=='4' or i=='7':
c+=1
l=[4,7,47,74,447,444,474,744,747,774,477]
d=0
for j in l:
if int(s)>j:
if int(s)%j==0:
d+=1
if d!=0 or c==len(s):
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
a=int(input())
b=[]
for i in range(a):
b.append(list(map(int,input().split(" ")[:3])))
r=0
for j in range(len(b)):
r=r+sum(b[j])
if(r==0):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
import math
m,n,a=map(int,input().split())
x=math.ceil(m/a)
y=math.ceil(n/a)
if x>1 and y>1:
t=x+y
if x<=1 and y<=1:
t=1
if x>1 and y<=1:
t=x
if x<=1 and y>1:
t=y
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3<=×<=3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
|
```python
a=input()
b=input()
c=input()
a=list(a)
b=list(b)
c=list(c)
if c[::-1]==a:
print("YES")
elif b[0]==b[2]:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One spring day on his way to university Lesha found an array *A*. Lesha likes to split arrays into several parts. This time Lesha decided to split the array *A* into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array *A*.
Lesha is tired now so he asked you to split the array. Help Lesha!
|
```python
#For fast I/O
import sys
input = lambda: sys.stdin.readline().strip()
n = int(input())
l = [int(i) for i in input().split()]
s = sum(l)
if s != 0:
print('YES')
print(1)
print(1,n)
else:
possible = False
for i in range(n):
if l[i] != 0:
possible = True
print('YES')
print(2)
print(1,i+1)
print(i+2,n)
break
if not possible:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 and *d* are any numbers.
Geometric progression is a sequence *b*1, *b*2<==<=*b*1*q*, ..., *b**n*<==<=*b**n*<=-<=1*q*, where *b*1<=≠<=0, *q*<=≠<=0, *q*<=≠<=1.
Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.
|
```python
numbers = list(map(int,input().split()))
arithmetic_prog = numbers[1] - numbers[0]
geometric_prog = numbers[1] / numbers[0]
if numbers[3]-numbers[2] == arithmetic_prog and numbers[2]-numbers[1] == arithmetic_prog:
print(int(numbers[-1]+arithmetic_prog))
elif numbers[3]/numbers[2] == geometric_prog and numbers[2]/numbers[1] == geometric_prog:
print(int(numbers[-1]*geometric_prog))
else:
print(42)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
|
```python
k,n,w=map(int,input().split())
sum=0
tc=0
for i in range(w+1):
sum=sum+i
tc=sum*k
print(tc-n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find the maximum possible least common multiple of these three integers?
|
```python
from math import gcd
n = int(input())
if n <= 3:
print([0, 1, 2, 6][n])
exit()
print(
max(
n * (n-1) * (n-2) // gcd(n, n-2),
(n-1) * (n-2) * (n-3) // gcd(n-1, n-3)
)
)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete *k*<=-<=1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.
Overall, Dima has *n* tasks to do, each task has a unique number from 1 to *n*. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.
Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
|
```python
def read():
n, k = list(map(int, input().split()))
powers = list(map(int, input().split()))
return n, k, powers
def get_min_power(n, k, powers):
start_task = 0
mins = []
for i in range(k):
s = 0
for j in range(i, n, k):
s += powers[j]
mins.append(s)
task = min(mins)
return mins.index(task) + 1
def main():
n, k, powers = read()
print(get_min_power(n, k, powers))
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
An *n*<=×<=*n* table *a* is defined as follows:
- The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1.
These conditions define all the values in the table.
You are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.
|
```python
n = int(input())
x = [0,1,2,6,20,70,252,924,3432,12870,48620]
print(x[n])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.
A substring *s*[*l*... *r*] (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) of string *s*<==<=*s*1*s*2... *s*|*s*| (where |*s*| is the length of string *s*) is the string *s**l**s**l*<=+<=1... *s**r*. The empty string is a substring of any string by definition.
You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.
|
```python
'''input
((()))([]
'''
from sys import stdin
def check_valid(string):
stack = []
for i in string:
if i in ['(', '[']:
stack.append(i)
elif i == ')':
if len(stack) > 0:
if stack[-1] == '(':
stack.pop()
continue
return False
elif i == ']':
if len(stack) > 0:
if stack[-1] == '[':
stack.pop()
continue
return False
return len(stack) == 0
def merge(index):
# refining
aux = []
if len(index) > 0:
start = index[0][0]
end = index[0][1]
for i in range(1, len(index)):
s, e = index[i]
if e <= end:
pass
elif s >= end:
aux.append([start, end])
start, end = s, e
aux.append([start, end])
index = aux
# acutal merging
aux = []
if len(index) > 0:
aux = [index[0]]
for i in range(1, len(index)):
if index[i][0] == aux[-1][1] + 1:
aux[-1][1] = index[i][1]
else:
if check_valid(string[aux[-1][1] + 1: index[i][0]]):
aux[-1][1] = index[i][1]
else:
aux.append(index[i])
return aux
# main starts
string = stdin.readline().strip()
stack = []
index = []
start = -1
end = -1
for i in range(len(string)):
if string[i] == '(':
stack.append(i)
elif string[i] == '[':
stack.append(i)
elif string[i] == ')':
if len(stack) > 0 and string[stack[-1]] == '(':
index.append([stack[-1], i])
stack.pop()
else:
stack = []
elif string[i] == ']':
if len(stack) > 0 and string[stack[-1]] == '[':
index.append([stack[-1], i])
stack.pop()
else:
stack = []
index.sort(key = lambda x:(x[0], x[1]))
index = merge(index)
diff = 0
ans = [-1, -1]
for i in index:
start, end = i
c = string[start: end + 1].count('[')
if diff < c :
ans = [start, end + 1]
diff = c
print(diff)
print(string[ans[0]: ans[1]])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given the current time in 24-hour format hh:mm. Find and print the time after *a* minutes.
Note that you should find only the time after *a* minutes, see the examples to clarify the problem statement.
You can read more about 24-hour format here [https://en.wikipedia.org/wiki/24-hour_clock](https://en.wikipedia.org/wiki/24-hour_clock).
|
```python
l1 = [int(x) for x in input().split(":")]
n = int(input())
final = l1[0]*60+l1[1]+n
total = 24*60
thing = final%total
print(str(int(thing/60))+str(":")+str(thing%60))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kitahara Haruki has bought *n* apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.
But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
|
```python
x = int(input())
from collections import Counter
y = map(int,input().split())
y = Counter(y)
# print(y)
s = y[100]+y[200]*2
# print(s)
if s%2:
print("NO")
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$.
Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$.
Note that the modulo is unusual!
|
```python
n, a, b, k = map(int,input().split())
s = input()
i = 0
su = []
for i in range(k):
t = 0
if s[i] == '+':
for j in range(n // k + 1):
if 0 <= n-k*j-i <= n:
t += pow(a, n-k*j-i, 10**9+9)*pow(b, k*j+i, 10**9+9)
else:
for j in range(n // k + 1):
if 0 <= n-k*j-i <= n:
t -= pow(a, n-k*j-i, 10**9+9)*pow(b, k*j+i, 10**9+9)
su.append(t)
print(sum(su) % (10**9+9))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:
- Assume that the rows are numbered 1 to *n* from top to bottom and the columns are numbered 1 to *m* from left to right, and a cell in row *i* and column *j* is represented as (*i*,<=*j*). - First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,<=1)<=→<=...<=→<=(1,<=*m*)<=→<=(2,<=1)<=→<=...<=→<=(2,<=*m*)<=→<=...<=→<=(*n*,<=1)<=→<=...<=→<=(*n*,<=*m*). Waste cells will be ignored. - Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on.
The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.
Now she is wondering how to determine the crop plants in some certain cells.
|
```python
def mi():
return map(int, input().split())
n,m,k,t = mi()
wasterowscount = [0]*(n+1)
d = {0:'Carrots',1:'Kiwis',2:'Grapes'}
waste = [[]]*(n+1)
def fun(x,y):
global waste
if y in waste[x]:
print ('Waste')
return 0
cur = (((x-1)*m-wasterowscount[x-1]))
cur+=(y)
for i in range(wasterowscount[x]-wasterowscount[x-1]):
if waste[x][i]<y:
cur-=1
cur-=1
cur%=3
print (d[cur])
for i in range(len(waste)):
waste[i] = waste[i][:]
for i in range(k):
x,y = mi()
waste[x].append(y)
wasterowscount[x] += 1
for i in range(2,len(wasterowscount)):
wasterowscount[i] += wasterowscount[i-1]
for i in range(t):
x,y = mi()
fun(x,y)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
T=input()
countU=0
countL=0
for i in range(len(T)):
if T[i].islower()==True:
countL+=1
else:
countU+=1
if countL==countU:
print(T.lower())
if countL>countU:
print(T.lower())
if countL<countU:
print(T.upper())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
An *n*<=×<=*n* table *a* is defined as follows:
- The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1.
These conditions define all the values in the table.
You are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.
|
```python
#get input
#n=5
n=int(input())
table=[]
##Making the appropriate table
#make nxn table following the given rule
for i in range(n):
table.append([])
#appending 1s in the first row
for i in range(n):
table[0].append(1)
#appending 1s at first column of each row except the first row
for y in range(1,n):
table[y].append(1)
#filling remaining number position with zeros so it can be filled later with appropriate values
for i in range(1,n):
for y in range(n-1):
table[i].append(0)
#creating the remaining numbers
for row in range(1,n):
for col in range(1,n):
table[row][col]=table[row][col-1]+table[row-1][col]
###########################################################################
#Find the maximum value in the entire n*n table
maximum=table[0][0]
for row in table:
for col in row:
if(col>maximum):
maximum=col
print(maximum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a connected weighted undirected graph without any loops and multiple edges.
Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.
Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST.
|
```python
N = 100010
n, m = map(int, input().split())
x = [0] * (N)
y = [0] * (N)
z = [0] * (N)
p = [0] * (N)
ans = [0] * (N)
f = [False] * (N)
h = [0] * (N)
pe = [0] * (N)
d = [0] * (N)
v = [[] for _ in range(N)]
# Função para comparar arestas com base em seus pesos (z)
def cmp(i, j):
return z[i] < z[j]
# Função para encontrar o representante de um conjunto
def par(x):
while pe[x]:
x = pe[x]
return x
# Função para unir dois conjuntos
def uni(x, y):
x = par(x)
y = par(y)
v[x].clear()
v[y].clear()
f[x] = False
f[y] = False
if x == y:
return
if h[x] > h[y]:
pe[y] = x
else:
pe[x] = y
if h[x] == h[y]:
h[y] += 1
# Função para adicionar uma aresta ao grafo
def add_edge(x, y, i):
if x == y:
return
ans[i] = 1
v[x].append((y, i))
v[y].append((x, i))
# Função de busca em profundidade (DFS)
def dfs(c, g, h):
f[c] = True
d[c] = h
for i in v[c]:
if not f[i[0]]:
dfs(i[0], i[1], h + 1)
d[c] = min(d[c], d[i[0]])
elif i[1] != g:
d[c] = min(d[c], d[i[0]])
if d[c] == h:
ans[g] = 2
# Leitura das informações das arestas
for i in range(1, m + 1):
x[i], y[i], z[i] = map(int, input().split())
p[i] = i
# Ordena as arestas com base em seus pesos
p.sort(key=lambda i: z[i])
i = 1
while i <= m:
j = i
while j <= m and z[p[j]] == z[p[i]]:
add_edge(par(x[p[j]]), par(y[p[j]]), p[j])
j += 1
j = i
while j <= m and z[p[j]] == z[p[i]]:
k = par(x[p[j]])
if not f[k]:
dfs(k, 0, 0)
j += 1
j = i
while j <= m and z[p[j]] == z[p[i]]:
uni(x[p[j]], y[p[j]])
j += 1
i = j
# Imprime o tipo de conectividade para cada aresta
for i in range(1, m + 1):
if ans[i] == 0:
print("none")
elif ans[i] == 1:
print("at least one")
else:
print("any")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.
Now each knight ponders: how many coins he can have if only he kills other knights?
You should answer this question for each knight.
|
```python
import heapq
if __name__ == '__main__':
rd = lambda: map(int, input().split())
n, k = rd()
a = sorted(zip(rd(), rd(), range(n)))
minH = []
total = 0
ans = [0] * n
for i in range(len(a)):
if len(minH) >= k + 1:
(coins, index) = heapq.heappop(minH)
total -= coins
heapq.heappush(minH, (a[i][1], i))
total += a[i][1]
ans[a[i][2]] = total
print(*ans)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.