source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and ...
```python l,r,a=map(int,input().split()) if l>=r: n=r*2 l-=n if l>=a: n+=(a*2) else: n+=(a//2)*2 else: n=l*2 r-=n if r>=a: n+=(a*2) else: n+=(a//2)*2 print(n) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
```python print("will do it") ```
MatrixStudio/Codeforces-Python-Submissions
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname...
```python def search(D,p,ln): k = p+1 #print(k) for i in range(ln): if k>=D[i][0] and k<=D[i][1] and k != D[i][2]: return(D[i][2]) return(0) def main(): D = [] Result = [] L = list(map(int,input().split())) ln = L[1] for i in range(ln): D.append(list(map(int,input().split()))) #print(D...
MatrixStudio/Codeforces-Python-Submissions
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
```python # LUOGU_RID: 112614184 s = str(input()) n = len(s) print(26 * (n + 1) - n) ```
MatrixStudio/Codeforces-Python-Submissions
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
```python import functools class Point: def __init__(self, x, y): self.x = x self.y = y def squared_distance(self, another_point): return (self.x - another_point.x) ** 2 + (self.y - another_point.y) ** 2 class SnowBlower: def solution(self): first_line =...
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...
```python s = input() countQPassed = 0 countQNotPassed = len([x for x in s if x == 'Q']) countRes = 0 for x in s: if x == 'A': countRes += countQPassed * countQNotPassed elif x == 'Q': countQPassed += 1 countQNotPassed -= 1 print(countRes) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a permutation *p* of length *n*. Remove one element from permutation to make the number of records the maximum possible. We remind that in a sequence of numbers *a*1,<=*a*2,<=...,<=*a**k* the element *a**i* is a record if for every integer *j* (1<=≤<=*j*<=&lt;<=*i*) the following holds: *a**j*<=&lt;<=*a*...
```python def find_max_records_to_remove(n, p): records = [] max_records = 0 max_records_element = 0 for i in range(n): if i == 0 or p[i] > p[i - 1]: records.append(i) for i in range(len(records)): remove_element1 = p[records[i]] remove_element2 = p[recor...
MatrixStudio/Codeforces-Python-Submissions
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes...
```python import re in1 = int(input()) in2 = re.split("\\s", input()) test = {} count = 0 for x in in2: test[x] = count count += 1 print(min(test, key=test.get)) ```
MatrixStudio/Codeforces-Python-Submissions
Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the *N* attendees love to play a very risky game... Every zombie gets a number *n**i* (1<=≤<=*n**i*<=≤<=*N*) written on his forehead. Although no zombie can see his own...
```python t = int(input()) for i in range(t): n, r = map(int, input().split()) l = list(map(int, input().split())) if r == 1: s = sum(l) % n if s == 0: s = n print(s) else: s = 2 * l[0] - r + 1 - sum(l) s = s % n if s == 0: ...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python n = int(input()) for i in range(n): x = input() g = len(x) if g <= 10: print(st) else: print(x[0], g - 2, x[g - 1], sep="") ```
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
```python a=list(map(int,input().split()))[:4] s=str(input()) sum=0 for i in s: if i =='1': sum+=a[0] elif i =='2': sum+=a[1] elif i=='3': sum+=a[2] elif i=='4': sum+=a[3] print(sum) ```
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 Vasy...
```python n = int(input()) a,b,c = 0,0,0 for i,j,k in [int(x) for x in input().split()]: a += i b+=j c +=k if a == 0 and b ==0 and c==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array consisting of *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to *n* defining the order elements of the array are destroyed. After each element is destroyed you have to find o...
```python h=int(input()) l=[*map(int,input().split())] d=[*map(int,input().split())] o=2 for i in range(h): for j in range(h): l[d[j] - 1] = -1 sums=[] x=0 y=0 for k in range(o): while l[x]!=-1 : y+=l[x] x+=1 ...
MatrixStudio/Codeforces-Python-Submissions
Hands that shed innocent blood! There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=&lt;<=*i* and *...
```python n=int(input()) a=list(map(int,input().split())) b=0 if n==1: print(1) else: ans=0 for i in range(n-1,-1,-1): if b==0: ans+=1 #print(b,'b',b-1,'b-1',a[i],'a[i]',i,'i') b=max(b-1,a[i],0) #print('b',b) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and his friends went to a picnic. The guys had *n* soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the *i*-th bottle is from brand *a**i*, besides, you can use it to open other bottles of brand *b**i*. You can use...
```python x,y,c=0,0,0 for i in range(int(input())): a,b=map(int, input().split()) if b-a==0: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i...
```python n=int(input()) l=list(map(lambda x : int(x)%2 ,input().split())) s=sum(l[:3]) x=-1 if s<=1:x=1 else:x=0 for i in range(n): if l[i]==x:break print(1+i) ```
MatrixStudio/Codeforces-Python-Submissions
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all ...
```python lis=input().split() n,m=map(int,lis[:-1]) c=lis[-1] ans=['0'*(m+2)] l=[] b={'0','.',c} for i in range(n): ans.append('0'+input()+'0') ans.append('0'*(m+2)) for i in range(n): for j in range(m): if ans[i+1][j+1]==c: l.append(ans[i+1][j]) l.append(ans[i+1][j+2]) ...
MatrixStudio/Codeforces-Python-Submissions
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be *n* interesting minutes *t*1,<=*t*2,<=......
```python input();s=0 for i in map(int,input().split()): if i-s>15:break else:s=i print([s+15,90][(s+15)>90]) ```
MatrixStudio/Codeforces-Python-Submissions
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rec...
```python a1,b1 = map(int,input().split()) a2,b2 = map(int,input().split()) a3,b3 = map(int,input().split()) n2 = [a2,b2] n3 = [a3,b3] l = [] for d2 in range(2): for d3 in range(2): l.append([n2[d2]+n3[d3],max(n2[d2-1],n3[d3-1])]) def c(l,a1,b1): a = False for i in l: if a1 >= i[...
MatrixStudio/Codeforces-Python-Submissions
You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to deter...
```python n = int(input()) s = input() balance_indices = {0: -1} balance = 0 max_length = 0 for i in range(n): if s[i] == '0': balance -= 1 else: balance += 1 if balance in balance_indices: max_length = max(max_length, i - balance_indices[balance]) else: bal...
MatrixStudio/Codeforces-Python-Submissions
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
```python if __name__=='__main__': s_arr = input() n_arr = [] for i in s_arr: n_arr.append(i) # print(s_arr, n_arr) ab = 0 ba = 0 for i in range(len(n_arr)-1): c = n_arr[i] # print(c) if c == 'A' and n_arr[i+1] == 'B': # print("ab cas...
MatrixStudio/Codeforces-Python-Submissions
The Easter Rabbit laid *n* eggs in a circle and is about to paint them. Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied: - Each of the seven colors should be used to paint at least one egg. - Any four eggs lying s...
```python n=int(input()) c="ROYGBIV" if n%7: m=n//7+1 c*=m print(c[:n]) else: m=n//7 print(c*m) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there. If...
```python #Presents n=int(input()) arr=[int(i) for i in input().split()] ans=[] respuesta = "" for i in range(n+1): ans.append(0) for i in range(0,n): ans[arr[i]] = i+1 for i in range(1,len(ans)): respuesta+=str(ans[i]) print(respuesta) ```
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 set...
```python n, m = map(int, input().split()) tv = list(map(int, input().split())) tv.sort() result = 0 for i in range(m): result -= tv[i] print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a*...
```python n, arr = int(input()), [int(t) for t in input().split()] ub = max(arr) count, dp = [0] * (ub + 1), [0] * (ub + 1) for i in arr: count[i] += i dp[1], dp[2] = count[1], count[2] for i in range(3, ub + 1): dp[i] = count[i] + max(dp[i - 2], dp[i - 3]) print(max(dp[-1], dp[-2])) ```
MatrixStudio/Codeforces-Python-Submissions
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have *n* layers. The first layer is hate, se...
```python print(" that ".join(["I hate","I love"][i%2] for i in range(int(input()))),end=" it\n") ```
MatrixStudio/Codeforces-Python-Submissions
Masha and Grisha like studying sets of positive integers. One day Grisha has written a set *A* containing *n* different integers *a**i* on a blackboard. Now he asks Masha to create a set *B* containing *n* different integers *b**j* such that all *n*2 integers that can be obtained by summing up *a**i* and *b**j* for al...
```python def get_numbers(numbers): result_numbers = [] tmp = [] for i in range(1, 10 ** 6): if len(result_numbers) == len(numbers): break for elem in numbers: summ = i + elem #print(not (summ in tmp or i in result_numbers), i, result_numbers) if not (summ in tmp or i in result_numbers): tmp.ext...
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo adores strings. But most of all he adores strings of length *n*. One day he wanted to find a string that meets the following conditions: 1. The string consists of *n* lowercase English letters (that is, the string's length equals *n*), exactly *k* of these letters are distinct. 1. No two neighbo...
```python n,k = map(int,input().split()) if n<k: print(-1) else: L = [chr(ord('a') + 2 + i) for i in range(k)] end = "".join(L) s = 'ab'*((n-k)//2) if (n-k)%2 == 0: print(s + end) else: print(s + 'a' + end) ```
MatrixStudio/Codeforces-Python-Submissions
You are given the string *s* of length *n* and the numbers *p*,<=*q*. Split the string *s* to pieces of length *p* and *q*. For example, the string "Hello" for *p*<==<=2, *q*<==<=3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo". Note it is allowed to split the string *s* to the st...
```python n, p, q = map(int, input().split()) s = str(input()) for i in range(101): for j in range(101): if p*i+q*j == n: ans = [] for k in range(i): ans.append(s[p*k:p*(k+1)]) for l in range(j): ans.append(s[p*i+q*l:p*i+q*(l+1)]) ...
MatrixStudio/Codeforces-Python-Submissions
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of *n* elements. Petya immediately decided to find there a segment of consecutive elements, such that the *xor* of all numbers from this segment was maximal possible. Help him with that. ...
```python n = int(input()) array = input().split() maximum = 0 possible_max = 0 for number in array: possible_max = maximum ^ int(number) if possible_max > maximum: maximum = possible_max if int(number) > maximum: maximum = int(number) print(maximum) ```
MatrixStudio/Codeforces-Python-Submissions
There is a given sequence of integers *a*1,<=*a*2,<=...,<=*a**n*, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.
```python n=int(input()) l=list(map(int, input().split()))[:n] x=[] x.append(l.count(1)) x.append(l.count(2)) x.append(l.count(3)) x.sort() print(x[0]+x[1]) ```
MatrixStudio/Codeforces-Python-Submissions
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr ...
```python n = int(input()) a = [int(x) - 1 for x in input().split()] ans = 0 for i in range(n): if a[i] == -1: continue ans ^= 1 x = i while x != -1: y = a[x] a[x] = -1 x = y if ans: print("Um_nik") else: print("Petr") ```
MatrixStudio/Codeforces-Python-Submissions
Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not. You are to place a spotlight on the stage in some good position. The spotlight will project light in one of t...
```python n, m=map(int, input().split()) a=[list(map(int, input().split())) for _ in range(n)] ans=p=0 def f(x): global ans, p if x==0: ans+=p else: p=1 for i in range(n): p=0 for j in range(m): f(a[i][j]) p=0 for j in range(m-1, -1, -1): f(...
MatrixStudio/Codeforces-Python-Submissions
Vasily has a deck of cards consisting of *n* cards. There is an integer on each of the cards, this integer is between 1 and 100<=000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number...
```python n = int(input()) f = [] for i in range(n): avg = int(input()) y=[avg,i+1] f.append(y) f.sort() last = -1 ans = 0 numberContinueing = 0 for i in f: if(i[1]>last): last = i[1] numberContinueing+=1 else: ans+=n n-=numberContinueing numberContinueing=1 last = i[1] print(ans+n...
MatrixStudio/Codeforces-Python-Submissions
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choos...
```python n,m,k=map(int,input().split()) p,matrix=0,[[0 for _ in range(m+2)]for _ in range(n+2)] l=[[1,1],[-1,1],[1,-1],[-1,-1]] for q in range(1,1+k): i,j=map(int,input().split()) matrix[i][j]=1 if sum([matrix[i][j],matrix[i+p[0]][j],matrix[i][j+p[1]],matrix[i+p[0]][j+p[1]]]==[1,1,1,1]for p in l)...
MatrixStudio/Codeforces-Python-Submissions
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
```python l=list(map(int,list(input()))) c=[] t=len(l) for x in range(9): s='' for x in range(t): if l[x]>0: l[x]-=1 s+='1' else: s+='0' c.append(int(s)) if c[-1]==0: c.pop();break print(len(c)) print(*c) ```
MatrixStudio/Codeforces-Python-Submissions
The input contains a single integer *a* (1<=≤<=*a*<=≤<=40). Output a single string.
```python a = int(input()) pr = ['Washington', 'Adams', 'Jefferson', 'Madison', 'Monroe', 'Quincy Adams', 'Jackson', 'Van Buren', 'Henry Harrison', 'Tyler', 'Polk', 'Taylor', 'Fillmore', 'Pierce', 'Buchanan', 'Lincoln', 'Johnson', 'S. Grant', 'B. Hayes', 'A. Garfield', 'A. Arthur', 'Cleveland', 'Harrison', 'Cleveland'...
MatrixStudio/Codeforces-Python-Submissions
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)). Max starts to type all the values from *a* to *b*. After typi...
```python a,b=map(int,input().split()) count=0 dict={"0":6,"6":6,"9":6,"1":2,"2":5,"3":5,"4":4,"5":5,"7":3,"8":7} for i in range(a,b+1): i=str(i) for j in range(len(str(i))): count+=dict[i[j]] print(count) ```
MatrixStudio/Codeforces-Python-Submissions
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes. A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people....
```python k,n,s,p=map(int,input().split()) q=s i=1 while q<n: q=s q*=i i+=1 sheets_required_per_person=q total_no_of_sheets=q*k packs=1 while total_no_of_sheets>(p*packs*s): packs+=1 print(packs) ```
MatrixStudio/Codeforces-Python-Submissions
Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды. Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть *n* точек, где можно взять велосипед в прокат и...
```python helper = 0 n = '' k = '' myList = [] firstData = input() for i in firstData: if i != ' ' and helper == 0: n += i elif i != ' ': k += i else: helper += 1 n = int(n) k = int(k) helper = 0 helpStr = '' secondData = input() for i in secondData: if i != ' ': helper = 0 helpStr...
MatrixStudio/Codeforces-Python-Submissions
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*. You ...
```python n, val = int(input()), 0 for x, y in zip(sorted(int(x) for x in input().split()), range(1, n + 1)): val += abs(x - y) print(val) ```
MatrixStudio/Codeforces-Python-Submissions
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
```python a = input() print(a[0].capitalize() + a[1:]) ```
MatrixStudio/Codeforces-Python-Submissions
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are *n* pages numbered by integers from 1 to *n*. Assume that somebody is on the *p*-th page now. The navigation will look like this: When someone clicks the button "&lt;&lt;" he is redirected to page 1, and wh...
```python X = list(map(int, input().split())) Pages = [str(i + 1) for i in range(X[0])] Pages[X[1] - 1] = '(' + Pages[X[1] - 1] + ')' if X[-1] <= X[1] - X[-1]: print("<< ", end="") print(*Pages[max(0, X[1] - X[-1] - 1):min(X[0], X[1] + X[-1])], end=" ") if X[1] < X[0] - X[-1]: print(">>") # Caption: G...
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
```python n=int(input()) price=[] quility=[] flag=True for _ in range(n): a,b=map(int,input().split()) price.append(a) quility.append(b) for i in range(n): if price[i]<price[i-1] and quility[i]>quility[i-1]: flag=True break else: flag=False print("Happy Alex")...
MatrixStudio/Codeforces-Python-Submissions
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ...
```python A,B = map(int, input().split()) x,y,z = map(int, input().split()) A1 = 2*x + y - A B1 = 3*z + y - B final = 0 if A1 > 0: final = final + A1 if B1 > 0: final = final + B1 print(final) ```
MatrixStudio/Codeforces-Python-Submissions
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square. A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
```python n=int(input()) a=list(map(int,input().split())) a.sort() for i in range(n): if math.sqrt(a[n-i-1])%1!=0: print(a[n-1-i]) exit() ```
MatrixStudio/Codeforces-Python-Submissions
You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.
```python from collections import Counter m,n=list(map(int,input().split())) a=list(map(int,input().split())) b=list(map(int,input().split())) res=[] counter=Counter(a) sortedKeys=sorted(counter.keys()) for num in b: sum=0 for x in sortedKeys: if x>num: break sum+=counter[x] res....
MatrixStudio/Codeforces-Python-Submissions
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." The problem is: You ar...
```python from sys import stdin; inp = stdin.readline from math import dist, ceil, floor, sqrt, log def IA(): return list(map(int, inp().split())) def FA(): return list(map(float, inp().split())) def SA(): return inp().split() def I(): return int(inp()) def F(): return float(inp()) def S(): return inp() from it...
MatrixStudio/Codeforces-Python-Submissions
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane...
```python a = [0] * 4 for i in range(4): a[i] = list(map(int, input().split())) if a[0][3] == 1: if a[3][3] or a[1][0] or a[2][1] or a[0][0] or a[0][1] or a[0][2]: print('YES') else: print('NO') elif a[1][3] == 1: if a[1][0] or a[1][1] or a[1][2] or a[0][2] or a[2][0] or a...
MatrixStudio/Codeforces-Python-Submissions
For a positive integer *n* let's define a function *f*: *f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n* Your task is to calculate *f*(*n*) for a given integer *n*.
```python n=int(input()) sum_e=0 sum_o=0 for i in range(1,n+1): if i%2==0: sum_e=sum_e+i else: sum_o=sum_o-i sum_t=sum_e+sum_o print(sum) ```
MatrixStudio/Codeforces-Python-Submissions
The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. *n* best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. *n*·(*n*<=-<=1)<=/<=2 games were played during the tournament, and each participa...
```python def solve(): n = int(input().strip()) v = [x for x in range(1, n + 1)] count = [0 for x in range(1, n + 1)] won = [0 for x in range(1, n + 1)] for i in range(int(n * (n - 1) / 2) - 1): a, b = map(int, input().split()) count[a - 1] += 1 count[b - 1] +...
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()) m=[] num=0 for i in range(0,n): m=list(map(int,input().split())) for i in range(0,len(m)): if(a[i]>k): num=num+1 break print(num) ```
MatrixStudio/Codeforces-Python-Submissions
A bus moves along the coordinate line *Ox* from the point *x*<==<=0 to the point *x*<==<=*a*. After starting from the point *x*<==<=0, it reaches the point *x*<==<=*a*, immediately turns back and then moves to the point *x*<==<=0. After returning to the point *x*<==<=0 it immediately goes back to the point *x*<==<=*a* ...
```python a,b,f,k=map(int,input().split()) petrol=b ans=0 for i in range(k): if petrol<0: print(-1) exit() if i%2==0: if petrol>=a: petrol-=a elif petrol>=f: petrol=b-(a-f) ans+=1 else: ans+=1 petr...
MatrixStudio/Codeforces-Python-Submissions
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer *q*. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of cir...
```python def factorize(n): p = 2 r = [] while p * p <= n: while n % p == 0: r.append(p) n //= p p += 1 if n > 1: r.append(n) return r q = int(input()) f = factorize(q) if len(f) <= 1: print(1) print(0) elif len(f) == 2: print(2) else: ...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python n = int(input()) answers=[] for i in range(n): accword = [] word = str(input()).strip() if len(word) > 4: for char in word: accword.append(char) new = accword[0]+str(len(word))+accword[-1] answers.append(new) else: answers.append(word) for i2 in answers: print(...
MatrixStudio/Codeforces-Python-Submissions
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph *G* is given. Subset *A* of its vertices is called a vertex cover of this graph, if for each edge *uv* there is at least one endpoint of it in this set, i.e. or (or bot...
```python flag = 0 n, e = [int(i) for i in input().split(" ")] edges = [] for i in range(e): k = [int(i) for i in input().split(" ")] edges.append(k) dictionary = {} visited = [0] * (n+1) def backtrack(ind, set_1, set_2): if ind >= len(edges): return [True, set_1, set_2] ...
MatrixStudio/Codeforces-Python-Submissions
You are given an equation: Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
```python import math a = float(input()) b = float(input()) c = float(input()) special = b**2 - 4*a*c if special < 0: print(0) elif special == 0: x = (-b)/(2*a) print(1) print(x) elif special > 9999999999: print(-1) else: x1 = float( (-b-math.sqrt(special))/(2*a) ) ...
MatrixStudio/Codeforces-Python-Submissions
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
```python n=list(map(int,list(input()))) ans=int(max(n)) print(ans) s="" while(ans): for i in range(len(n)): if(n[i]>=1): s+="1" n[i]-=1 else: s+=str(n[i]) print(s,end=" ") s="" ans-=1 ```
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. Th...
```python a, b = map(int, input().split()) f = list(map(int, input().split())) f = [f[i] + b for i in range(a)] r = 0 for _ in range(a): if f[_] <= 5: r+=1 #print(*f) print(r//3) ```
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 c...
```python from sys import stdin, stdout from bisect import bisect_left, bisect_right from collections import Counter, deque from queue import Queue import heapq import math from itertools import permutations, combinations, islice n = int(stdin.readline()) a = [*map(int, stdin.readline().strip().split())] for...
MatrixStudio/Codeforces-Python-Submissions
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul...
```python from typing import DefaultDict letters = DefaultDict(lambda :0) for i in range(3): line = input() f = line[0] s = line[1] l = line[2] if s=='>': letters[f]+=1 if s=='<': letters[l]+=1 order = [None]*3 res = '' for letter in 'ABC': v = letters[letter] if order[...
MatrixStudio/Codeforces-Python-Submissions
Mike is trying rock climbing but he is awful at it. There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=&lt;<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ...,...
```python n = int(input()) arr = list(map(int,input().split())) l = [] for i in range(1 , n-1): x = arr.pop(i) d = [] #print(x) for j in range(len(arr) - 1): d.append(arr[j+1] - arr[j]) #print(d) l.append(max(d)) arr.append(x) arr.sort() print(min(l)) `...
MatrixStudio/Codeforces-Python-Submissions
Consider the infinite sequence of integers: 1,<=1,<=2,<=1,<=2,<=3,<=1,<=2,<=3,<=4,<=1,<=2,<=3,<=4,<=5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains ...
```python n = int(input()) i, s = 1, 0 while s + i < n: s += i i += 1 print(n - s if n - s <= i else i) ```
MatrixStudio/Codeforces-Python-Submissions
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a 2<=×<=*n* maze. Imagine a maze that looks like a 2<=×<=*n* rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can ...
```python n, m = map(int, input().split()) s1 = input() s1 = 'X' + s1 s2 = input() s2 = 'X' + s2 blocks = [] groups = [0 for i in range(n)] res = [0 for i in range(2 * n)] group = 0 for i in range(n + 1): el1 = s1[i] el2 = s2[i] if el1 == el2 == 'X': blocks.append(3) elif el1 == 'X': blo...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the Wo...
```python # Getting Problem-Data from Codeforces. eventCount,pairs = int(input()),[] for i in range(eventCount): newPair = tuple(map(int,input().split(' '))) pairs.append(newPair) # Sorting Pairs by first componenet. from operator import itemgetter pairs.sort(key=itemgetter(0)) # Method to detemine if e...
MatrixStudio/Codeforces-Python-Submissions
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on the...
```python import random a = input() a = int(a) t1 = input() t2 = input() mor = 0 s = [] n = [] for i in range(0,a): s.append(int(t1[i])) n.append(int(t2[i])) n.sort() t = 1 for i in range(0,a): t = t * (a - i) mor = a * 2 sher = 0 for i in range (0,t * 2): random.shuffle(n)...
MatrixStudio/Codeforces-Python-Submissions
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
```python import math k = {'s':'Sheldon' , 'l' : 'Leonard' , 'p' :'Penny' , 'r' : "Rajesh" , 'h' :'Howard'} h = "" st = "slprh" g = int(input()) h = int(math.log(g/5 + 1 , 2)) su = 5*(2**h - 1) diff = g - su p = 2**h ind = math.ceil(diff/p) print( k[st[ind-1]]) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* boys and *m* girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to *n*<=+<=*m*. Then the number of integers *i* (1<=≤<=*i*<=&lt;<=*n*<=+<=*m*) such th...
```python nm=input().split() n=int(nm[0]) m=int(nm[1]) output=[] if n>=m: i=0 while(i<m): output.append('B') output.append('G') i+=1 j=0 while(j<n-m): output.append('B') j+=1 elif m>n: i=0 while(i<n): output.append('G') ou...
MatrixStudio/Codeforces-Python-Submissions
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
```python # Problem: http://codeforces.com/contest/731/problem/A # Time: ms # Space: KB # String -> int # returns minimum no. of rotations of the wheel (either c.w. or a.c.w starting from a) needed to print the given string # stub # def countSteps(string): # return 0 # unit tests # def test(): # assert co...
MatrixStudio/Codeforces-Python-Submissions
There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave...
```python n = int(input()) footprints = list(input()) start = 0 ending = 0 if 'R' in footprints: for i in range(n): if footprints[i] == 'R' and footprints[i - 1] == '.': start = i + 1 if footprints[i] == 'R' and footprints[i + 1] == '.': ending = i + 2 elif ...
MatrixStudio/Codeforces-Python-Submissions
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of tea...
```python n=int(input()) l=list(map(int,input().split())) ones=l.count(1) twos=l.count(2) if ones==0: print(0) else: res=0 if ones>=twos: res=twos ones-=twos res+=(ones//3) else: res+=ones print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has *n* sticks whose lengths equal *a*1,<=*a*2,<=... *a**n*. Nicholas does not want...
```python n = int(input()) A = list(map(int, input().split())) from collections import Counter C = Counter(A) cnt = 0 for k, v in C.items(): cnt += v//2 print(cnt//2) ```
MatrixStudio/Codeforces-Python-Submissions
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that...
```python from collections import defaultdict n, m = map(int, input().split()) amigos = defaultdict(set) for _ in range(m): c, d = map(int, input().split()) amigos[c].add(d) amigos[d].add(c) is_reasonable = all(amigos[i].intersection(amigos[j]) for i in amigos for j in amigos[i] if i != j) print("YES" ...
MatrixStudio/Codeforces-Python-Submissions
There are *n* stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
```python n=Int(input()) r=input() c=0 for i in range(0,n-1): if r[i]==r[i+1]: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her *t* queries, each of one of the following type: 1. <=+<= *a**i* — add non-negative integer *a**i* to the multiset. Note, that she has a multiset, thus there may b...
```python cnt = [0]*262200 trans = str.maketrans('0123456789', '0101010101') t = int(input()) for _ in range(t): o, a = input().split() if o == '+': cnt[int(a.translate(trans), 2)] += 1 elif o == '-': cnt[int(a.translate(trans), 2)] -= 1 else: print(cnt[int(a, 2)]) ...
MatrixStudio/Codeforces-Python-Submissions
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of tea...
```python n = int(input()) p = list(map(int, input().split())) amount_of_ones = 0 amount_of_twos = 0 for i in range(n): if p[i] == 1: amount_of_ones += 1 if p[i] == 2: amount_of_twos += 1 x = min(amount_of_twos, amount_of_ones) if amount_of_ones/3 > amount_of_twos: print (...
MatrixStudio/Codeforces-Python-Submissions
High school student Vasya got a string of length *n* as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than *k* characters of the original strin...
```python n,k=map(int,input().split()) s=input() i,j=0,0 rm=k ans=0 while i<n and j<n: while j<n and (rm>0 or s[j]=='a'): if s[j]=='b': rm-=1 j+=1 ans=max(ans,j-i) if j==n: break while s[i]=='a': i+=1 i+=1 rm+=1 i,j=0,0 rm=k while i<n and j<n: whil...
MatrixStudio/Codeforces-Python-Submissions
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
```python s = list(map(int, input().split('+'))) s.sort() print(*s, sep='+') ```
MatrixStudio/Codeforces-Python-Submissions
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner. Output the probability that SmallR will...
```python from sys import stdin,stdout ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().split() mod = 1000000007 a, b, c, d = iia() p = a / b q = (1 - c / d) * (1 - a / b) p...
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 t...
```python a = int(input()) s = list(map(int,input().split())) s1 = sum(s) c = 0 for i in range(1,5+1): if (s1+i)%(a+1)!=1: c+=1 print(c) ```
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...
```python a= input() if "0000000" in a or "1111111" in a: print("yes") else: print("no") ```
MatrixStudio/Codeforces-Python-Submissions
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*. Will the robot be able to build the fence Emuska...
```python for _ in range(int(input())): a = int(input()) print("YES" if (360/(180-a)).is_integer() else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are *n* days, at the *i*-th day, Arya finds *a**i* candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of ...
```python import math alph="abcdefghijklmnopqrstuvwxyz" #----------------------------------- n,k=map(int,input().split()) a=list(map(int,input().split())) p=0 for i in range(n): if a[i]>8: k-=8 p+=a[i]-8 else: k-=a[i] if p!=0: k-=min(p,8-a[i]) ...
MatrixStudio/Codeforces-Python-Submissions
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2<...
```python n, m = map(int, input().split()) a = [] ans = 0 for i in range(n): a.append(input()) for i in range(1, n): for j in range(1, m): c = [a[i][j], a[i - 1][j], a[i - 1][j - 1], a[i][j - 1]] if 'f' in c and 'a' in c and 'c' in c and 'e' in c: ans += 1 print(ans) ```
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 ...
```python from numpy import array a = array([int] * 1000) def solve(): n = int(input()) h = int(input()) k = 0 for i in range(n): a[i] = int(input()) if a[i] <= h: k = k + 1 else: k = k + 2 print(k) '''def main(): t = int(input(...
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 ...
```python M_N,S_A = map(int, input().split()) for _R in range(M_N): if any(x in 'CMY' for x in input().split()) print('#Color') break else: print('#Black&White') ```
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 th...
```python s= input() k=0 for i in s: if i.upper()== i: k+=1 if k> len(s)//2: print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which...
```python # A number is divisible by 4 when its last two digits are divisible by 4 s= input() ans = 0 # First find sigle substring divisible by 4 for i in s: if int(i)%4 == 0: ans+=1 n = len(s) # when two digits form a number divisible by 4 then increase the answer by the index of the right one for i in...
MatrixStudio/Codeforces-Python-Submissions
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after *k* minutes after turning on. During cooking, Julia goes to the kitchen every *d* minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. T...
```python """Problem C - Save Energy!. http://codeforces.com/contest/937/problem/C Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns o...
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not n...
```python s = input() n = len(s) if n < 26: print(-1) exit() characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ") substring = [] for i in range(n): while len(substring) == 26 or (s[i] in substring and s[i] != "?"): substring.pop(0) substring.append(s[i]) if len(substring) == 26: ...
MatrixStudio/Codeforces-Python-Submissions
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function *f*, which is defined ...
```python n = int(input()) A =list(map(int, input().split())) B = [] for i in range(n-1): B.append(abs(A[i]-A[i+1])) dpmin = [0] * n dpmax = [0] * n for i in range(n-2,-1,-1): dpmax[i] = B[i] dpmin[i] = B[i] dpmin[i] = min(dpmin[i], B[i] - dpmax[i+1]) dpmax[i] = max(dpmax[i], B[i] - dpmi...
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 ...
```python m,n=map(int,input().split()) area=m*n if area<2: print(0) else: print(area//2) ```
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 morn...
```python a,b,c=map(int,input().split()) d=c//b if a==c or (d>0 and (c%b==a or c%b==a+1)) :print("YES") else:print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume th...
```python n, s = map(int, input().split()) a = list(map(int, input().split())) a.remove(max(a)) ans = sum(a) > s print("NO" if ans else "YES") ```
MatrixStudio/Codeforces-Python-Submissions
Ann has recently started commuting by subway. We know that a one ride subway ticket costs *a* rubles. Besides, Ann found out that she can buy a special ticket for *m* rides (she can buy it several times). It costs *b* rubles. Ann did the math; she will need to use subway *n* times. Help Ann, tell her what is the minimu...
```python l=list(map(int,input().split())) n=l[0] m=l[1] a=l[2] b=l[3] total_cost=0 while(n>0): if(n-m>=0): current_cost=min(m*a,b) total_cost+=current_cost n=n-m elif(n-1>=0): current_cost=a; total_cost+=current_cost n=n-1 print(total_cost) ```
MatrixStudio/Codeforces-Python-Submissions
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors. Consider positive integers *a*, *a*<=+<=1, ..., *b* (*a*<=≤<=*b*). You want to find the minimum integer *l* (1<=≤<=*l*<=≤<=*b*<=-<=*a...
```python # -*- coding: utf-8 -*- """ Created on Tue Jul 6 23:37:57 2021 @author: LENOVO """ #método que crea un array (prim) desde 0 hasta b, dónde prim[i]=1 solo si i es un número primo def PrimeGen(b): prim=[1]*(b+1) prim[0]=prim[1]=0 for i in range(2,b+1,1): fo...
MatrixStudio/Codeforces-Python-Submissions
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to *y*. Some of them (more precise, from 2 to *p*) are occupied by tiny vile grasshoppers which you're at war with. These grassh...
```python import math def printDivisors(n): i = 2 s = set() while i <= math.sqrt(n): if (n % i == 0): if (n // i == i): s.add(i) else: s.add(i) s.add(n//i) i = i + 1 return s p,y = map(int,input(...
MatrixStudio/Codeforces-Python-Submissions
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*. For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375. W...
```python n, k = input().split() k = int(k) n = int(n) a = n b = 10**k if n%10 == 5 or n%10 == 0: while a%2 == 0 and b%2 == 0: a = a//2 b = b//2 while a%5 == 0 and b%5 == 0: a = a//5 b = b//5 a = n*b else: a = a*(10**k) print (a) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen. On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, ...
```python a = input() n = len(a) ans = [] cnt = 1 m = 1 #for max ans.append(1) for i in range(1,n): if(a[i] == a[0]): cnt+=1 else: cnt -=1 ans.append(cnt) m = max(m,cnt) # print(ans) print(m) ```
MatrixStudio/Codeforces-Python-Submissions
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes....
```python #!/usr/bin/env python3 number_of_mines = int(input()) x_coords = [] y_coords = [] for _ in range(number_of_mines): x, y = (int(value) for value in input().split()) x_coords.append(x) y_coords.append(y) print(max(abs(max(x_coords) - min(x_coords)), abs(max(y_coords) - min(y_coords))) ** 2...