source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Anton likes to play chess, and so does his friend Danik. Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
```python count=int(input()) wins=input() A=0 D=0 for i in wins: if i=='A': A+=1 else: D+=1 if A>D: print('Anton') elif A<D: print('Danik') else: print('Friendship') ```
MatrixStudio/Codeforces-Python-Submissions
Fafa owns a company that works on huge projects. There are *n* employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best *l* em...
```python n=int(input()) nb=bin(n).replace("0b","") lnb=len(nb) x=lnb-1 print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange ...
```python n, b, d = map(int, input().split()) arr = list(map(int, input().split())) sum_, count = 0, 0 for i in range(n): if arr[i] < b: sum_ += arr[i] if sum_ >= d: count += 1 sum_ = 0 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
```python n = int(input()) stewards = list(map(int, input().split())) count = 0 sm = 10000000000 lg = -10000000000 for i in stewards: sm = min(i, sm) lg = max(i, lg) for i in stewards: if i > sm and i < lg: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
```python characters = int(input()) string = input() removals = 0 for i in range(0, characters - 2): if string[i] == 'x' and string[i + 1] == 'x' and string[i + 2] == 'x': removals = removals + 1 print(removals) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences. Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequenc...
```python n = int(input()) a = list(map(int,input().split())) c = 0 for i in range(n): c += abs(a[i]) print(c) ```
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* woode...
```python n=int(input()) x=list() y=list() for i in range(n): a,b=map(int,input().split()) x.append(a) y.append(b) x0=x.count(0) x1=n-x0 y0=y.count(0) y1=n-y0 # if(x0>x1 and y1>y0): # print(x1+y0) # elif(x0>x1 and y1>y0): # print(x0) if x0+y1>y0+x1: print(x1+y0) else: ...
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() ctru,ctrl=0,0 for i in s: if i.islower():ctrl+=1 else:ctru+=1 if ctrl>ctru:s=s.lower() else: s=s.upper() print(s) ```
MatrixStudio/Codeforces-Python-Submissions
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were pub...
```python from collections import deque n,k = [int(i) for i in input().split()] h = [int(i) for i in input().split()] r = [] d = deque() cnt = 0 for i in range(len(h)): d.append(h[i]) if max(d) - min(d) > k: temp = len(d)-1 if temp > cnt: cnt = temp r = [] ...
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
```python n = input() n = str(n) a = n.replace("a",".") b = n.replace("b",".") c = n.replace("c",".") d = n.replace("d",".") e = n.replace("e",".") f = n.replace("f",".") g = n.replace("g",".") h = n.replace("h",".") i = n.replace("i",".") j = n.replace("j",".") k = n.replace("k",".") l = n.replace("l",".") m = n.repla...
MatrixStudio/Codeforces-Python-Submissions
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color...
```python import sys import math def fn(n,m,a): if n==1: t1=0 for i in range(m): t1=t1+a[i][0] print(t1,end=' ') return 0 t=[0]*n t[0]=a[0][0] for i in range(1,n): t[i] = a[0][i]+ t[i-1] print(t[n-1],end=' ') for i i...
MatrixStudio/Codeforces-Python-Submissions
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the...
```python n = int(input()) string = str(input()) #str2 = "" while string.find("ogo") > -1: f = string.find("ogo") end = f + 3 end2 = end + 2 while string[end:end2] == "go": end += 2 end2 = end + 2 string = string[:f] + "***" + string[end:] print(string) ```
MatrixStudio/Codeforces-Python-Submissions
A tourist hiked along the mountain range. The hike lasted for *n* days, during each day the tourist noted height above the sea level. On the *i*-th day height was equal to some integer *h**i*. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most ...
```python N, M = map(int, input().split()) H = [] D = [] for i in range(M): d, h = map(int, input().split()) H.append(h) D.append(d) res = max(max(H), H[M - 1] + N - D[M - 1]) for i in range(M - 1): dest = D[i + 1] - D[i] diff = abs(H[i + 1] - H[i]) if diff > dest: res = float('inf') ...
MatrixStudio/Codeforces-Python-Submissions
Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, *mex*([4,<=33,<=0,<=1,<=1,<=5])<==<=2 and *mex*([1,<=2,<=3])<==<=0. Vitya quickly understood all tasks of the teacher, but ca...
```python from sys import stdin, stdout n,m = map(int,stdin.readline().rstrip().split()) a = set(map(int,stdin.readline().rstrip().split())) q = 0 for _ in range(m): q = q ^ int(stdin.readline().rstrip()) for i in range(n+1): if q^i not in a: print(i) break ```
MatrixStudio/Codeforces-Python-Submissions
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free...
```python from collections import* q=int(input()) lst=[] for i in range(q): h,m=map(int,input().split()) d=str(h)+str(m) lst.append(d) s=1 for i,x in Counter(lst).items(): if x>=2: s+=1 print(s) ```
MatrixStudio/Codeforces-Python-Submissions
You have *n* devices that you want to use simultaneously. The *i*-th device uses *a**i* units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·*a**i* units of power. The *i*-th device currently has *b**i* units of power stored. All devices can store an arbitrary amount of pow...
```python from math import inf n, p = [int(x) for x in input().split()] l = [] for i in range(n): a, b = [int(x) for x in input().split()] l.append((a, b, b/a)) l.sort(key=lambda x: x[2]) asum = 0 bsum = 0 sumt = 0 for i in range(n): a0, b0, _ = l[i] c1 = inf if i == n-1 else l[i+1][2] ...
MatrixStudio/Codeforces-Python-Submissions
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the...
```python ch=input() x=len(ch) a=0 i=0 while (a==0) and (i<x/2): if ch[0:i+1]==ch[x-1-i:x]: a=1 i+=1 t=ch[0:i] c=len(t) if (c>1): if (a==1) and (t in ch[c:x-c]): print(t) else: print("Just a legend") else: print("Just a legend") ```
MatrixStudio/Codeforces-Python-Submissions
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the ...
```python a=[int(k) for k in input().split()] b=[int(k) for k in input().split()] c=[int(k) for k in input().split()] d=[int(k) for k in input().split()] if (a[0]>c[1] and b[1]>d[0]) and (a[0]>d[1] and b[1]>c[0]): print("Team 1") elif (a[1]>c[0] and b[0]>d[1]) and (a[1]>d[0] and b[0]>c[1]): print("Team...
MatrixStudio/Codeforces-Python-Submissions
HQ9+ is a joke programming language which has only four one-character instructions: - "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator. Instructions "H" and "Q" are case-s...
```python x = input() instructions = "HQ9" for char in x: if char in instructions: print("YES") break else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
In Ancient Berland there were *n* cities and *m* two-way roads of equal length. The cities are numbered with integers from 1 to *n* inclusively. According to an ancient superstition, if a traveller visits three cities *a**i*, *b**i*, *c**i* in row, without visiting other cities between them, a great disaster awaits him...
```python import sys def find(b, road): if b: find(pre[b][road], b) print(road, end=' ') _input = lambda:[*map(int, input().split())] n, m, k = _input() road_descs = [[]for i in range(n + 1)] for i in range(m): a, b = _input() road_descs[a] += [b] road_descs[b] += [a] st = se...
MatrixStudio/Codeforces-Python-Submissions
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses ...
```python n,m=map(int,input().split()) lst=list(map(int,input().split())) vis=[0]*n cnt=0 for i in range(n): if lst[i]<=m: cnt+=1 vis[i]=1 else: break for i in range(n-1,-1,-1): if vis[i]==1 or lst[i]>m: break else: cnt+=1 print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it?
```python s = int(input()) a = hex(s)[2:] print(a.count('0') + a.count('4') + a.count('6') + a.count('8') * 2 + a.count('a') + a.count('9') + a.count('b') * 2 + a.count('d')) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But h...
```python item=input() def LTE(a,b): if(len(a)!=len(b)): #smaller length always smaller return len(a)<len(b) #same len for i in range(len(a)): if(a[i]<b[i]): return True elif(a[i]>b[i]): return False #equal return True if(item[0]!='-'): #...
MatrixStudio/Codeforces-Python-Submissions
DZY has a hash table with *p* buckets, numbered from 0 to *p*<=-<=1. He wants to insert *n* numbers, in the order they are given, into the hash table. For the *i*-th number *x**i*, DZY will put it into the bucket numbered *h*(*x**i*), where *h*(*x*) is the hash function. In this problem we will assume, that *h*(*x*)<==...
```python p, n = [int(_) for _ in input().split()] d = {} ans = -1 f = True for i in range(n): x = int(input()) if f and x%p in d: ans = i+1 f = False else: d[x%p] = 1 print(ans) ```
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...
```python m,n,a = map(int, input().split()) if(a>=m and a>=n): print(1) elif(a==1): print(m*n) elif(a>=m and a <n and a >= n and a<m): print((m*n)//(a*a) +1) else: print((m*n)//(a*a) +2) ```
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 input() km = input().split(' ') k,m = int(km[0]),int(km[1]) ast = input().split(' ')[:k] bst = input().split(' ')[:m] a,b = list(),list() for s in ast: a.append(s) for s in bst: b.append(s) a.sort() b.sort() if (a[len(a)-1] < b[0]): print('YES') else : print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array *a*. Some element of this array *a**i* is a local minimum iff it is strictly less than both of its neighbours (that is, *a**i*<=&lt;<=*a**i*<=-<=1 and *a**i*<=&lt;<=*a**i*<=+<=1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, *a**i*<=&gt;<=*...
```python n = int(input()) L = list(map(int, input().split())) ans = 0 for i in range(1, n-1): if L[i] > L[i-1] and L[i] > L[i+1]: ans += 1 if L[i] < L[i-1] and L[i] < L[i+1]: ans += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? — Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcom...
```python from math import inf def solve_task5(): n = int(input()) trees = tuple(map(int, input().split(" "))) reversed_trees = tuple(reversed(trees)) max_rating = -1 * inf begin_tree = 0 end_tree = 0 deleted_trees = [] for i in range(n): l = trees[i] r = n...
MatrixStudio/Codeforces-Python-Submissions
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
```python n, m = map(int, input().split()) words = {} for _ in range(m): first_lang, second_lang = input().split() words[first_lang] = second_lang lecture = input().split() recorded_lecture = [words[word] if len(words[word]) < len(word) else word for word in lecture] recorded_lecture = ' '.join(rec...
MatrixStudio/Codeforces-Python-Submissions
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a ...
```python # https://codeforces.com/problemset/problem/34/A def func_sol(raw_data): temp = list(map(int, raw_data.split('\n')[1].split(' '))) a = sorted([(idx, t) for idx, t in enumerate(temp)], key=lambda e: e[1]) min_diff = abs(a[0][1] - a[1][1]) x, y = a[0][0], a[1][0] for idx in range(-1,...
MatrixStudio/Codeforces-Python-Submissions
Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to a...
```python def solve(x, y): global k if x < 0 or x > n - 1 or y < 0 or y > m - 1 or arr[x][y] != '.' or vis[x][y] == True: return vis[x][y] = True solve(x + 1, y) solve(x - 1, y) solve(x, y + 1) solve(x, y - 1) if k > 0: arr[x][y] = 'X' k -= 1 ...
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take...
```python def game(a, b, c, x, y): while True: x=a y=b z=c while z > 0: x, z = z, x % z c-=x z=c if c<b: return 0 y=b while z > 0: y, z = z, y % z c-=y z=c if c<a: ...
MatrixStudio/Codeforces-Python-Submissions
There is a square painted on a piece of paper, the square's side equals *n* meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwa...
```python import math def lcm(x,y): return x * y // math.gcd(x,y) n = int(input()) arr = list(map(int, input().split())) for i in arr: print((lcm(4*i, i+1) // (i+1)) + 1) ```
MatrixStudio/Codeforces-Python-Submissions
zscoder loves simple strings! A string *t* is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string *s*. He wants to change a minimum number of characters so that the string *s* becomes simple. Help him with th...
```python from sys import stdin,stdout input = stdin.readline print = stdout.write s = list(input()) s.pop() for i in range(1, len(s)): if s[i] == s[i-1] and i != len(s)-1: if s[i-1] != 'a' and s[i+1] != 'a': s[i] = 'a' elif s[i-1] != 'b' and s[i+1] != 'b': s[i] = '...
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() h = 0 l = 0 for c in s: if c.isupper(): h = h + 1 elif c.islower(): l = l +1 else: pass if h > l: print(s.upper()) elif h < l: print(s.lower()) elif h == l: print(s.upper()) else: pass ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array of *n* integer numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
```python n=int(input()) a=[] s=10 d=0 for i in input().split(): a.append(int(i)) m=min(a) p0=a.index(m) for i in range(p0+1,len(a)): if a[i]==m: d=i-p0 if d<s: s=d p0=i print(s) ```
MatrixStudio/Codeforces-Python-Submissions
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: - the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color. Using colors...
```python t = int(input()) ref = {"red":"Reality","purple":"Power","yellow":"Mind","orange":"Soul","green":"Time","blue":"Space"} ans = [] for x in range(t): stone = input().lower() ans.append(stone) mis = [b for a,b in ref.items() if a not in ans] print (6-t) for z in mis: print (z) ...
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope wi...
```python inf = 1000000000 def solve(): n = int(input()) num4 = inf num7 = inf for num_4 in range(n // 4): left = n - 4 * num_4 if left % 7 != 0: continue num_7 = left // 7 if num_4 + num_7 <= num4 + num7: num4 = num_4 num7 = num_7...
MatrixStudio/Codeforces-Python-Submissions
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (*x*,<=*y*), he can move to (or attack) positions (*x*<=+<=1,<=*y*), (*x*–1,<=*y*), (*x*,<=*y*<=+<=1) and (*x*,<=*y*–1). ...
```python n = int(input()) for i in range(0,n): for j in range(0,n): if((i + 1) % 2 == 0): if( (j + 1)% 2 == 0): print("C",end = "") else: print(".",end = "") else: if( (j + 1)% 2 == 1): print("C",end = "")...
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 = int(input()) lst = list(map(int, input().split())) lst.sort() tot = 0 for i in range(n): tot += abs((i+1) - lst[i]) print(tot) ```
MatrixStudio/Codeforces-Python-Submissions
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel. Ari draws a regular convex polygon on the floor and numbers it's vertices 1,<=2,<=...,<=*n* in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other v...
```python import math as mt import sys,string input=sys.stdin.readline #print=sys.stdout.write import random import collections from heapq import heappush,heapify,heappop L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n=I() print((...
MatrixStudio/Codeforces-Python-Submissions
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl...
```python a=int(input());b=input();print(sum(b[i-1]==b[i-2]==b[i-3] for i in range(a,len(b),a))) ```
MatrixStudio/Codeforces-Python-Submissions
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec...
```python n = int(input()) line = input() lst = [] lst += line vowels = "aeiouy" for i in range(1, n): if lst[i - 1] in vowels and lst[i] in vowels: lst[i] = "" print("".join(lst)) ```
MatrixStudio/Codeforces-Python-Submissions
Valera is a lazy student. He has *m* clean bowls and *k* clean plates. Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can...
```python n,m,k = map(int, input().split()) al = list(map(int, input().split())) k -= al.count(2) m -= al.count(1) + max(0, -k) print(max(0, -m)) ```
MatrixStudio/Codeforces-Python-Submissions
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, an...
```python l, n = input(), input() o = n.count("1") z = n.count("0") print(int(l)-2*min(z, o)) ```
MatrixStudio/Codeforces-Python-Submissions
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a set of digits, your task is to find the maximum integer that you can mak...
```python n = int(input()) array = list(map(int,input().split())) if 0 not in array: print(-1) else: output = [] answer = "" for i in range(len(array)): if array[i] == 0 or array[i] % 2 == 0 or array[i] % 3 == 0 or array[i] % 5 == 0: output.append(array[i]) output.sort(...
MatrixStudio/Codeforces-Python-Submissions
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1. Note that all c...
```python def mcd(a, b): resto = 0 while(b > 0): resto = b b = a % b a = resto return a n=int(input()) y=n k=2 p=0 r=0 for q in range (0, n-2): n=y while n>=k: a=n%k p=p+a n=n//k p=p+n k=k+1 t=k-2 a=mcd(p,t) n...
MatrixStudio/Codeforces-Python-Submissions
The new "Die Hard" movie has just been released! There are *n* people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells t...
```python n=int(input()) x=input() if(x==25 or x== 50): print("Yes") else: print("No") ```
MatrixStudio/Codeforces-Python-Submissions
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all oth...
```python ans = -1 req = [] mx = 0 mn = 10**10 for _ in range(int(input())): seg = list(map(int, input().split())) # print(seg) if seg[0] < mn: mn = seg[0] req = seg ans = _+1 elif seg[0] == mn and seg[1] > mx: mx = seg[1] req =...
MatrixStudio/Codeforces-Python-Submissions
Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, first...
```python y,k,n=map(int,input().split()) if(y>=n): print(-1) else: x=n//k l=[] for i in range(1,x+1): if(k*i-y>0): l.append((str(k*i-y))) print(' '.join(l)) ```
MatrixStudio/Codeforces-Python-Submissions
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on. When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if *i*-th garland is switched on during *x*-th s...
```python x1,x2,x3=[int(x1) for x1 in input().split()] arr=[] count=0 count2=0 if(x1==1 or x2==1 or x3==1): print("YES") else: arr.append(x1) arr.append(x2) arr.append(x3) for i in range(3): if(arr[i]==2): count=count+1 elif(arr[i]==4): count2=co...
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()) s = 0 if n % 2 == 0: s = n // 2 else: s = n // 2 - n print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments...
```python input() L = list(map(int, input().split())) L.sort() flag = False #print(L) for i in range(1, len(L) - 1): for j in range(0, len(L) - i - 1): #print(L[j], L[len(L) - i - 1], L[len(L) - i]) if L[j] + L[len(L) - i - 1] >= L[len(L) - i]: flag = True break pr...
MatrixStudio/Codeforces-Python-Submissions
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number *a*, the second player wrote number *b*. How many w...
```python a,b=map(int,input().split()) aw=0 draw=0 bw=0 for i in range(1,7): if(abs(a-i)<abs(b-i)): aw+=1 elif(abs(a-i)>abs(b-i)): bw+=1 else: draw+=1 print(aw,draw,bw) ```
MatrixStudio/Codeforces-Python-Submissions
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores *t* points, he wins the set; then the ...
```python import sys n = int(input()) a = [int(i) for i in input().split()] m = a[-1] ans = [] for t in range(1, n + 1): for s in range(1, n // t + 1): s1, s2, i, k1, k2 = 0, 0, 0, 0, 0 while i != n: if a[i] == m: s1 += 1 else: s2 += 1 ...
MatrixStudio/Codeforces-Python-Submissions
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1. Note that all c...
```python from math import gcd n, s=int(input()), 0 for i in range(2,n): k = n while k != 0: s+=k%i k//=i p=gcd(s,n-2) print(f'{s//p}/{(n-2)//p}') ```
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()) b, total = 0, 0 for x in range(1, w+1): total += x * k if (n - total) > -1: print(n) else: print(abs(n-total)) ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let *a* is a permutation of an integers from 1 to *n*, inclusive, and *a**i* denotes the *i*-th element of the permutation. The Little Elephant's recursive function *f*(*x*), that sorts the first *x* permutation's elements, works...
```python def f(m): p[m-1],p[m]=p[m],p[m-1] k=int(input()) p=[] for i in range(1,k+1): p.append(str(i)) for i in range(k,-1,-1): if i==1: break else: f(i-1) print(' '.join(p)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded. For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct. For given *n* find out to which int...
```python print(input()[:-1]+'0') ```
MatrixStudio/Codeforces-Python-Submissions
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team ...
```python n = int(input()) home = input() flights = [] comesFrom = [] goesTo = [] for i in range(n): flights.append(input()) goingFrom, comingTo = flights[i].split('->', 1) if(goingFrom == home): goesTo.append(comingTo) if(comingTo == home): comesFrom.append(goingFrom) if(len(comes...
MatrixStudio/Codeforces-Python-Submissions
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know l...
```python from collections import defaultdict,Counter,deque import math import bisect from itertools import accumulate from math import ceil, log,gcd from functools import lru_cache from sys import stdin, stdout import atexit import io import sys def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = ...
MatrixStudio/Codeforces-Python-Submissions
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of *n* non-negative integers *a**i* numbered from 1 to *n*. The goal of the game is to make numbers *a*1,<=*a*2,<=...,<=*a**k* (i.e. some pr...
```python import math n=int(input()) seq=list(map(int,input().split())) move=0 while len(seq)>1: lenth=len(seq) while seq[0]!=0: move+=1 seq[0]-=1 lgint=int(math.log2(lenth-1)//1) seq[2**lgint]+=1 seq.remove(seq[0]) print(move) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly. An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. ...
```python import math mod=10**9+7 n=int(input()) d = 0 abc = 3 for i in range(2,n+1): d,abc = abc, 3*d+2*abc print(d%mod) ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
```python n, m = list(map(int, input().split())) ans = 0 for i in range(n): cur = i f = n - i mn = m - 2 * i if mn >= f: cur += min(mn, f // 2) ans += max(cur, ans) print(ans) ```
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, ...
```python # 01234 keyword = "hello" n_keyword = len(keyword) #keyword[0] == word[0] no #keyword[0] == word[1] yes #keyword[1] == word[2] no #keyword[1] == word[3] yes #keyword[2] == word[4] yes #keyword[3] == word[5] yes #keyword[4] == word[6] no #keyword[4] == word[7] no #keyword[4] == word[8] no ...
MatrixStudio/Codeforces-Python-Submissions
Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, first...
```python y, k, n = map(int, input().split()) vals = [] for x in range(((y//k)+1)*k-y, n+1, k): if x+y>n: break vals.append(str(x)) if not vals: print(-1) else: print(*vals) ```
MatrixStudio/Codeforces-Python-Submissions
One day Ms Swan bought an orange in a shop. The orange consisted of *n*·*k* segments, numbered with integers from 1 to *n*·*k*. There were *k* children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper...
```python n, k = [int(x) for x in input().split(' ')] a = [int(x) for x in input().split(' ')] b = [i for i in range(1, n * k + 1) if i not in a] for i in range(k): print(*([a[i]] + b[i*(n-1):(i+1)*(n-1)])) ```
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 allo...
```python a=int(input()) b=int(input()) c=int(input()) d=int(input()) if (a+b>c) and (b+c>a) and (c+a>b): print("TRIANGLE") elif (a+b>d) and (a+d>b) and (d+b>a): print("TRIANGLE") elif (a+c>d) and (a+d>c) and (d+c>a): print("TRIANGLE") elif (b+c>d) and (b+d>c) and (b+c>a): print("TRIANGLE") e...
MatrixStudio/Codeforces-Python-Submissions
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with th...
```python a , b = map(int , input().split()) arr = [list(input()) for _ in range(a)] ans = [['-']*b for _ in range(a)] for i in range(a): for j in range(b): if arr[i][j] == '-': continue if (i+j)%2==0: ans[i][j] = 'B' else: ans[i][j] = 'W' for i in ans: print(''.join(i)) ```
MatrixStudio/Codeforces-Python-Submissions
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of *r*1 cm, inner radius of *r*2 cm, (0<=&lt;<=*r*2<=&lt;<=*r*1) made of metal with density *p*1 g/cm3. The second part is an inner disk with radius *r*2 cm, it is made of metal with density *p*2 g/...
```python import math x = [int(x) for x in input().split()][1:] y = [int(x) for x in input().split()][1:] z= [int(x) for x in input().split()][1:] A,B = [int(x) for x in input().split()] pi= 3.14159 x.sort() y.sort() z.sort() r1 = x[-1] p1 = y[-1] p2 = z[0] ans = r1 *(math.sqrt((B*p1)/(A*p2+B*p1))) print...
MatrixStudio/Codeforces-Python-Submissions
You are given an undirected graph with *n* vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to *n*. You have to answer *q* queries. Each query is described by a segment of vertices...
```python import sys readline=sys.stdin.readline from bisect import bisect_right N,M=map(int,readline().split()) graph=[[] for x in range(N)] for m in range(M): a,b=map(int,readline().split()) a-=1;b-=1 graph[a].append(b) graph[b].append(a) seen=[False]*N finished=[False]*N order=[None]*N ...
MatrixStudio/Codeforces-Python-Submissions
The new "Die Hard" movie has just been released! There are *n* people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells t...
```python n = int(input()) money = [int(i) for i in input().split()] stored = 0 flag = True for i in range(n): change = money[i] - 25 if stored >= 0 and change > 0: stored = stored - change if stored < 0: flag = False break stored += 25 if flag: ...
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...
```python m,n,a= map(int,input().split()) M = 0 N = 0 if m % a == 0: M = m // a else: M = (n // a) +1 if n % a == 0: N = n // a else: N = (n // a) +1 print(M*N) ```
MatrixStudio/Codeforces-Python-Submissions
One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the min...
```python n,s = int(input()) - 1,list(map(int,input().split())) print(max(int(sum(s) / n + 0.5),max(s))) ```
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and *L*, and they move towards each other ...
```python l,d,v1,v2=map(int,input().split()) v=v1+v2 a=v x=d-l if(v-x>19995): v=2000 ans=str(x/v).split(".") if(a-x>19995): ans[1]="0"+ans[1]+"0"*(19-len(ans[1])) print(ans[1]) else: ans[1]=ans[1]+"0"*(20-len(ans[1])) print(".".join(ans)) ```
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, ...
```python x=input().lower() s=[] hello=["h","e","l","l","o"] if len(x)>5: for i in x: for j in hello: if j==i: s.append(i) if len(s)<5: print("NO") else: print("YES") else: print("NO") ```
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 cost = 0 k, n, w = map(int, input().split()) for i in range(1 , w+1): cost += i*k print(cost-n) if cost > n else print(0) ```
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady...
```python from math import ceil n, t, k, d = map(int, input().split()) total_time = ceil(n / k) * t if total_time > t + d: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and ...
```python w=int(input('no')) assert 1<=w<=100 for i in range(2,w,2): if (w-i)%2==0: return YES return NO ```
MatrixStudio/Codeforces-Python-Submissions
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players t...
```python n,k = map(int,input().split());s=0;t=0 if (n == 1 and k != 1) or (n == 1 and k == 1): print("YES") exit() else: while n - k > t: t+=k s+=1 if s % 2 == 0: print("NO") elif s % 2 != 0: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case ...
```python ## 2 - version import re s=input() if re.search('C.*O.*D.*E.*F.*O.*R.*C.*E.*S',s): print('YES') else: print('NO') ```
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=input() summands=list(map(int,input().split())) sorted_summands=sorted(summands) new_sum="+".join(map(str,sorted_summands)) print(new_sum) ```
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 import sys n1 = sys.stdin.readline().strip("\n") n2= sys.stdin.readline().strip("\n") i =0 r ="" while ...
MatrixStudio/Codeforces-Python-Submissions
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards ...
```python class Solution: def __init__(self): pass def solve(self): n = int(input()) arr = list(map(int, input().split())) each = 2*sum(arr)//n result = "" for i in range(n - 1): if arr[i] != 0: for j in range(i+1, n): if arr[j] + arr[i] == each: result += "{} {}\n".for...
MatrixStudio/Codeforces-Python-Submissions
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But h...
```python n = int(input()) sections = [int(i) for i in input().split()] maximal = 0 for i in range(n): counter = 0 for j in range(i, -1, -1): if sections[j] > sections[i]: break counter += 1 for j in range(i + 1, n): if sections[j] > sections[i]: ...
MatrixStudio/Codeforces-Python-Submissions
There is a square painted on a piece of paper, the square's side equals *n* meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwa...
```python n=int(input()) for i in range(n): t=int(input()) print(4*t+1) ```
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 ans...
```python n=input() n=n[::-1] v=['A','E','I','O','U','Y','a','e','i','o','u','y'] for i in range(len(n)): if n[i]!='' and n[i]!='?': if n[i] in v: print("YES") else: print("NO") break ```
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 #!/usr/bin/env python3.4 n, m = map(int, input().split()) board = [] for i in range(n): board.append(input()) ok_set = set(['f', 'a', 'c', 'e']) ans = 0 for i in range(n - 1): for j in range(m - 1): cur_set = set([board[i][j], board[i][j + 1], board[i + 1][j], board[i + 1][j + 1]]) if...
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...
```python l = list(map(int,input().split())) x = l[1]%l[2] y = l[0]%l[2] a = (l[0]+y)//l[2] b = (l[1]+x)//l[2] print(a*b) ```
MatrixStudio/Codeforces-Python-Submissions
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to *n* (*n*<=≥<=2) burles and the amount of tax he has to pay is calculated as the maximum divisor of *n* (not equal to *n*, of course). For example, if *n*<==<=6 then Funt has to pay 3 burles, while fo...
```python import sys import math def isprime(n): if n == 1: return False if n == 2: return True if n == 3: return True if (n % 2 == 0) or (n % 3 == 0): return False for i in range(5, int(math.sqrt(n))+1, 6): if (n % i == 0) or (n % (i + 2)) =...
MatrixStudio/Codeforces-Python-Submissions
Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages...
```python n, out, po = int(input()), set(), 1 for x in range(64): be, en = 1, 2 * 10 ** 9 while be <= en: md = (be + en) >> 1 val = md * (po - 1) + md * (md - 1) // 2 if val < n: be = md + 1 elif val == n: out.add(po * md) break ...
MatrixStudio/Codeforces-Python-Submissions
Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*.
```python n=list(map(int,input().split())) s=1 while(True): n[0]=n[0]+1 if(n[0]%n[1]==0): print(n[0]) break ```
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* woode...
```python count = 0 wcount = 0 for i in range(int(input())): a , b = map(int,input().split()) if (a == 0 and b == 0) or (a == 1 and b == 1): count += 1 else: wcount += 1 print(wcount) ```
MatrixStudio/Codeforces-Python-Submissions
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to *n*. Let's assume that Misha chose number *m*, and Andrew chose number *a*. Then, by using a random generator they choose a random integer *c* in the range between 1 and *n* (any integer from 1 to *n*...
```python n,m=map(int,input().split(' ')) if(m==1): if(n==1):print(1) else:print(2) elif(m==n):print(n-1) else: if(m-1>=n-m):print(m-1) else:print(n-m) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya collects coins: he has exactly one coin for every year from 1 to *n*. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from *l* to *r* inclusively and put them in the reverse...
```python n=int(input());A=list(map(int,input().split()));B=A.copy();B.sort();C=[] if A==B:print(0,0) else: left=0;right=0 for i in range(n): if A[i]!=B[i]: C.append(abs(A[i]-B[i])) if A[i]==B[i] and right==0:left=i+2 elif A[i]!=B[i]:right=i+1 if C==C[::-1]:print...
MatrixStudio/Codeforces-Python-Submissions
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has *n* balls and *m* baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to *m*, correspondingly...
```python n,m = map(int,input().split()) mid = (m+1)//2 lst = [0]*m lst[0] = mid p = 1 for i in range(1,mid): lst[p] = mid-i lst[p+1] = mid+1 p += 2 if m%2==0: lst[n-1] = m x = n//m v = n-x*m lst *= x lst.extend(lst[:v]) print(*lst) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
```python s=input() t=list(reversed(list(input()))) for letter_s,letter_t in zip(s,t): if letter_s!=letter_t: print("NO") break else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain ...
```python n=int(input()) output=[] for i in range(1,101): listi=list(map(int,str(i))) if(i+sum(listi)==n): output.append(i) print(len(output)) for i in range(len(output)): print(output[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Duff is addicted to meat! Malek wants to keep her happy for *n* days. In order to be happy in *i*-th day, she needs to eat exactly *a**i* kilograms of meat. There is a big shop uptown and Malek wants to buy meat for her from there. In *i*-th day, they sell meat for *p**i* dollars per kilogram. Malek knows all numbers ...
```python n = int(input()) m = [] p = [] for i in range(n): mi, pi = map(int, input().split()) m.append(mi) p.append(pi) ans = 0 minp = p[0] for i in range(n): minp = min(p[i], minp) ans += m[i]* minp print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve th...
```python x,y=map(int,input().split()) c=240-y p,q=0,0 while (c-p-5)>=0 and x>0: p+=5 q+=1 x-=1 c-=p print(e) ```