source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
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()) l = [] for i in range(m): l.append(list(map(int,input().split()))) ans = max(l[0][1]+l[0][0],l[-1][1]+n-l[-1][0]) for i in range(m-1): if abs(l[i][1]-l[i+1][1]) > abs(l[i][0]-l[i+1][0]): ans = 'IMPOSSIBLE' break if l[i][1] > l[i+1][1]: ...
MatrixStudio/Codeforces-Python-Submissions
Sean is trying to save a large file to a USB flash drive. He has *n* USB flash drives with capacities equal to *a*1,<=*a*2,<=...,<=*a**n* megabytes. The file size is equal to *m* megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
```python n=int(input()) m=int(input()) count=0 c=[] for i in range(n): a = int(input()) c.append(a) c.sort(reverse=True) if sum(c)<m: print("0") for i in range(len(c)-1): if c[0]>=m: coumt=0 break s=c[i]+c[i+1] if s<m: count+=1 if s>=m: count+=1 break prin...
MatrixStudio/Codeforces-Python-Submissions
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sendi...
```python def get_letters(word): letters = set(word) return ''.join(sorted(letters)) def main(): n = int(input()) words = [input() for _ in range(n)] two_letter_maps = {} single_letter_maps = {} for word in words: letters = get_letters(word) if len(letters) == 2: ...
MatrixStudio/Codeforces-Python-Submissions
The input contains a single integer *a* (0<=≤<=*a*<=≤<=35). Output a single integer.
```python n = (int)(input()); print(2 ** n); ```
MatrixStudio/Codeforces-Python-Submissions
Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers ex...
```python n=int(input()) c=0 m=0 while(n): a,b=map(int,input().split()) c=c-a+b m=max(m,c) n-=1 print(m) ```
MatrixStudio/Codeforces-Python-Submissions
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute. He was asked to insert one takeoff in the schedule. The takeoff takes $1$ minut...
```python n,s = map(int,input().split()) a = [] for i in range(n): h , m = map(int,input().split()) a.append((h*60)+m) time = a[n-1]+s+1 for i in range(n-1): dif = a[i+1] - a[i] if(dif > s*2+1): time = a[i]+s+1 break h = int(time/60) m = time%60 print("{} {}".format(h,m)) ```
MatrixStudio/Codeforces-Python-Submissions
A sequence of non-negative integers *a*1,<=*a*2,<=...,<=*a**n* of length *n* is called a wool sequence if and only if there exists two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such that . In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0. The expression means...
```python x = input() i = 3 y = "" while (i < len(x)-3): if (x[i]=="W" and x[i+1]=="U" and x[i+2]=="P"): y = y + " " i += 3 else: y = y + x[i] i += 1 print(y) ```
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 a = input() c = 'CODEFORCES' if len(a)<10:print('NO') else: t = 0 for i in range(10): if a[i] == c[i]: t+=1 for i in range(10): if a[(-1)*(i+1)] == c[(-1)*(i+1)]:t+=1 print('YES' if t>=10 else 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the au...
```python nums=int(input()) a=list(map(int, input().split())) m=a[0];mi=0 #m=Largest bid; mi=index of largest bid n=0 #Second largest number for i in range(1, nums): if a[i]>=m: n=m #Second largest bacomes equal to the previous largest one m=a[i] #New largest number mi=i #index of the largest bid...
MatrixStudio/Codeforces-Python-Submissions
Polycarp takes part in a math show. He is given *n* tasks, each consists of *k* subtasks, numbered 1 through *k*. It takes him *t**j* minutes to solve the *j*-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order. ...
```python def I(): return(list(map(int,input().split()))) def sieve(n): a=[1]*n for i in range(2,n): if a[i]: for j in range(i*i,n,i): a[j]=0 return a n,k,m=I() arr=I() arr.sort() pts=0 f=0 for i in range(k-2): currm=m pts+=min(n,currm//arr[i]) m-=min(currm//ar...
MatrixStudio/Codeforces-Python-Submissions
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment o...
```python n=int(input()) m=list(map(int,input().split())) c1=1 c2=1 for i in range(0,n-1): if m[i]<=m[i+1]: #print(m[i],m[i+1]) c2 +=1 elif m[i]>m[i+1]: if c2>c1: c1=c2 c2=1 if c2 > c1: c1 = c2 print(c1) ```
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 d = {'4':1 ,'7':2} res =0 for i in input(): res = res * 2 + d[i] #print(res) print(res) ```
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. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
```python def main(): inp = input() IL = len(inp) if IL == 7 or IL == 4: print("YES") else: print("NO") main() ```
MatrixStudio/Codeforces-Python-Submissions
The array *a* with *n* integers is given. Let's call the sequence of one or more consecutive elements in *a* segment. Also let's call the segment k-good if it contains no more than *k* different values. Find any longest k-good segment. As the input/output can reach huge size it is recommended to use fast input/output...
```python from collections import Counter n,k=map(int,input().split()) arr=list(map(int,input().split())) c=Counter() count=0 ans=[-1,-1] l=0 for r,el in enumerate(arr): c[el]+=1 if c[el]==1: count+=1 while count>k: c[arr[l]]-=1 if c[arr[l]]==0: count-=1 ...
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 n, m, a, b = map(int,input().split()) q=int(((n/m)//1)) p=n-(q*m) print((q*b)+(p*a)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
```python # Wadea # n = str(input()) r = "" for i in n: if n.count(i) > 1: pass else: r += i if len(r) == 0: print(n[0]) else: print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to *n*. Entrance *n* and entrance 1 are adjacent. Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance *a* and he decided that during his walk he will move around the house *b* entrances in th...
```python import math def solve(n,a,b): if b< 0: res=(n-(-1*b%n))+a else: res = b%n + a return res if res < n else res-n def main() : arr = list(map(int, input().split(' '))) # arr = [] # for _ in range(3): # arr.append(input()) print(solve(*arr)) main() ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person...
```python import sys serverTraffic = 0 activeUsers = 0 for line in sys.stdin: if line[0] == '+': activeUsers += 1 elif line[0] == '-': activeUsers -= 1 else: #serverTraffic += (activeUsers - 1) * (len(line) - line.find(':') - 1) serverTraffic += activeUsers * (len(line) - l...
MatrixStudio/Codeforces-Python-Submissions
Manao is trying to open a rather challenging lock. The lock has *n* buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the seque...
```python a=int(input()) count=0 j=1 arr=[] for i in range(a-1): count=count+j j=j+1 arr.append(count) print(sum(arr)+a) ```
MatrixStudio/Codeforces-Python-Submissions
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly *k* points, the score is reset and a new set begins. Across all the sets Misha scored *a* poi...
```python k,a,b=map(int,input().split()) if (a%k==0 or b%k==0) and (a!=0 and b!=0): print(a//k+b//k) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Vitaly has an array of *n* distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero (<=&lt;<=0). 1. The product of all numbers in the second set is greater than zero (<=&gt;<=0). 1. The produ...
```python # -*- coding: utf-8 -*- N = int(input()) a = [] for _ in range(N): _a = int(input()) a.append(_a) a.sort() print('ce pula mea de runtime error iti trebuie') ```
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()) c=0 k=0 for i in range(n+1): if i>0: if i%2!=0: c-=i else: k+=i print(c+k) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the *i*-th star on the pedal axle has *a**i* (0<=&lt;<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<...
```python n=int(input()) list1=list(map(int,input().split())) m=int(input()) list2=list(map(int,input().split())) max1=0 for i in list2: for j in list1: if i%j==0 and (i//j)>max1: max1=(i//j) c=0 for i in list2: for j in list1: if i%j==0 and i//j==max1: ...
MatrixStudio/Codeforces-Python-Submissions
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the *i*-th safe f...
```python ###################################################### def convert_inp_to_int(): return [int(x) for x in input().strip().split()] ####################################################### def get_position(flag,n,notes_at,pos): if(flag): i=0 while(i<n): if(notes_at[i]>pos): return (i-1) i+...
MatrixStudio/Codeforces-Python-Submissions
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into *k* lines not shorter than *a* and not longer than *b*, for the text to resemble h...
```python k, a, b = map(int, input().split()) s = input() n = len(s) if n > k*b or n < k*a: print("No solution") exit() r = n % k i, j = 0, n//k while i < n: if r: r -= 1 print(s[i:i+j+1]) i += j i += 1 else: print(s[i:i+j+1]) i += j ...
MatrixStudio/Codeforces-Python-Submissions
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that: - there are exactly *n* pixels o...
```python n = int(input()) a = 1 ans = 10**18 while a*a <= n: if n%a == 0: b = n//a if b-a < ans: ans = b-a ans_a = a a+=1 print(ans_a, n//ans_a) ```
MatrixStudio/Codeforces-Python-Submissions
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ...
```python n = int(input()) word = input() isKey = True keys = [] buy = 0 for pos in range(len(word)): if(isKey): keys.append(word[pos].upper()) isKey = False else: isKey = True if (word[pos] not in keys): buy += 1 else: keys.remove(word[pos]...
MatrixStudio/Codeforces-Python-Submissions
Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that...
```python l = input() l = l.split() l[0] = int(l[0]) l[1] = int(l[1]) l1 = input() l1 = l1.split() for i in range(len(l1)): l1[i] = int(l1[i]) l1.sort() d = float("inf") for j in range(len(l1)-1): d = min(d, abs(l1[i+1] - l1[i])) print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a game. Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players ...
```python n = int(input()) i = (n // 2) - (n % 2 == 0) print(list(sorted(map(int, input().split())))[i]) ```
MatrixStudio/Codeforces-Python-Submissions
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers fr...
```python sum = 0 i = 0 ans = "NO" t = int(input()) while sum <= t: i += 1 sum += i if sum == t: ans = "YES" print(ans) ```
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 # SOLUTION 1 # a,b,c,d = map(int,input().split()) # s = input() # print(s.count("1")*a+s.count("2")*b+s.count("3")*c+s.count("4")*d) # SOLUTION 2 # a,b,c,d = map(int,input().split()) # sum = 0 # for w in input(): # if w == "1": # sum += a # elif w == "2": # sum += b # ...
MatrixStudio/Codeforces-Python-Submissions
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given *n*, print the last digit of 1378*n*. Mehrdad has become quite confused and wants you to help him. Please help, al...
```python n=int(input()) p=1 for i in range(n): p=p*1378 plist=list(str(p)) print(plist[-1]) ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant very much loves sums on intervals. This time he has a pair of integers *l* and *r* (*l*<=≤<=*r*). The Little Elephant has to find the number of such integers *x* (*l*<=≤<=*x*<=≤<=*r*), that the first digit of integer *x* equals the last one (in decimal notation). For example, such numbers as 101, 4...
```python arr=list(map(int,input().split())) ans=0 for i in range(arr[0],arr[1]+1): if(i%10==i//(10**math.log10(i)): ans+=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti...
```python n = int(input()) l = list(map(int, input().split())) l1 = l.copy() l1.sort() if l1[0]==l1[1]: print("Still Rozdil") else: mini = l1[0] index = 0 for i in range(len(l)): if l[i] == mini: index = i break print(index+1) ```
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 from math import * a,b,c=map(int,input().split()) p=min(a,b) k=max(a,b) s=k-p if s>=c: ans=2*(p+c) else: ans=2*(k+(c-s)//2) print(ans) ```
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 s = input() yes = False leftMostAB = -1 leftMostBA = -1 rightMostAB = -1 rightMostBA = -1 for i in range(len(s)-1): if s[i:i+2] == "AB": leftMostAB = i if s[i:i+2] == "BA": leftMostBA = i for i in range(len(s)-2,-1,-1): if s[i:i+2] == "AB": rightMostAB = i ...
MatrixStudio/Codeforces-Python-Submissions
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights. Polycarpus has bought a posh piano and is thinking about how to get it into the h...
```python n, k = [int(i) for i in input().split()] h = [int(i) for i in input().split()] sum_min = sum(h) j = 0 for curr_j in range(n-k): print(curr_j) if sum(h[curr_j:curr_j+k]) < sum_min: sum_min = sum(h[curr_j:curr_j+k]) j = curr_j print(j+1) ```
MatrixStudio/Codeforces-Python-Submissions
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en...
```python n = int(input()) l = input().split(" ") ans = 1 for i in l: ans = ans * int(i) print(ans) ```
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 #-------------Program-------------- #----Kuzlyaev-Nikita-Codeforces---- #-------------Training------------- #---------------------------------- n=int(input()) a=list(map(int,input().split())) b=0;c=0 for i in range(n): if a[i]<0:c-=a[i] else: b+=a[i] print(b-c) ```
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 A. Vasya and String ```
MatrixStudio/Codeforces-Python-Submissions
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of *n* vertices. For each vertex *v* from 0 to *n*<=-<=1 he wrote down two integers, *degree**v* and *s**v*, were the first integer is the number of vertices adjacent to vertex ...
```python from collections import deque n = int(input()) process = deque() vs = [] for i in range(n): d, s = map(int, input().split()) if d == 1: process.append(i) vs.append((d, s)) edges = [] while process: a = process.popleft() d, s = vs[a] if d == 0: continue ...
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 import re n = int(input()) string = input() is_match = re.findall(r'01|10', string) matcheo = string while is_match: matcheo = re.sub(r'01|10', '', matcheo) is_match = re.findall(r'01|10', matcheo) print(0) if not matcheo else print(len(matcheo)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it la...
```python a, b = map(int,input().split()) c = 0 d = a for i in range(0, a): if i % b == 0: a = a + 1 print(int(d + a//b)) ```
MatrixStudio/Codeforces-Python-Submissions
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surround...
```python import math class Point: def __init__(self, x, y): self.x = x self.y = y def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def distance(self, other): dx = abs(self.x - other.x) dy = abs(self.y - other.y) ret...
MatrixStudio/Codeforces-Python-Submissions
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. E...
```python t=int(input()) d=[] for i in range(t): n=input() d.append(n) k=d[0] for i in range(len(d)): if(d.count(d[i])>d.count(k)): k=i print(k) ```
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 str = input() lower, upper = 0, 0 for i in range(len(str)): if (str[i].isupper()): upper += 1 else: lower += 1 if (lower < upper): print(str.upper()) else: print(str.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were *x* details in the factory storage, then by the end of the day the factory has to produce (remainder after dividing *x* by *m*) more details. Unfortunately, no cu...
```python a,m = map(int,input().split()) s = set() flag = 0 while 1: if a>m: a %= m if a in s: break s.add(a) a *= 2 if a==m: flag = 1 break if flag: print("Yes") else: print("No") ```
MatrixStudio/Codeforces-Python-Submissions
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0. It is allowed to leave *a* as it is.
```python a=input() b=input() na=len(a) nb=len(b) if(na<nb): print("".join(sorted(list(a),reverse=True))) else: if(a==b): print(a) l=sorted(list(a),reverse=True) l2=l.copy() ans1="" ans2="" flag=0 for i in b: for j in range(len(l)): if i==l[j]: ans1+=l[j] l.pop(j) break if i>l[j]: ans1...
MatrixStudio/Codeforces-Python-Submissions
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string *s* with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maxi...
```python import sys import math import collections import heapq input=sys.stdin.readline s=input() n=len(s)-1 c=s.count('VK') for i in range(n): if(s[i]=='V'): s1=s[:i]+'K'+s[i+1:] else: s1=s[:i]+'V'+s[i+1:] c=max(c,s1.count('VK')) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could ha...
```python l=list(input()) count=0 ans=0 for i in range(len(l)): if count==0: count+=1 print(ans,1) if 0< count<5 and l[i]==l[i-1]: count+=1 print(ans,2) if 0< count<5 and l[i]!=l[i-1]: ans+=1 count=1 print(ans,3) if count==5: ...
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant loves chess very much. One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8<=×<=8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard d...
```python bad = False for i in range(8): row = input().strip() if row not in ('WBWBWBWB', 'BWBWBWBW'): bad = True if bad: print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a...
```python m = [int(i) for i in input().split(" ")] w = [int(i) for i in input().split(" ")] hs, hu = [int(i) for i in input().split(" ")] score = 0 for i in range(5): score += max(0.3 * 500 * (i+1), (1 - m[i]/250) * (500 * (i+1)) - 50 * w[i]) score += 100 * hs score -= 50 * hu print(int(score)) ```
MatrixStudio/Codeforces-Python-Submissions
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an...
```python n = input() s= len(n) j =n.count('RU' and 'UR') print((s-(j*2))+j-1) ```
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 n=int(input()) m=1000000007 f=0 g=1 for i in range(1,n): t=f+0 f=(3*g)%m g=(2*g+t)%m print(f) ```
MatrixStudio/Codeforces-Python-Submissions
An *n*<=×<=*n* table *a* is defined as follows: - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the ...
```python n=int(input()) arr=[1,5,15,35,70,126,210,230,395] print(arr[n-1]) ```
MatrixStudio/Codeforces-Python-Submissions
After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first...
```python import sys n, m = map(int, sys.stdin.readline().split()) res = (n // 5) * (m // 5) * 5 res += (n // 5) * (m % 5) res += (m // 5) * (n % 5) for i in range(1, (n % 5) + 1): for j in range(1, (m % 5) + 1): if (i + j) % 5 == 0: res += 1 print(res) ```
MatrixStudio/Codeforces-Python-Submissions
You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in su...
```python import sys input = sys.stdin.readline g = sorted([input()[:-1] for _ in range(int(input()))], key=len) for i in g[:-1]: if i not in g[-1]: print("NO") break else: print("YES") for i in g: print(i) ```
MatrixStudio/Codeforces-Python-Submissions
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
```python s = input() mc = -1 for i in range(len(s)): for j in range(i+1, len(s)): cu = 0 for cu in range(len(s)-max(i, j)): if s[i+cu] == s[j+cu]: mc = max(mc, cu) else: break print(mc + 1) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*. Pasha likes rectangles but hates squares, so he wonders, how many ways are there to ...
```python n=int(input()) ans=0 for i in range(1,n//2+1): i1=i i2=n//2-i if(i1<i2): ans+=1 else: break print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dis...
```python n = int(input()) s = input() a = [*map(int, input().split())] mn = 99**99 for i in range(len(s)-2): if s[i:i+2] != 'RL': continue mn = min(mn, a[i+1]-a[i]>>1) print(mn if mn < 99**99 else~ 0) ```
MatrixStudio/Codeforces-Python-Submissions
*n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that coul...
```python from math import comb a,b = list(map(int,input().split())) if b == 1: print((comb(a,2)),comb(a,2)) else: m = a-b+1 if m%2: mx = comb(m-1,2) + 1 else: mx = comb(m,2) p = a//b q = a%b mn = (b-q)*comb(p,2) + q*(comb(p+1,2)) print(...
MatrixStudio/Codeforces-Python-Submissions
*n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that coul...
```python import math n, m = map(int, input().split()) teams = [0] * m f = n // m for i in range(m): teams[i] += f if n % m > 0: teams[0] += 1 ansMin = 0 for i in teams: ansMin += math.comb(i, 2) ansMax = math.comb(n-(m-1), 2) print(ansMin, ansMax) ```
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 board = input().split(" ") m = int(board[0]) n = int(board[1]) area = m * n print(area // 2) ```
MatrixStudio/Codeforces-Python-Submissions
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he...
```python n,p,q,r=map(int,input().split()) arr=list(map(int,input().strip().split())) pi,qj,rk= -1000000001,-1000000001,-1000000001 for i in range(n): x=arr[i] pi=max(pi,x*p) qj=max(qj,x*q) rk=max(rk,x*r) print(pi+qj+rk) ```
MatrixStudio/Codeforces-Python-Submissions
Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't wat...
```python s = list(map(int,input().split())) list_of_lengths = list(map(int,input().split())) a = [] for j in list_of_lengths: if(s[1]%j ==0): a.append(int(s[1]//j)); print(min(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. ...
```python import sys read = lambda: sys.stdin.readline().strip() readi = lambda: map(int, read().split()) from collections import * original = read() output = read() mapping = dict() for i in range(len(original)): key = original[i] val = output[i] if key in mapping: if mapping[key] ...
MatrixStudio/Codeforces-Python-Submissions
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
```python n = int(input()) count = n // 100 + (n % 100) // 20 + (n % 20) // 10 + (n % 10) // 5 + (n % 5) print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored...
```python n = int(input()) bits = input() counter = 1 i = 0 while i < n-1 and bits[i] == '1': counter += 1 i += 1 print(counter) ```
MatrixStudio/Codeforces-Python-Submissions
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees. A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *...
```python import bisect import math from collections import deque import heapq import functools from queue import Queue mod = 998244353 N = 200005 def mul(a, b): return (a*b)%mod def add(a, b): return (a+b) if (a+b<mod) else (a+b)-mod def sub(a, b): return (a-b) if (a-b>=0) else (a-b)+mod def powr(a, b): ans...
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 # cook your dish here n=input() s=input() res = '' for i in range(len(n)): res += str(int(s[i])^int(n[i])) print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya got bored and he painted *n* distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
```python import itertools n = int(input()) if n < 3: print(0) exit(0) pos = [list(tuple(map(int,input().split())))for _ in range(n)] max = 0 for ss in itertools.combinations(pos, 3): area = ss[0][0]*(ss[1][1]-ss[2][1]) + ss[1][0]*(ss[2][1]-ss[0][1]) + ss[2][0]*(ss[0][1]-ss[1][1]) if area == ...
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 #刘乐天 2300012105 生命科学学院 i=int(input()) for i in range(0,i): a=input() b=len(a)-2 if b>8: print(a[0]+str(b)+a[-1]) else: print(a) ```
MatrixStudio/Codeforces-Python-Submissions
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into *a* pieces, and the second one — into *b* pieces. Ivan knows that there will be *n* people at the celebration (including himself), so Ivan has set ...
```python from math import floor inputs = input().split(' ') n = int(inputs[0]) a = int(inputs[1]) b = int(inputs[2]) cur_max = floor((a + b) / n) while True: for i in range(n): if cur_max * i <= a and cur_max * (n-i) <= b: print(cur_max) exit() cur_max -= 1 p...
MatrixStudio/Codeforces-Python-Submissions
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gr...
```python n, k = [int(x) for x in input().split()] s = input() ti = s.index('T') gi = s.index('G') d = abs(gi - ti) r = d % k if r!= 0: print("NO") else: if ti < gi: ti, gi = gi, ti bad = False for i in range(gi + k, ti, k): if s[i] == '#': bad = True ...
MatrixStudio/Codeforces-Python-Submissions
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not....
```python s = input() stack = [] ans = 0 c = 0 c1 = 0 for i in range(len(s)): if s[i] == "(": stack.append(s[i]) c+=1 else: if len(stack) == 0: pass else: p = stack.pop() if len(stack) == 0: if ans < (2*c): ...
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 s=input() b=True for x in range(1,len(s)): i=s[:len(s)-x] e=s[x:] if(i==e and i in s[1:-1]): print(i) b=False break if(b): print("Just a legend") ```
MatrixStudio/Codeforces-Python-Submissions
Buses run between the cities *A* and *B*, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city *A* departs every *a* minutes and arrives to the city *B* in a *t**a* minutes, and a bus from the city *B* departs every *b* minutes and arrives to the city *A* in a *t**b* min...
```python a, ta = map(int, input().split()) b, tb = map(int, input().split()) h, m = map(int, input().split(':')) time = h * 60 + m basetime = 300 if time - basetime >= tb: ans = (ta + tb) // b if ta == tb: ans -= 1 else: ans = (time - basetime + ta) // b print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression *b* defined by two integers *b*1 and *q*. Remind that a geometric progression is a sequence of integers *b*1,<=*b*2,<=*b*3,<=..., where for each *i*<=&gt;<=1 the respective term satisfi...
```python import math b, q, l, m = list(map(int,input().split(" "))) a = set(map(int,input().split(" "))) if q == 1: if b in a: ans = 0 else: ans = "inf" elif q == -1: if b in a and -b in a: ans = 0 else: ans = "inf" else: # Finite progression #...
MatrixStudio/Codeforces-Python-Submissions
There are *n* walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the *n*-th walrus stands at the beginning of the queue. The *i*-th walrus has the age equal to *a**i*. The *i*-th walrus becomes displeased if there's a younger...
```python n = int(input()) l = list(map(int,input().split())) for i in range(len(l)-1): if l[i] > l[i+1]: j = i c = 0 while l[i] > l[j+1]: c += 1 if j+1 == len(l) - 1: break j += 1 print(c-1,end=" ") else: p...
MatrixStudio/Codeforces-Python-Submissions
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations wil...
```python a,b,c,d=map(int,input().split()) if a//b==0:print(0) elif b>a: k=abs((b-a)*c);l=abs(a*d) if k<l:print(k) else:print(l) elif a>b: k=(b-(a%b))*c;l=(a%b)*d if k<l:print(k) else:print(l) ```
MatrixStudio/Codeforces-Python-Submissions
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings *a* and *b*, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence ...
```python m = input() n = intput() if len(n) == len(m) and m != n : print(-1) else : print(max(len(n) , len(m))) ```
MatrixStudio/Codeforces-Python-Submissions
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length *L*, in distinct points of which there are *n* barriers. Athlete always run the track in counterclockwise direction if...
```python import sys; inp = list(map(int,input().split(' '))); a = list(map(int,input().split(' '))); b = list(map(int,input().split(' '))); f = 0; a = sorted(a); #print(a); for i in range(inp[1]): #print(i); for j in range(inp[0]): b[j] = (b[j]+1)%inp[1]; if sorted(b) == a: prin...
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()) numbers = list(map(int, input().split(' '))) memo = {0: 0, 1: 0} for number in numbers: remainder = int(number % 2) memo[remainder] += 1 for index, number in enumerate(numbers, start=1): if memo[int(number % 2)] == 1: print(index) break ```
MatrixStudio/Codeforces-Python-Submissions
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,<=1]. Next, *n* stones will fall and Liss will escape from the stones. The stones are numbered from 1 to *n* in order. The stones always fall to the center of Liss's ...
```python if __name__=='__main__': s = input() ind = 2 l = [1] currpos = 0 for ch in s[0:len(s)-1]: if ch=='l': l.insert(currpos,ind) currpos = l.index(ind) else: l.insert(currpos+1,ind) currpos += 1 ind+=1 for ...
MatrixStudio/Codeforces-Python-Submissions
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
```python n=int(input()) l=list(map(int,input().split())) store=0 c=0 for i in l: if i>0: store+=i if store>0: if i<0: store-=1 else: c+=1 print(c) ```
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 ################################################################################ n,k=map(int, input().split()) h=list(map(int, input().split())) # n=3 # k=3 # h=[14,12,10] # n=4 # k=5 # h=[8,19,10,13] ################################################################################ max_a=0 i1=...
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix...
```python t=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=list(map(int,input().split())) summ1=sum(a) summ2=sum(b) summ3=sum(c) print(summ1-summ2) print(summ2-summ3) ```
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 from math import gcd def lcm(x, y): ans = (x*y)//gcd(x, y) return ans n, k = (map(int, input().split())) if k == 0: print(n) else: z = 10**k print(lcm(n, z)) ```
MatrixStudio/Codeforces-Python-Submissions
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en...
```python '''input 3 5 10 1 ''' n = int(input()) p = 1 for x in map(int, input().split()): p *= x print(p) ```
MatrixStudio/Codeforces-Python-Submissions
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero,...
```python m,n=map(int,input().split()) for i in range(n): if(m%10!=0): m=m-1 else: m=m//10 print(m) ```
MatrixStudio/Codeforces-Python-Submissions
You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length. The output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th cha...
```python a=input() b=input() for i in range(len(a)): if b[i]>a[i]: print(-1) exit(0) print(b) ```
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 for i in range(n): s=list(map(int,input().split())) a+=s[0] b+=s[1] c+=s[2] if a==b==c==0: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Mike is the president of country What-The-Fatherland. There are *n* bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to *n* from left to right. *i*-th bear is exactly *a**i* feet high. A group of bears is a non-empty contiguous segment of the line. The size of...
```python def strength(bears): return (max(min(bears[displacement:displacement + group_size]) for displacement in range(len(bears) - group_size + 1)) for group_size in range(1, len(bears) + 1)) useless = input() bears = input().split(' ') for i in strength(bears): print(i, end = ' ') ```
MatrixStudio/Codeforces-Python-Submissions
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
```python import math def lotto(money): bills = 0 while money != 0: bills += math.floor(money/100) money %= 100 bills += math.floor(money/20) money %= 20 bills += math.floor(money/10) money %= 10 bills += math.floor(money/5) money %= 5 bills += math.floor(money/1) money %= 1 ret...
MatrixStudio/Codeforces-Python-Submissions
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The...
```python n,m=map(int,input().split()) d=dict() for i in range(0,m): a,b,c=map(int,input().split()) if a in d: d[a]=d[a]+c else: d[a]=c if b in d: d[b]=d[b]-c else: d[b]=-c print(abs(sum([i for i in d.values() if i<0]))) ```
MatrixStudio/Codeforces-Python-Submissions
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-...
```python i = int(input()) a = 0 while i >= 10: a += 1 i = sum(int(x) for x in str(i)) print(a) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a string *s* consisting of |*s*| small english letters. In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter. Your target is to make some number...
```python import string alf = string.ascii_lowercase count = 0 s = list(input()) for i, el in enumerate(s): if alf.index(el) <= count: s[i] = alf[count] print(''.join(s)) count += 1 if count == 26: print(''.join(s)) exit(0) print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
In this problem you have to simulate the workflow of one-thread server. There are *n* queries to process, the *i*-th will be received at moment *t**i* and needs to be processed for *d**i* units of time. All *t**i* are guaranteed to be distinct. When a query appears server may react in three possible ways: 1. If ser...
```python #include <bits/stdc++.h> #include <tr1/unordered_map> typedef long long ll; typedef unsigned long long ull; #define clr(ma) memset(ma,-1,sizeof ma) #define inf 30000000; #define vi vector<int> #define pi pair<int,int> #define T2 pair<pi ,pi > #define mk make_pair #define getBit(m,i) ((m&(1<<i))==(1<...
MatrixStudio/Codeforces-Python-Submissions
Array of integers is unimodal, if: - it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arra...
```python n = int(input()) h = list(map(int, input().split())) p = 0 s = 0 for i in range(n-1): if h[i]<h[i+1]: if s>=1: print("NO") quit() if p>=1: print("NO") quit() elif h[i]>h[i+1]: p+=1 elif h[i]==h[i+1]: s+=...
MatrixStudio/Codeforces-Python-Submissions
There are *n* cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers *a*1,<=*a*2,<=...,<=*a**n*. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport d...
```python n = int(input()) ls = list(map(int, input().split())) ls.sort() k=[] for x in range(len(ls)-1): k.append(ls[x+1] - ls[x]) print (min(k), k.count(min(k))) ```