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 1, i.e. for all *i*'s from 1 to *n*<=-<=1 the inequality |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1 holds. At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1.
```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]: ans = max(ans,l[i][1]+(-(l[i][1]-l[i+1][1])+(l[i+1][0]-l[i][0]))//2) else: ans = max(ans,l[i][1]+(-(l[i][1]-l[i+1][1])+(l[i+1][0]-l[i][0]))//2) print(ans) ```
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 print(count+1) ```
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 sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters. Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.
```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: increase_count(letters, two_letter_maps, len(word)) elif len(letters) == 1: increase_count(letters, single_letter_maps, len(word)) for pairs in two_letter_maps: for letter in pairs: two_letter_maps[pairs] += get_count(letter, single_letter_maps) double_count = get_max(two_letter_maps) single_count = get_max(single_letter_maps) count = max(double_count, single_count) print(count) def get_count(key, dictionary): if key not in dictionary: return 0 return dictionary[key] def get_max(dictionary): if len(dictionary) == 0: return 0 return max(dictionary.values()) def increase_count(key, dictionary, value): if key not in dictionary: dictionary[key] = 0 dictionary[key] += value if __name__ == '__main__': main() ```
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 exit so that it becomes empty. Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.
```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$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $s$ minutes from both sides. Find the earliest time when Arkady can insert the takeoff.
```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 applying the operation of a bitwise xor to numbers *x* and *y*. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal — as "xor". In this problem you are asked to compute the number of sequences made of *n* integers from 0 to 2*m*<=-<=1 that are not a wool sequence. You should print this number modulo 1000000009 (109<=+<=9).
```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 English letters. There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc. Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.
```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 auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction). Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.
```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 else: if a[i]>=n: n=a[i] #Second largest number changes if there exists a number between 'n' and 'm' print(mi+1, n) ```
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. By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all *k* of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is *k*<=+<=1. Polycarp has *M* minutes of time. What is the maximum number of points he can earn?
```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//arr[i],n)*arr[i] if m<=0: f=1 break # print(m) if f or m<arr[-1]: print(pts) else: if arr[-1]<arr[-2]*2: pts+=(m//(arr[-1]+arr[-2]))*3 m-=(m//(arr[-1]+arr[-2]))*(arr[-1]+arr[-2]) if m: pts+=m//arr[-2] else: pts+=min(m//arr[-2],n) num=m//arr[-2] m-=(min(m//arr[-2],n))*arr[-2] if m and num>=n: pts+=(m//arr[-1])*2 print(pts) ```
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 of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order. Help Kefa cope with this task!
```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 are given a lucky number *n*. 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. If we sort all lucky numbers in increasing order, what's the 1-based index of *n*? Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
```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 digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.
```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 methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
```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 l+=1 if r-l+1>=ans[-1]-ans[0]+1: ans=[l+1,r+1] print(*ans) ```
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 minimum sum of money she will have to spend to make *n* rides?
```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 yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.
```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 the direction of increasing numbers (in this order entrance *n* should be followed by entrance 1). The negative value of *b* corresponds to moving |*b*| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance *n*). If *b*<==<=0, then Vasya prefers to walk beside his entrance. Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.
```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 to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands. Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends *l* bytes to each participant of the chat, where *l* is the length of the message. As Polycarp has no time, he is asking for your help in solving this problem.
```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) - line.find(':') - 2) print(serverTraffic) ```
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 sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens. Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock. Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.
```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* points in total, and Vanya scored *b* points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible. Note that the game consisted of several complete sets.
```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 product of all numbers in the third set is equal to zero. 1. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.
```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;<=*a**n*) teeth, and the *j*-th star on the rear wheel axle has *b**j* (0<=&lt;<=*b*1<=&lt;<=*b*2<=&lt;<=...<=&lt;<=*b**m*) teeth. Any pair (*i*,<=*j*) (1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (*i*,<=*j*) has a gear ratio, equal to the value . Since Vasya likes integers, he wants to find such gears (*i*,<=*j*), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (*i*,<=*j*) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears. In the problem, fraction denotes division in real numbers, that is, no rounding is performed.
```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: c=c+1 print(c) ```
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 from the left is called safe *i*. There are *n* banknotes left in all the safes in total. The *i*-th banknote is in safe *x**i*. Oleg is now at safe *a*. There are two security guards, one of which guards the safe *b* such that *b*<=&lt;<=*a*, i.e. the first guard is to the left of Oleg. The other guard guards the safe *c* so that *c*<=&gt;<=*a*, i.e. he is to the right of Oleg. The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.
```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+=1 return (i-1) else: i=0 while(i<n): if(notes_at[i]>=pos): return (i-1) i+=1 return (i-1) #################################################### abc=convert_inp_to_int() a=abc[0] b=abc[1] c=abc[2] n=convert_inp_to_int()[0] notes_at=convert_inp_to_int() notes_at.sort() #print(notes_at) oleg_pos=get_position(0,n,notes_at,a) g1_pos=get_position(1,n,notes_at,b) g2_pos=get_position(0,n,notes_at,c) g1_pos+=1 print(oleg_pos,g1_pos,g2_pos) if(g1_pos<g2_pos): print(g2_pos-g1_pos+1) else: print(0) ```
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 human speech more. Help Anfisa.
```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 i += 1 ```
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 on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible.
```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 room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1. The potato pie is located in the *n*-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F. Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door. Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*. Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
```python n = int(input()) 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]) print(buy) ```
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 are at the distance of at most *d* from it, where *d* is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius *d* should the lanterns have to light the whole street?
```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 alternate turns. The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it. You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
```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 from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number). Your task is to find out if a given integer is a triangular number.
```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 of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip. You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
```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 # elif w == "3": # sum += c # else : # sum += d # print(sum) #SOLUTION 3 l = list(map(int,input().split())) sum = 0 for w in input(): sum += l[int(w)-1] print(sum) ```
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, although it's a naive cheat.
```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, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not. Help him and count the number of described numbers *x* for a given pair *l* and *r*.
```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 time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere. For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
```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 exactly half of the players should play with their left hand. One player should use only on of his hands. Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand. Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.
```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 if s[i:i+2] == "BA": rightMostBA = i if leftMostAB+1 < rightMostBA or leftMostBA+1 < rightMostAB: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights. Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible. Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
```python 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 enough time to assign tanks into teams and the whole game will collapse! There are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
```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 sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?
```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 string. What is the maximum beauty of the string he can achieve?
```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 *v*, and the second integer is the XOR sum of the numbers of vertices adjacent to *v* (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values *degree**v* and *s**v* left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
```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 dd, ss = vs[s] vs[s] = (dd - 1, ss ^ a) if dd == 2: process.append(s) edges.append((a, s)) print(len(edges)) for a, b in edges: print(a,b) ```
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, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result. Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
```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 late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
```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 surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities. The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most *r* from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most *r*). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (*r*) is, the more the radar costs. That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius *r* (*r*<=≥<=0) such, that a radar with radius *r* can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.
```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) return math.hypot(dx, dy) def float_eq(a, b): return abs(a - b) < 1e-9 def main(): ax, ay, ar = map(int, input().split()) bx, by, br = map(int, input().split()) point_a = Point(ax, ay) point_b = Point(bx, by) p_dist = point_a.distance(point_b) r_sum = ar + br if float_eq(p_dist, r_sum): return print(0) if p_dist > r_sum: return print((p_dist - r_sum) / 2) if p_dist > ar: return print(0) print(abs(ar - br) / 2) main() ```
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. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
```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 that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```python 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 customer has ever bought any mythical detail, so all the details produced stay on the factory. The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by *m*). Given the number of details *a* on the first day and number *m* check if the production stops at some moment.
```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+=l[j] l.pop(j) flag=1 break if(flag==1): break ans1+="".join(l) flag=0 for i in b: for j in range(len(l2)): if i>l2[j]: ans2+=l2[j] l2.pop(j) flag=1 break if(flag==1): break ans2+="".join(l2) if(int(ans1)<=int(b)): print(ans1) else: print(ans2) ```
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 maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.
```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 have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all. The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*.
```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: ans+=1 count=1 print(ans,4) print(ans+1) ```
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 doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation multiple times (or not run it at all). For example, if the first line of the board looks like that "BBBBBBWW" (the white cells of the line are marked with character "W", the black cells are marked with character "B"), then after one cyclic shift it will look like that "WBBBBBBW". Help the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.
```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 as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score. Codeforces scores are computed as follows: If the maximum point value of a problem is *x*, and Kevin submitted correctly at minute *m* but made *w* wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack. All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.
```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 any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left. Your problem is to print the minimum possible length of the sequence of moves after the replacements.
```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. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
```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 remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. These conditions define all the values in the table. You are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.
```python n=int(input()) 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 column and the other from the second column, such that their sum is divisible by 5. Formally, Alyona wants to count the number of pairs of integers (*x*,<=*y*) such that 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* and equals 0. As usual, Alyona has some troubles and asks you to help.
```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 such a way that they form $a$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".
```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 split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square. Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way.
```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 distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers. You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time. Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
```python 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 could have formed by the end of the competition.
```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(mn,mx) ```
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 could have formed by the end of the competition.
```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 two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python 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 wants to give Dumbledore exactly *x* drops of the potion he made. Value of *x* is calculated as maximum of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* for given *p*,<=*q*,<=*r* and array *a*1,<=*a*2,<=... *a**n* such that 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*. Help Snape find the value of *x*. Do note that the value of *x* may be negative.
```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 water the ground outside the garden. Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length *a**i* if she chooses the *i*-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden. See the examples for better understanding.
```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. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard. You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
```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] != val: print(-1) break if val in mapping: if mapping[val] != key: print(-1) break if key != val: mapping[key] = val mapping[val] = key else: n = len(mapping)//2 print(n) keys = list(mapping.keys()) for key in keys: if key in mapping: print(key, mapping[key]) mapping.pop(mapping[key]) mapping.pop(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 in the second bit, and so on; the most significant bit is stored in the *n*-th bit. Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded. Sergey wrote certain values ​​of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
```python n = int(input()) 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, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below. Dr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add? A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
```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 = 1 while b>0: if b & 1: ans=mul(ans,a) a = mul(a,a) b//=2 return ans def inv(n): return powr(n, mod-2) def factlist(): fact = [1] for i in range(1, N): fact.append(mul(fact[i-1],i)) return fact def invfactlist(fact): invfact=[0]*N invfact[0]=1 invfact[N-1]= inv(fact[N-1]) for i in range(N-2, 0, -1): invfact[i]= mul(invfact[i+1],(i+1)) return invfact def rot(S): return list(zip(*S[::-1])) def gcd(a, b): if b==0: return a return gcd(b, a%b) def generate(): ans = [0] while ans[-1]<1000000000: ans.append(1+ans[-1]*2) return ans def main(): n=int(input()) g=[[]*n for _ in range(n)] for i in range(n-1): u,v=map(int,input().split()) g[u-1].append(v-1) g[v-1].append(u-1) queue=Queue() d=[-1]*n for i in range(n): if(d[i]==-1): d[i]=0 queue.put(i) while(not queue.empty()): u=queue.get() for v in g[u]: if(d[v]==-1): d[v]=1-d[u] queue.put(v) l=d.count(0) r=n-l print(l*r-(n-1)) if __name__ == "__main__": main() ```
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 calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```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 == 1: max = max + 1 print(max) ```
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 like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes. Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
```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 *n* plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met: 1. Each piece of each cake is put on some plate; 1. Each plate contains at least one piece of cake; 1. No plate contains pieces of both cakes. To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number *x* such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least *x* pieces of cake. Help Ivan to calculate this number *x*!
```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 print(1) ```
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 grasshopper wants to eat the insect. Ostap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell. Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.
```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 break if bad: print("NO") else: print("YES") ```
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. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
```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): ans = (2*c) c1 = 1 elif ans == (2*c): ans = (2*c) c1+=1 c=0 if ans == 0: print(ans,1) else: print(ans,c1) ```
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 temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*. Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end. Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened. You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.
```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* minutes. The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish. You know the time when Simion departed from the city *A* to the city *B*. Calculate the number of buses Simion will meet to be sure in his counting.
```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 satisfies the condition *b**i*<==<=*b**i*<=-<=1·*q*, where *q* is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both *b*1 and *q* can equal 0. Also, Dvastan gave Masha *m* "bad" integers *a*1,<=*a*2,<=...,<=*a**m*, and an integer *l*. Masha writes all progression terms one by one onto the board (including repetitive) while condition |*b**i*|<=≤<=*l* is satisfied (|*x*| means absolute value of *x*). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term. But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
```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 # b_n = b_1*q^(n-1): |b_n| <= l -> |b_1*q^(n-1)| <= l # (log(l)-log(|b_1|))/ log(q) + 1 >= n max_num = int((math.log(l) - math.log(abs(b))) / math.log(q) + 1) # a/b == 0 mod (q) bad_count = sum(map(lambda x: x <= l and (math.log(x/b)/math.log(q)) % 1 == 0, a)) # print(bad_count) ans = max_num - bad_count print(ans) ```
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 walrus standing in front of him, that is, if exists such *j* (*i*<=&lt;<=*j*), that *a**i*<=&gt;<=*a**j*. The displeasure of the *i*-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the *i*-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of *n* walruses in the queue his displeasure.
```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: print("-1 ",end="") print(-1) ```
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 will be upset. So each box should be occupied by exactly one delegation. If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment. Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes. What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?
```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 of one of them and not a subsequence of the other. A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
```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 you look on him from above. All barriers are located at integer distance from each other along the track. Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the *n* barriers. Thus, each of them wrote *n* integers in the ascending order, each of them was between 0 and *L*<=-<=1, inclusively. There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks. Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction — counterclockwise, if you look on a track from above.
```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: print("YES"); sys.exit(); print('NO'); ```
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 is different in evenness.
```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 interval. When Liss occupies the interval [*k*<=-<=*d*,<=*k*<=+<=*d*] and a stone falls to *k*, she will escape to the left or to the right. If she escapes to the left, her new interval will be [*k*<=-<=*d*,<=*k*]. If she escapes to the right, her new interval will be [*k*,<=*k*<=+<=*d*]. You are given a string *s* of length *n*. If the *i*-th character of *s* is "l" or "r", when the *i*-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the *n* stones falls.
```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 i in l: print(i) ```
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 officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated. Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
```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 published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than *k* millimeters. The library has *n* volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is *h**i*. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.
```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=0 mincup=h[0] maxcup=h[0] for i in range(1,n): if h[i]<mincup: mincup=h[i] if h[i]>maxcup: maxcup=h[i] while maxcup-mincup>k and i1!=i: if mincup==h[i1]: mincup=min(h[i1+1:i+1]) if maxcup==h[i1]: maxcup=max(h[i1+1:i+1]) i1+=1 if i-i1+1>max_a: max_a=i-i1+1 i1=0 mincup=h[0] maxcup=h[0] out=[] for i in range(1,n): if h[i]<mincup: mincup=h[i] if h[i]>maxcup: maxcup=h[i] while maxcup-mincup>k and i1!=i: if mincup==h[i1]: mincup=min(h[i1+1:i+1]) if maxcup==h[i1]: maxcup=max(h[i1+1:i+1]) i1+=1 if i-i1+1==max_a: out.append([i1+1,i+1]) print(max_a,len(out)) for out1 in out: print(out1[0],out1[1]) ```
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 some mistake and then another one mistake. However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change. Can you help B find out exactly what two errors he corrected?
```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. Write a program that will perform the *k*-rounding of *n*.
```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 enough time to assign tanks into teams and the whole game will collapse! There are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
```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, she divides the number by 10 (i.e. removes the last digit). You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions. It is guaranteed that the result will be positive integer number.
```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 character of *s*1 and the *i*-th character of *s*2. For example, *f*("ab", "ba") = "aa", and *f*("nzwzl", "zizez") = "niwel". You found two strings *x* and *y* of the same length and consisting of only lowercase English letters. Find any string *z* such that *f*(*x*,<=*z*)<==<=*y*, or print -1 if no such string *z* exists.
```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 Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
```python 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 a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group. Mike is a curious to know for each *x* such that 1<=≤<=*x*<=≤<=*n* the maximum strength among all groups of size *x*.
```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 return bills print(lotto(int(input()))) ```
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 debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has *n* people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
```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-digit?
```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 of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.
```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 server is free and query queue is empty, then server immediately starts to process this query. 1. If server is busy and there are less than *b* queries in the queue, then new query is added to the end of the queue. 1. If server is busy and there are already *b* queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment *x*, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears. For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.
```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<<i)) #define setBit(m,i) (m|(1<<i)) #define setBit2(m,i) (m|(1ull<<i)) #define cont(i,ma) ((ma.find(i))!=(ma.end())) #define in(i) scanf("%d",&i) #define in2(i,j) scanf("%d%d",&i,&j) #define in3(i,j,k) scanf("%d%d%d",&i,&j,&k) #define in4(i,j,k,l) scanf("%d%d%d%d",&i,&j,&k,&l) #define il(i) scanf("%I64d",&i) #define itr map<ll,ll>::iterator #define itr2 map<ll,map<ll,ll> >::iterator #define id(k) scanf("%9lf",&k) #define fi(ss) freopen (ss,"r",stdin) #define fo(ss) freopen (ss,"w",stdout) #define clean(vis) memset(vis,0,sizeof vis) using namespace std; int t [200000+10]; int d[200000+10]; int n,b; int state; int pos; queue<int> q; ll res[200000+10]; ll ct; int main(){ in2(n,b); for(int i=0;i<n;i++)in2(t[i],d[i]); state=1; pos=0; ct=0; while(1){ if (state==1){ if (q.empty() && pos>=n)break; if (q.empty()){ res[pos]=t[pos]+d[pos]; ct=t[pos]+d[pos]; pos++; } else{ int v=q.front(); q.pop(); res[v]=ct+d[v]; if (pos<n && t[pos]==ct){ q.push(pos++); } ct=ct+d[v]; } state=2; } else{ while (pos<n && t[pos]<ct){ if (q.size()<b)q.push(pos); else res[pos]=-1; pos++; } state=1; } } for (int i=0;i<n;i++)cout<<res[i]<<" "; } ```
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 arrays are unimodal: [5,<=7,<=11,<=11,<=2,<=1], [4,<=4,<=2], [7], but the following three are not unimodal: [5,<=5,<=6,<=6,<=1], [1,<=2,<=1,<=2], [4,<=5,<=5,<=6]. Write a program that checks if an array is unimodal.
```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+=1 if p>=1: print("NO") quit() print("YES") ```
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 decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
```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))) ```