source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
You are given *n* switches and *m* lamps. The *i*-th switch turns on some subset of the lamps. This information is given as the matrix *a* consisting of *n* rows and *m* columns where *a**i*,<=*j*<==<=1 if the *i*-th switch turns on the *j*-th lamp and *a**i*,<=*j*<==<=0 if the *i*-th switch is not connected to the *j*-th lamp. Initially all *m* lamps are turned off. Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards. It is guaranteed that if you push all *n* switches then all *m* lamps will be turned on. Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other *n*<=-<=1 switches then all the *m* lamps will be turned on.
```python def dfs(v,graph,flag,vnt): vnt[v] = 1 flag[v] = True for i in range(len(graph[v])): if(flag[graph[v][i]] == False): dfs(graph[v][i],graph,flag,vnt) vnt[v] += vnt[graph[v][i]] n = int(input()) graph = [[] for _ in range(n+1)] flag = [False]*(n+1) vnt = [0]*(n+1) for _ in range(n-1): u,v = input().split() graph[int(u) -1].append(int(v) -1) graph[int(v) -1].append(int(u) -1) dfs(0,graph,flag,vnt) ans = 0 for i in range(1,n): if(vnt[i]%2 == 0): ans += 1 if(n%2 != 0): print(-1) else: print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment. Vitaly sees a building of *n* floors and 2·*m* windows on each floor. On each floor there are *m* flats numbered from 1 to *m*, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·*m* from left to right, then the *j*-th flat of the *i*-th floor has windows 2·*j*<=-<=1 and 2·*j* in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on. Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.
```python f = 0 v = [] n,m = map(int,input().split()) for i in range(n): l = list(map(int,input().split())) for j in range(len(l)): v.append(l[j]) for i in range(0,len(v)-1,2): if v[i] == 1 or v[i+1] == 1: f+=1 print(f) ```
MatrixStudio/Codeforces-Python-Submissions
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are *m* types of discounts. We assume that the discounts are indexed from 1 to *m*. To use the discount number *i*, the customer takes a special basket, where he puts exactly *q**i* items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the *q**i* items in the cart. Maxim now needs to buy *n* items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well. Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
```python m = int(input()) q = [int(i) for i in input().split()] n = int(input()) a = [int(i) for i in input().split()] c = min(q) a.sort() price = 0 for i in range(n): if i % (c+2) < c: price += a[n-1-i] print(price) ```
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 x = input().split() l = int(x[0]) r = int(x[1]) a = int(x[2]) min1 = min(l,r) max1 = max(l,r) diff = max1 - min1 if diff > 0: if diff > a: print((min1+a)*2) else: a-=diff divide = int(a/2) print((max1+divide)*2) else: print((min1+int(a/2))*2) ```
MatrixStudio/Codeforces-Python-Submissions
We'll define *S*(*n*) for positive integer *n* as follows: the number of the *n*'s digits in the decimal base. For example, *S*(893)<==<=3, *S*(114514)<==<=6. You want to make a consecutive integer sequence starting from number *m* (*m*,<=*m*<=+<=1,<=...). But you need to pay *S*(*n*)·*k* to add the number *n* to the sequence. You can spend a cost up to *w*, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.
```python w, m, k = [int(i) for i in input().split()] s = lambda n: len(str(n)) cost = s(m)*k seqLen = 0 while cost <= w: m += 1 cost += s(m)*k seqLen += 1 #print('cost: ',cost,' m: ',m,' w: ',w) print(seqLen) ```
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 l,r,a = map(int,input().split()) total = 0 if min(l,r)+a<=l or min(l,r)+a<=r: minemum = min(l,r)+a total=minemum*2 else: minemum = min(l,r)+a a = minemum-max(l,r) minemum = max(l,r) total=(minemum*2)+(a) if total%2==0: print(total) else: print(total-1) ```
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()) sum_coordinates = [] new_list = [] for i in range(n): sum_coordinates.append(list(map(int, input().split()))) new_list = [sum(x) for x in zip(*sum_coordinates)] if sum(new_list) == 0 or new_list[0] == 0 and new_list[1] == 0 and new_list[2] == 0: print("YES") elif new_list[0] != 0 and new_list[1] != 0 and new_list[2] != 0: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Vladik had started reading a complicated book about algorithms containing *n* pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation *P*<==<=[*p*1,<=*p*2,<=...,<=*p**n*], where *p**i* denotes the number of page that should be read *i*-th in turn. Sometimes Vladik’s mom sorted some subsegment of permutation *P* from position *l* to position *r* inclusive, because she loves the order. For every of such sorting Vladik knows number *x* — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has *p**x* changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.
```python n, m = list(map(int, input().split())) pages = list(map(int, input().split())) res = [] inputs = [list(map(int, input().split())) for _ in range(m)] for row in inputs: l, r, x = row not_changed = "Yes" if l <= x <= r: el = pages[x - 1] seg = pages[l - 1:r] seg.sort() if seg[x - l] != el: not_changed = "No" res += [not_changed] for i in res: print(i) ```
MatrixStudio/Codeforces-Python-Submissions
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at *a*1 percent and second one is charged at *a*2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger). Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops. Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent.
```python energy1, energy2 = map(int, input().split()) i = 0 connected = 1 while True: if connected == 1: if energy2 < energy1: connected = 2 energy1 -= 2 energy2 += 1 else: energy1 += 1 energy2 -= 2 else: if energy1 < energy2: connected = 1 energy2 -= 2 energy1 += 1 else: energy1 -= 2 energy2 += 1 if energy1 <= 0 or energy2 <= 0: break i += 1 print(i) ```
MatrixStudio/Codeforces-Python-Submissions
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test. You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
```python n = int(input()) a = sorted([int(i) for i in input().split()]) for i in a: if i+1 not in a: print(i+1) exit() ```
MatrixStudio/Codeforces-Python-Submissions
Right now she actually isn't. But she will be, if you don't solve this problem. You are given integers *n*, *k*, *A* and *B*. There is a number *x*, which is initially equal to *n*. You are allowed to perform two types of operations: 1. Subtract 1 from *x*. This operation costs you *A* coins. 1. Divide *x* by *k*. Can be performed only if *x* is divisible by *k*. This operation costs you *B* coins.
```python n=int(input()) k=int(input()) A=int(input()) B=int(input()) s=0 while n>1: #print('n='+str(n)) #print('s='+str(s)) if n<k: s+=A*(n-1) break r=n%k if r>0: s+=r*A n-=r else: m=n//k s+=min((n-m)*A,B) n=m print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Evlampiy has found one more cool application to process photos. However the application has certain limitations. Each photo *i* has a contrast *v**i*. In order for the processing to be truly of high quality, the application must receive at least *k* photos with contrasts which differ as little as possible. Evlampiy already knows the contrast *v**i* for each of his *n* photos. Now he wants to split the photos into groups, so that each group contains at least *k* photos. As a result, each photo must belong to exactly one group. He considers a processing time of the *j*-th group to be the difference between the maximum and minimum values of *v**i* in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups. Split *n* photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible.
```python # n , k = 5,2 s1 = input() arr1 = s1.split(' ') n,k = int(arr1[0]),int(arr1[1]) s2 = input() # s = '50 110 130 40 120' array = s2.split(' ') for i in range(n): array[i] = int(array[i]) array.sort(reverse=True) left = 0 right = array[0] - array[-1] def check(x)->bool: l = 0 r = k - 1 if r == n-1: return array[0]-array[-1]<=x while l < n and r<n-1: while r+1<n and n-1-(r+1)>=k and array[l] - array[r+1]<=x: r+=1 if r==n-1 or n-(r+1)<k: # print('dd',r) return array[l]-array[-1]<=x if array[l]-array[r]>x: # print('ee') return False l = r+1 r = l+k-1 # print(l,r) # print('en ',l,r) return True while left<right: mid = left+(right-left-1)//2 if check(mid): right = mid else: left = mid+1 print(left) ```
MatrixStudio/Codeforces-Python-Submissions
A restaurant received *n* orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the *i*-th order is characterized by two time values — the start time *l**i* and the finish time *r**i* (*l**i*<=≤<=*r**i*). Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept? No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.
```python from collections import defaultdict n=int(input()) x=[] z=defaultdict(list) for j in range(n): a,b= map(int,input().split()) x.append([a,b]) z[b].append(a) x.sort(key = lambda xx: xx[1]) dp = [0 for i in range(n+1)] dp[1] = len(z[1]) for i in range(2,n+1): for j in z[i-1]: dp[i]=max(dp[j]+1,dp[i]) print(max(dp)+1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array consisting of *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to *n* defining the order elements of the array are destroyed. After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
```python n = int(input()) a = list(map(int, input().split())) p = list(map(int, input().split())) valid = [False for i in range(n)] parent = [0] * n size = [0] * n stat = [0] * n def find(x): while parent[x] != x: x = parent[x] return x def union(a, b): x = find(a) y = find(b) if x == y: return elif size[x] < size[y]: parent[x] = y size[y] += size[x] stat[y] += stat[x] else: parent[y] = x size[x] += size[y] stat[x] += stat[y] ans = [0] for i in range(n - 1, 0, -1): k = p[i] - 1 valid[k] = True parent[k] = k stat[k] = a[k] if k > 0 and valid[k - 1]: union(k, k - 1) if k < n - 1 and valid[k + 1]: union(k, k + 1) t = stat[find(k)] m = max(ans[-1], t) ans.append(m) while len(ans) > 0: print(ans.pop()) ```
MatrixStudio/Codeforces-Python-Submissions
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each digit. One day when Malek wanted to go from floor 88 to floor 0 using the elevator he noticed that the counter shows number 89 instead of 88. Then when the elevator started moving the number on the counter changed to 87. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem. Suppose the digital counter is showing number *n*. Malek calls an integer *x* (0<=≤<=*x*<=≤<=99) good if it's possible that the digital counter was supposed to show *x* but because of some(possibly none) broken sticks it's showing *n* instead. Malek wants to know number of good integers for a specific *n*. So you must write a program that calculates this number. Please note that the counter always shows two digits.
```python l = [2, 7, 2, 3, 3, 4, 2, 5, 1, 2] s = input() k = 1 for i in s: k *= l[int(i)] print(k) ```
MatrixStudio/Codeforces-Python-Submissions
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number *n* to Bob and said: —Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes. —No problem! — said Bob and immediately gave her an answer. Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
```python a=str(input()) b=str(input()) d={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0} for i in range(len(a)): d[int(a[i])]+=1 #print(d) ans="" keep=0 for i in range(1,10): if d[i]>0 : ans+=str(i) keep=i d[i]-=1 break #print(ans) for i in range(1,len(a)): for j in range(10): if(d[j]>0): ans+=str(j) d[j]-=1 break if(ans==b): print("OK") else: print("WRONG_ANSWER") ```
MatrixStudio/Codeforces-Python-Submissions
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size *b*1 and *b*2, then one of the following is correct: *a*1 is equivalent to *b*1, and *a*2 is equivalent to *b*2 1. *a*1 is equivalent to *b*2, and *a*2 is equivalent to *b*1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent. Gerald has already completed this home task. Now it's your turn!
```python sa = input().strip() sb = input().strip() def check(p1, p2, ln): global sa, sb for i, j in zip(range(p1, p1 + ln), range(p2, p2 + ln)): if sa[i] != sb[j]: break else: return True if ln % 2: return False nln = ln // 2 return (check(p1, p2, nln) and check(p1 + nln, p2 + nln, nln)) or (check(p1, p2 + nln, nln) and check(p1 + nln, p2, nln)) print("YES" if check(0, 0, len(sa)) else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that. Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them. The English alphabet vowels are: A, E, I, O, U, Y The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
```python s=input() i=-1 while(not((s[i]>='a' and s[i]<='z') or (s[i]>='A' and s[i]<='Z'))): i-=1 if(s[i]=='A' or s[i]=='E' or s[i]=='I' or s[i]=='O' or s[i]=='Y' or s[i]=='a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='y'): 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 = list(map(int,input().split(" "))) arr=list(map(int,input().split(" "))) sumi=0 for i in range(k): sumi=sumi+arr[i] mini = sumi index=0 l=0 r=k-1 while(r<=n-2): r=r+1 sumi=sumi+arr[r] sumi=sumi-arr[l] l=l+1 if(sumi<mini): mini=sumi index=j print(j) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: - if he enters 00 two numbers will show up: 100000000 and 100123456, - if he enters 123 two numbers will show up 123456789 and 100123456, - if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
```python n=int(input()) s=[] for i in range(0,n): s.append(str(input())) for i in range(0,n): b=0; for j in range(1,10): if(b==1): break; for t in range(9-j,-1,-1): flag=1; for m in range(0,n): if(m==i): continue; for k in range(0,10-j): if(s[i][t:t+j]==s[m][k:k+j]): flag = 0; if(flag): print(s[i][t:t+j]); b=1; break; ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has an array *a* consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position). Inserting an element in the same position he was erased from is also considered moving. Can Vasya divide the array after choosing the right element to move and its new position?
```python n=int(input()) ls=list(map(int,input().split())) s=sum(ls)/2 if sum(ls)%2!=0: print('No') exit() lz=ls.copy() for i in range(1,n): lz[i]+=lz[i-1] if lz[i]==s or ((lz[i]-s) in ls[:i+1]): print('Yes') break else: lc=ls.copy() lc.reverse() for i in range(1,n): lc[i]+=lc[i-1] if lc[i]==s or ((lc[i]-s) in ls[i+1:]): print('Yes') break else: print('No') ```
MatrixStudio/Codeforces-Python-Submissions
You've got an array *a*, consisting of *n* integers. The array elements are indexed from 1 to *n*. Let's determine a two step operation like that: 1. First we build by the array *a* an array *s* of partial sums, consisting of *n* elements. Element number *i* (1<=≤<=*i*<=≤<=*n*) of array *s* equals . The operation *x* *mod* *y* means that we take the remainder of the division of number *x* by number *y*. 1. Then we write the contents of the array *s* to the array *a*. Element number *i* (1<=≤<=*i*<=≤<=*n*) of the array *s* becomes the *i*-th element of the array *a* (*a**i*<==<=*s**i*). You task is to find array *a* after exactly *k* described operations are applied.
```python mod=1000000007 n,k=map(int,input().split()) arr=list(map(int,input().split())) arrx=[] arr1=[] for i in range(n): arr1.append(arr[i]) sum1=0 if(k==0): print(*arr) else: j=1 sumx=0 for i in range(n): sumx=(j*(j+1))//2 arrx.append(sumx) j+=1 #print(*arrx) for i in range(n): sum1=0 val=k for j in range(i): sum1+=((val)*(val+1)*arr1[j])//2 val=max(val-1,1) #print(sum1,i) arr[i]=((arr[i]%mod)+(sum1%mod))%mod print(*arr) ```
MatrixStudio/Codeforces-Python-Submissions
Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits. Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.
```python a = int(input()) b = int(input()) c = int(input()) s = min(a//1, b//2, c//4) ans = s*7 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password". Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address. Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits. Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
```python if __name__ == "__main__": passw = input() line0 =input() line1 =input() line2 =input() line3 =input() line4 =input() line5 =input() line6 =input() line7 =input() line8 =input() line9 =input() #passw = list(passw) passws = [str(passw[0:10]), str(passw[10:20]), str(passw[20:30]),str(passw[30:40]), str(passw[40:50]), str(passw[50:60]), str(passw[60:70]), str(passw[70:80])] print(passws) line = "" for i in passws: if(i == line0): line = line + "0" elif(i == line1): line = line + "1" elif(i == line2): line = line + "2" elif(i == line3): line = line + "3" elif(i == line4): line = line + "4" elif(i == line5): line = line + "5" elif(i == line6): line = line + "6" elif(i == line7): line = line + "7" elif(i == line8): line = line + "8" elif(i == line9): line = line + "9" print(int(line)) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.
```python a=input() b=input().split() c=input().split() d=[] def p(i,x): for j in b: if int(j)<=i: x+=1 return x print(*list(map(lambda i:p(int(i),0),c))) ```
MatrixStudio/Codeforces-Python-Submissions
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in.
```python def main(): path = input() coordinate = [[0 for i in range(2)] for j in range(len(path)+1)] coordinate[0] = [0,0] left = 0 right = 0 up = 0 down = 0 for direction in path: if direction == 'U': up += 1 elif direction == 'R': right += 1 elif direction == 'D': down += 1 elif direction == 'L': left += 1 if (left = 1 and right = 1 and up = 1 and down = 0) or (left = 1 and right = 1 and up = 0 and down = 1) or (left = 1 and right = 0 and up = 1 and down = 1) or (left = 0 and right = 1 and up = 1 and down = 1): print('BUG') return for i in range(0,len(path)): if i == 0: if path[i] == 'U': coordinate[i + 1][0] = 0 coordinate[i + 1][1] = 1 elif path[i] == 'R': coordinate[i + 1][0] = 1 coordinate[i + 1][1] = 0 elif path[i] == 'D': coordinate[i + 1][0] = 0 coordinate[i + 1][1] = -1 elif path[i] == 'L': coordinate[i + 1][0] = -1 coordinate[i + 1][1] = 0 else: if path[i] == 'U': coordinate[i + 1][0] = coordinate[i][0] coordinate[i + 1][1] += 1 + coordinate[i][1] elif path[i] == 'R': coordinate[i + 1][1] = coordinate[i][1] coordinate[i + 1][0] += 1 + coordinate[i][0] elif path[i] == 'D': coordinate[i + 1][0] = coordinate[i][0] coordinate[i + 1][1] += -1 + coordinate[i][1] elif path[i] == 'L': coordinate[i + 1][1] = coordinate[i][1] coordinate[i + 1][0] += -1 + coordinate[i][0] coordinateSet = list(set(map(tuple,coordinate))) if len(coordinate) == len(coordinateSet): print('OK') else: print('BUG') main() ```
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 n,m,a,b=map(int,input().split()) k=n%m print(min(k*b,(m-k)*a)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.
```python def rec(m, arr): if(m in arr): return 1 if(len(arr) == 2): return 1 + max(rec(m-arr[0], arr), rec(m-arr[1], arr)) return 1 + max(rec(m-arr[0], arr), rec(m-arr[1], arr), rec(m-arr[-1], arr)) nums = list(map(int, input().split())) n = nums[0] nums = nums[1:] nums.sort() if(n%nums[0]): print(rec(n, nums[:-1])) if(nums[-1] == nums[0] + nums[1]) else print(rec(n, nums)) else: print(n//nums[0]) ```
MatrixStudio/Codeforces-Python-Submissions
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution. This contest offers *n* problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.
```python Number = int(input()) counter = 0; for i in range(Number): Lists = str(input()) if Lists == "1 1 1" or Lists == "0 1 1" or Lists == "1 1 0": counter = counter + 1 print(counter) ```
MatrixStudio/Codeforces-Python-Submissions
The polar bears are going fishing. They plan to sail from (*s**x*,<=*s**y*) to (*e**x*,<=*e**y*). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (*x*,<=*y*). - If the wind blows to the east, the boat will move to (*x*<=+<=1,<=*y*). - If the wind blows to the south, the boat will move to (*x*,<=*y*<=-<=1). - If the wind blows to the west, the boat will move to (*x*<=-<=1,<=*y*). - If the wind blows to the north, the boat will move to (*x*,<=*y*<=+<=1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (*x*,<=*y*). Given the wind direction for *t* seconds, what is the earliest time they sail to (*e**x*,<=*e**y*)?
```python from collections import Counter def main(): dirs = { 'S': -1, 'N': 1, 'W': -1, 'E': 1, } t, sx, sy, ex, ey = map(int, input().split()) for i, dir in enumerate(input(), 1): if dir in 'SN': if abs(ey - sy - dirs[dir])< abs(ey - sy): sy += dirs[dir] elif dir in 'EW': if abs(ex - sx - dirs[dir]) < abs(ex - sx): sx += dirs[dir] if sx == ex and sy == ey: print(i) break else: print(-1) main() ```
MatrixStudio/Codeforces-Python-Submissions
Find the number of *k*-divisible numbers on the segment [*a*,<=*b*]. In other words you need to find the number of such integer values *x* that *a*<=≤<=*x*<=≤<=*b* and *x* is divisible by *k*.
```python s=[int(i) for i in input().split()] k=s[0] a=s[1] b=s[2] s.clear() if a<=0 and b>=0: a=-a print((a+b)//k+1) continue else: if a<=0 and b<=0: a=-a b=-b a,b=b,a ans=(b-a+1)//k print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: - Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
```python x = input() cnt=0 for i in range(1,x): s = input() if s=="Tetrahedron": cnt+=4 elif s=="Cube": cnt+=6 elif s=="Octahedron": cnt+=8 elif s=="Dodecahedron": cnt+=12 elif s=="Icosahedron": cnt+=20 print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of *n* letters. Oleg and Igor each have a set of *n* letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by *n* question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters *c* in his set and replace any of the question marks with *c*. Then, a copy of the letter *c* is removed from his set. The game ends when all the question marks has been replaced by some letter. For example, suppose Oleg has the set of letters {*i*,<=*o*,<=*i*} and Igor has the set of letters {*i*,<=*m*,<=*o*}. One possible game is as follows : Initially, the company name is ???. Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {*i*,<=*o*}. Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {*i*,<=*m*}. Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {*i*}. In the end, the company name is oio. Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally? A string *s*<==<=*s*1*s*2...*s**m* is called lexicographically smaller than a string *t*<==<=*t*1*t*2...*t**m* (where *s*<=≠<=*t*) if *s**i*<=&lt;<=*t**i* where *i* is the smallest index such that *s**i*<=≠<=*t**i*. (so *s**j*<==<=*t**j* for all *j*<=&lt;<=*i*)
```python A = [0 for _ in range(26)] B = [0 for _ in range(26)] ptr_a = 30 ptr_b = -1 s1 = input() length = len(s1) for c in s1: x = ord(c)-ord("a") A[x] += 1 if A[x] == 1 and x < ptr_a: ptr_a = x s2 = input() for c in s2: x = ord(c) - ord("a") B[x] += 1 if B[x] == 1 and x > ptr_b: ptr_b = x name = [] p = 0 while len(name) < length: if p == 0: name.append(chr(ord("a")+ptr_a)) A[ptr_a] -= 1 if A[ptr_a] == 0: while True: ptr_a += 1 if ptr_a == 26: break if A[ptr_a] > 0: break p = 1 else: name.append(chr(ord("a") + ptr_b)) B[ptr_b] -= 1 if B[ptr_b] == 0: while True: ptr_b -= 1 if ptr_b == -1: break if B[ptr_b] > 0: break p = 0 print("".join(name)) ```
MatrixStudio/Codeforces-Python-Submissions
A permutation of size *n* is an array of size *n* such that each integer from 1 to *n* occurs exactly once in this array. An inversion in a permutation *p* is a pair of indices (*i*,<=*j*) such that *i*<=&gt;<=*j* and *a**i*<=&lt;<=*a**j*. For example, a permutation [4,<=1,<=3,<=2] contains 4 inversions: (2,<=1), (3,<=1), (4,<=1), (4,<=3). You are given a permutation *a* of size *n* and *m* queries to it. Each query is represented by two indices *l* and *r* denoting that you have to reverse the segment [*l*,<=*r*] of the permutation. For example, if *a*<==<=[1,<=2,<=3,<=4] and a query *l*<==<=2, *r*<==<=4 is applied, then the resulting permutation is [1,<=4,<=3,<=2]. After each query you have to determine whether the number of inversions is odd or even.
```python n = int(input()) lst = [] for x in input().split(): lst.append(int(x)) m = int(input()) pair = [] for x in range(m): (l, r) = map(int, input().split()) pair.append((l, r)) k = 0 for x in range(0, len(lst) - 1): for y in range(x + 1, len(lst)): if lst[y] < lst[x]: k += 1 for (l, r) in pair: if (k - (r - l + 1) // 2) % 2 == 0: print("even") else: print("odd") k = k - (r - l + 1) // 2 ```
MatrixStudio/Codeforces-Python-Submissions
You are given an equation: Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
```python import sys, io, os from collections import Counter input = sys.stdin.readline # for strings # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # for non-strings def solve(): a, b, c = map(int, input().split()) if a == 0: if b == 0: if c == 0: print(-1) else: print(0) else: print(1) print(-c/b) else: delta = b**2 - 4*a*c if delta == 0: print(1) print(-b/(2*a)) elif delta<0: print(0) else: print(2) print((-b-delta**0.5)/(2*a)) print((-b+delta**0.5)/(2*a)) if __name__=="__main__": solve() ```
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!
```python a, b = map(int, input().split()) if a == b: print(a) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only two pockets. She can put at most *k* pebbles in each pocket at the same time. There are *n* different pebble types in the park, and there are *w**i* pebbles of the *i*-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day. Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
```python import math c=0 n,k=map(int,input().split()) arr=list(map(int,input().strip().split())) for i in arr:c+=math.ceil(i/k) print(math.ceil(c/2)) ```
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 s=input() r=input() print(s^r) ```
MatrixStudio/Codeforces-Python-Submissions
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's and Eeyore's house is *b* meters, between Owl's and Eeyore's house is *c* meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal *n* times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal *n* times, traveling minimum possible distance. Help him to find this distance.
```python n = int(input()) a = int(input()) b = int(input()) c = int(input()) no_move = False _min = min(a, b) if n == 1: no_move = True if no_move: print(0) else: if c >= _min: dist = (n-1)*_min else: dist = _min+(n-2)*c print(dist) ```
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 t = input() events = list(map(int , input().split())) police = 0 count = 0 for event in events: police += event if police < 0: count +=1 police = 0 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*. Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
```python n,k =input().split() n =int(n) k=int(k) a=input() x=a.split() c=0 for i in range(n): x[i]=int(x[i]) if x[i]>k: c+=2 else: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=&gt;<=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
```python n = int(input()) h = *map(int, input().split()), cost = 0 cost += h[1] e = h[1] i = 2 while i < n: if h[i] > e: cost += h[i] - e e += h[i] - e else: e += e - h[i] i += 1 print(cost) ```
MatrixStudio/Codeforces-Python-Submissions
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012"). The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date. A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it. Notice, that any year between 2013 and 2015 is not a leap year.
```python from statistics import mode import re lst = [] str = input() S = str while len(S): m = re.search(r'([0-2][0-9]|[3][01])[-]([0][13578]|[1][02])[-]([2][0][1][3-5])',S) if m: lst.append(m.group()) S = S[m.start() + 1:] else: break S = str while len(S): m = re.search(r'([0-2][0-9]|[3][0])[-]([0][469]|[1][1])[-]([2][0][1][3-5])',S) if m: lst.append(m.group()) S = S[m.start() + 1:] else: break S = str while len(S): m = re.search(r'([0-2][0-9])[-][0][2][-][2][0][1][3-5]',S) if m: lst.append(m.group()) S = S[m.start() + 1:] else: break print(mode(lst)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1<=×<=*n* square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.
```python n=int(input()) s=input() c=0 for i in range(n): if (i+1)%2==0 and s[i]=="1" or (i+1)%2==1 and s[i]=="0": c+=1 print(min(n-c,c)) ```
MatrixStudio/Codeforces-Python-Submissions
Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0.
```python n=int(input()) l=list(map(int,input().split())) s=0 ol=[] for i in l: if i%2==0: s=s+i else: ol.append(i) if len(ol)%2==0: s=s+sum(ol) else: s=s+sum(ol)-min(ol) print(s) ```
MatrixStudio/Codeforces-Python-Submissions
You have a positive integer *m* and a non-negative integer *s*. Your task is to find the smallest and the largest of the numbers that have length *m* and sum of digits *s*. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
```python m,s=[int(i) for i in input().split()] def convert(lis): max_val=0 min_val=0 s='' for i in lis: s=s+str(i) max_val=int(s) lis.reverse() s='' for i in lis: s=s+str(i) min_val=int(s) return (min_val,max_val) if s<1 or s>m*9:print(-1,-1) else: lis=[] q=s//m for i in range(m-1): lis.append(s-q) s=s-q lis.append(q) p=lis.count(0) if p>0: lis.sort() for i in range(m): if lis[i]!=0: k=i for i in range(m): if lis[i]==0: lis[i]=1 elif i==k and a[k]-p>=0: lis[k]=lis[k]-p elif i==k and lis[k]-p<0: p=p-lis[k] lis[k]=0 k=k+1 else: lis.sort() lis.reverse() for i in range(m-1): if lis[i]==9: continue elif lis[i]!=9 and 9-lis[i]<lis[i+1]: lis[i+1]=lis[i+1]+lis[i]-9 lis[i]=9 elif lis[i]!=9 and 9-lis[i]>=lis[i+1] and i==m-2: lis[i]=lis[i]+lis[i+1]-1 lis[i+1]=1 elif lis[i]!=9 and 9-lis[i]>=lis[i+1] and i!=m-2: lis[i]=lis[i]+lis[i+1] lis[i+1]=0 print(convert(lis)) ```
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 x=input("") y=x.lower() z=x.upper() y1=0 x1=0 for i in x: if i in y: y1+=1 else: x1+=1 if y1>x1: print(y) else: print(z) ```
MatrixStudio/Codeforces-Python-Submissions
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.
```python def qpow(x,y): z=1 while (y): if (y&1): z=z*x x=x*x y>>=1 return z x,y=map(int,input().strip().split()) a=x**y b=y**x if (a==b): print('=') elif (a>b): print('>') else: print('<') ```
MatrixStudio/Codeforces-Python-Submissions
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has *m* faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the *m*-th face contains *m* dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice *n* times.
```python def miis(): return map(int, input().split()) m, n = miis() ans = 0 for i in range(1, m+1): ans += i*((i/m)**n-((i-1)/m)**n) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells *n*<=×<=*m* in size (containing *n* rows, *m* columns). Petya marked two different cells of the rectangle and now he is solving the following task: Let's define a simple path between those two cells as a sequence of distinct cells *a*1,<=*a*2,<=...,<=*a**k*, where *a*1 and *a**k* are the two marked cells. Besides, *a**i* and *a**i*<=+<=1 are side-neighboring cells of the path (1<=≤<=*i*<=&lt;<=*k*). Let's denote the path length as number *k* (the sequence length). Petya's task is to find the longest simple path's length and to print the path. Help him.
```python m,n=map(int,input().split()) a1,b1=map(int,input().split()) a2,b2=map(int,input().split()) print((m*n)-1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros. Determine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible. An integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$.
```python q = int(input()) pot = [] b = 1 while (42): a = b**2 if(a <= q): pot.append((a)) b += 1 else: break pot.sort(reverse = True) b = 0 aux = -1 res = "" q = list(str(q)) while b < len(pot): pot_aux = list(str(pot[b])) flag = 0 aux = -1 for i in range(len(pot_aux)): if pot_aux[i] in q and q.index(pot_aux[i]) > aux: aux = q.index(pot_aux[i]) else: flag = 1 break if flag == 0: res = str(pot[b]) break else: b += 1 if res == "": print(-1) else: print(len(q)-len(res)) ```
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 m, n = map(int, input().split()) area = m*n count = area//2 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A colored stripe is represented by a horizontal row of *n* square cells, each cell is pained one of *k* colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to *k* to repaint the cells.
```python print("_RANDOM_GUESS_1689366534.3880188")# 1689366534.388033 ```
MatrixStudio/Codeforces-Python-Submissions
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert *a* grams of sand into *b* grams of lead, the second one allows you to convert *c* grams of lead into *d* grams of gold and third one allows you to convert *e* grams of gold into *f* grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable... Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.
```python # LUOGU_RID: 112089745 a, b, c, d, e, f = map(int, input().split()); if a * c * e < b * d * f or a == 0 and b * d > 0 or c == 0 and d > 0: print("Ron"); else: print("Hermione"); ```
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 def comb(n, k): if(n >= k): return math.comb(n, 2) else: return 0 def take_min(n, t): l = int(n/t) + 1 dif = t*l - n friends = (t-dif)*comb(l, 2) + (dif)*comb(l-1, 2) return int(friends) def take_max(n, t): return int(comb(n-(t-1), 2)) n, t = list(map(int, input().split())) print(take_min(n, t), take_max(n, t)) ```
MatrixStudio/Codeforces-Python-Submissions
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true: - Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager. Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*. What is the minimum number of groups that must be formed?
```python n=int(input()) l=[int(input()) for i in range(n)] g=0 for i in range(n): cnt=0 while i>=0: i=l[i]-1 cnt+=1 g=max(g,cnt) print(g) ```
MatrixStudio/Codeforces-Python-Submissions
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the *expose* procedure. Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?) Given integers *l*, *r* and *k*, you need to print all powers of number *k* within range from *l* to *r* inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
```python import math import cmath import string import sys import bisect import ctypes from queue import Queue,LifoQueue,PriorityQueue from itertools import permutations,combinations from collections import deque,Counter l,r,k=list(map(int,input().split())) i=0 a=[] while 1: temp=pow(k,i) i+=1 if temp<=r: a.append(temp) else: break b=[] for i in a: if i<=r and i>=l: b.append(i) if len(b)==0: print(-1) for i in b: print(i,end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams. After practice competition, participant number *i* got a score of *a**i*. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.
```python def solution(peeps): s = sum(peeps) for i in range(len(peeps)): for j in range(i + 1, len(peeps)): for k in range(j + 1, len(peeps)): total = i + j + k if total == s - total: return "YES" return "NO" peeps = list(map(int, input().split())) print(solution(peeps)) ```
MatrixStudio/Codeforces-Python-Submissions
Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on. Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
```python ons = [[1,1,1], [1,1,1], [1,1,1]] for i in range(3): rr = map(int, input().split()) for j, togs in enumerate(rr): for _ in range(togs): for ii in range(i-(i>0), min(i+2, 3)): for jj in range(j-(j>0), min(j+2,3)): ons[ii][jj] ^= 1 for g in ons: for h in g: print(h, end="") print() ```
MatrixStudio/Codeforces-Python-Submissions
Jzzhu is the president of country A. There are *n* cities numbered from 1 to *n* in his country. City 1 is the capital of A. Also there are *m* roads connecting the cities. One can go from city *u**i* to *v**i* (and vise versa) using the *i*-th road, the length of this road is *x**i*. Finally, there are *k* train routes in the country. One can use the *i*-th train route to go from capital of the country to city *s**i* (and vise versa), the length of this route is *y**i*. Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
```python # ﷽ from collections import defaultdict from heapq import heappop, heappush import sys input = lambda: sys.stdin.readline().strip() def inlst():return [int(i) for i in input().split()] class Graph: def __init__(self,n): self.graph=defaultdict(list) self.graph2=set() self.n=n self.train=[0]*n self.ans=0 def dijkstra(self, start=0): """ Uses Dijkstra's algortihm to find the shortest path from node start to all other nodes in a directed weighted graph. """ n = self.n dist, parents = [float("inf")] * n, [-1] * n dist[start] = 0 queue = [(0, start)] while queue: path_len, v = heappop(queue) if path_len == dist[v]: for w, edge_len in self.graph[v]: if edge_len + path_len < dist[w]: dist[w], parents[w] = edge_len + path_len, v heappush(queue, (edge_len + path_len, w)) if edge_len + path_len == dist[w] and v!=start: dist[w], parents[w] = edge_len + path_len, v heappush(queue, (edge_len + path_len, w)) return dist, parents def ingraph(self,num_edges, num_edqe2): for _ in range(num_edges): a,b,w=[int(i) for i in input().split()] self.graph[a].append((b,w)) self.graph[b].append((a,w)) if a==1: self.graph2.add((b,w)) if b==1: self.graph2.add((a,w)) for _ in range(num_edqe2): a,b,w=[1]+[int(i) for i in input().split()] self.graph[a].append((b,w)) self.graph[b].append((a,w)) self.train[b]+=1 def solve(): n,m,k=inlst() graph=Graph(n+1) graph.ingraph(m,k) dist, parents=graph.dijkstra(1) tot=0 # print(dist) # print(parents) for i ,j in enumerate(parents): if j==1: if (i,dist[i]) in graph.graph2: tot+=1*graph.train[i] else: tot+=graph.train[i]-1 elif j!=-1:tot+=1 # print(i,j,tot) print(tot) # print(graph.graph) if __name__ == "__main__": # for i in range(int(input())): solve() ```
MatrixStudio/Codeforces-Python-Submissions
The "BerCorp" company has got *n* employees. These employees can use *m* approved official languages for the formal correspondence. The languages are numbered with integers from 1 to *m*. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar. Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
```python def find_min_cost_to_connect_employees(n, m, employees): graph = [[] for _ in range(n)] for i in range(n): _, *languages = employees[i] for lang in languages: graph[i].append(lang) visited = [False] * n total_cost = 0 def dfs(node): visited[node] = True return 1 for i in range(n): if not visited[i]: component_size = dfs(i) total_cost += component_size - 1 return total_cost n, m = map(int, input().split()) employees = [list(map(int, input().split())) for _ in range(n)] min_cost = find_min_cost_to_connect_employees(n, m, employees) print(min_cost) ```
MatrixStudio/Codeforces-Python-Submissions
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
```python d = {} for i in range(int(input())): s = list(map(str, input().split())) if s[0] not in d: d[s[0]] = [s[1]] else: if (s[1] not in d[s[0]]): d[s[0]].append(s[1]) ans = 0 # print(d) for key in d: for value in d[key]: ans += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created. We assume that Bajtek can only heap up snow drifts at integer coordinates.
```python n = int(input()) snowpatch = [input().split() for i in range(n)] newnode = 0 visited = [ False for i in range(n)] for i in range(n): if visited[i] == True: continue visited[i] = True newnode += 1 stack = [i] while stack: x = stack[-1] stack.pop() for j in range(n): if visited[j] == True: continue if snowpatch[j][0] == snowpatch[x][0] or snowpatch[j][1] == snowpatch[x][1]: stack.append(j) visited[x] = True print(newnode - 1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python s = input() hello = "hello" counter = 0 j = 0 for i in range(len(hello)): while j < len(s): if hello[i] == s[j]: counter += 1 j += 1 break j += 1 if counter == 5: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data points — for each 1<=≤<=*i*<=&lt;<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≤<=1. A range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≤<=*i*<=≤<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≤<=1. Find the length of the longest almost constant range.
```python n = int (input()) a = list(map(int,input().split())) check = 0 i = 0 ans = 2 mn = min(a[0],a[1]) mx = max(a[0],a[1]) check =0 while(i<n-1): l = 1 if check: break for j in range(i+1,n): next = a[j] # print('I:',i,'J',j) # print('mx', mx, 'mn', mn, 'next', next) if next<mn and mn!=mx: # print('1111111111111111111111111111111') mx = mn mn = next i+=1 if l>ans: ans = l break elif next > mx and mn!=mx: # print('22222222222222222222222222222222') mn= mx mx = next i += 1 if l > ans: ans = l break else: # print('33333333333333333333333333333333') l+=1 mn = min(mn,mx,next) mx = max(mn,mx,next) if j == n-1: # print('4444444444444444444444444444444444') if l>ans: ans = l check = 1 break # print('Cur L:',l) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure. Bottle with potion has two values *x* and *y* written on it. These values define four moves which can be performed using the potion: - - - - Map shows that the position of Captain Bill the Hummingbird is (*x*1,<=*y*1) and the position of the treasure is (*x*2,<=*y*2). You task is to tell Captain Bill the Hummingbird whether he should accept this challenge or decline. If it is possible for Captain to reach the treasure using the potion then output "YES", otherwise "NO" (without quotes). The potion can be used infinite amount of times.
```python positions = [int(a) for a in input().split()] potion = [int(a) for a in input().split()] x_dist = abs(positions[2] - positions[0]) y_dist = abs(positions[3] - positions[1]) if (x_dist%potion[0]==0 and y_dist%potion[1]==0): x_div = x_dist//potion[0] y_div = y_dist//potion[1] if (abs(x_div - y_div)%2 == 0): print('YES') else: print('NO') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are *n* days, at the *i*-th day, Arya finds *a**i* candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later. Your task is to find the minimum number of days Arya needs to give Bran *k* candies before the end of the *n*-th day. Formally, you need to output the minimum day index to the end of which *k* candies will be given out (the days are indexed from 1 to *n*). Print -1 if she can't give him *k* candies during *n* given days.
```python n, k = map(int, input().split()) a = list(map(int, input().split())) got = 0 for i in range(n): got += a[i] k -= min(got, 8) got -= min(got, 8) if k <= 0: print(i+1) break if k > 0: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there. If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift. Now Petya wants to know for each friend *i* the number of a friend who has given him a gift.
```python n=int(input()) a=[int(x) for x in input().split()] d=[0]*n for i in range(n): d[a[i]-1]=str(i+1) m=" ".join(d) print(m) ```
MatrixStudio/Codeforces-Python-Submissions
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!). Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
```python s=input() l=list(s) n=len(s) c=0 for i in range(n): if l[i]=='A': a=0 b=0 for j in range(i): if l[j]=='Q': a+=1 for j in range(i,n): if l[j]=='Q': b+=1 c+=a*b print(c) ```
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 = int(input) text = input() new_text1 = text.replace('RU', 'D') new_text2 = text.replace('UR', 'D') x = len(new_text2) print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and *L*, and they move towards each other with speed *v*1 and *v*2, respectively. Luke has width *d* and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.
```python d,L,v1,v2 = map(int,input().split()) t = (L-d)/(v1+v2) print(t) ```
MatrixStudio/Codeforces-Python-Submissions
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail. You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.
```python k=int(input()) m=[int(c) for c in input() if c!='.' for row in range(4)] print("YES" if all(m.count(t)<=2*k for t in set(m)) else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) s = list(input().rstrip().decode().split()) u = set() for s0 in s: v = list(set(s0)) v.sort() u.add(tuple(v)) ans = len(u) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas: Here, "mod" means the operation of taking the residue after dividing. The expression means applying the bitwise *xor* (excluding "OR") operation to integers *x* and *y*. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor". People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence *p*, calculate the value of *Q*.
```python n=int(input()) a=list(map(int,input().split())) dp=[0 for i in range(n+1)] for i in range(1,n+1): dp[i]=dp[i-1]^i ans=0 for i in a: ans=ans^i for i in range(2,n+1): x=n//i if x&1: ans=ans^dp[i-1] rem=n%i ans=ans^dp[rem] print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded. For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct. For given *n* find out to which integer will Vasya round it.
```python n=int(input()) if n>=1 and n<=1000000000: a=n%10 if a <=5: print(n-a) else: print(n+(10-a)) ```
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()) number=[int(x) for x in input().split()] odd=0 even=0 for i in range(n): if number[i]%2==0: evennum=number[i] even+=1 else: oddnum=number[i] odd+=1 if odd>even: print((number.index(evennum))+1) else: print((number.index(oddnum))+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 a=input() b=input() c=input() d=input() e=input() f=input() g=input() h=input() s="WBWBWBWB" s1="BWBWBWBW" l=[a,b,c,d,e,f,g,h] ok=0 if l.count(s)==4 and l.count(s1)==4: ok+=1 else: ok=0 # else: # ok=0 if ok==1: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic. Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.
```python n,m = list(map(int,input().split())) a = list(map(int,input().split())) a.sort() l,p,k = a[n-1],0,0 for i in range(n-1): if p<l: if a[i]>p: k+=(a[i]-1) p+=1 else: k+=(a[i]-1) else: k+=(a[i]-1) if p>=l: print(k+(a[n-1]-1)) else: print(k+(a[n-1]-(l-p))) ```
MatrixStudio/Codeforces-Python-Submissions
A continued fraction of height *n* is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height *n*. Check if they are equal.
```python p, q = [int(x) for x in input().split()] n = int(input()) a = [int(x) for x in input().split()] for x in a: p -= q*x p,q = q,p if(q==0): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Dreamoon wants to climb up a stair of *n* steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer *m*. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
```python n,m=map(int,input().split()) if n<m: print(-1) else: print((((n+1)//2-1)//m+1)*m) ```
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 if __name__ == "__main__": s = input() count_up = 0 count_low = 0 for ch in s: if ch.isupper(): count_up += 1 else: count_low += 1 if count_up > count_low: for ch in s: print(ch.upper(), end="") else: for ch in s: print(ch.lower(), end="") ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them. Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got. Can you help him?
```python x, y = map(int, input().split()) min = min(x, y) max = max(x, y) different_days = min same_days = (max - min) // 2 print(different_days, same_days) ```
MatrixStudio/Codeforces-Python-Submissions
On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with *n* rows and *m* columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column. To win the level, after all the moves, the number in the cell at the *i*-th row and *j*-th column should be equal to *g**i*,<=*j*. Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!
```python import math as mt import sys,string input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,m=M() l=[] x=[] req=[] req2=[] ans=[] ans2=[] c=0 f=0 c2=0 for i in range(n): l.append(L()) k=min(l[-1]) if(k>0): ans.append(("r",i+1,k)) req.append([k]*m) c+=k else: req.append([0]*m) for i in range(n): for j in range(m): if(l[i][j]!=req[i][j]): e=l[i][j]-req[i][j] c+=e for k in range(n): req[k][j]+=e ans.append(("c",j+1,e)) #print(e,"E") if(req==l): f=1 for i in range(n): req2.append([0]*m) for i in range(m): k=10**10 for j in range(n): k=min(k,l[j][i]) if(k>0): for p in range(n): req2[p][i]=k c2+=k ans2.append(("c",i+1,k)) for i in range(n): for j in range(m): if(l[i][j]!=req2[i][j]): e=l[i][j]-req2[i][j] c2+=e for k in range(m): req2[i][k]+=e ans2.append(("r",i+1,e)) if(req2==l): f+=2 if(f==3): print(min(c,c2)) if(c<c2): for i in range(len(ans)): if(ans[i][0]=="c"): for k in range(ans[i][2]): print("col",ans[i][1]) else: for k in range(ans[i][2]): print("row",ans[i][1]) else: for i in range(len(ans2)): if(ans2[i][0]=="c"): for k in range(ans2[i][2]): print("col",ans2[i][1]) else: for k in range(ans2[i][2]): print("row",ans2[i][1]) elif(f==1): print(c) for i in range(len(ans)): if(ans[i][0]=="c"): for k in range(ans[i][2]): print("col",ans[i][1]) else: for k in range(ans[i][2]): print("row",ans[i][1]) elif(f==2): print(c2) for i in range(len(ans2)): if(ans2[i][0]=="c"): for k in range(ans2[i][2]): print("col",ans2[i][1]) else: for k in range(ans2[i][2]): print("row",ans2[i][1]) else: print(-1) ```
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 def sum_digits(num): tot = 0 while num: tot += (num % 10) num //= 10 return tot if __name__ == "__main__": n = int(input()) ans = 0 while n >= 10: ans += 1 n = sum_digits(n) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer *n*. Help Anton to determine the exchange rate of currency you all know for tomorrow!
```python n=[i for i in input()] flag=True bravo=-1 for i in range(len(n)): if int(n[i])%2==0 and int(n[i])<int(n[-1]): count_=i flag=False break elif int(n[i])%2==0: bravo=i if flag: if bravo==-1: print(-1) else: tre=n[bravo] n[bravo]=n[-1] n[-1]=tre print("".join(n)) else: tre=n[count_] n[count_]=n[-1] n[-1]=tre print("".join(n)) ```
MatrixStudio/Codeforces-Python-Submissions
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome. In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment. However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.
```python t=input() if int(t[:2])==23 and int(t[3:5])>32: print('00:00') elif(6<=int(t[:2])<=9): print('10:01') elif(16<=int(t[:2])<=19): print('20:02') elif(int(t[:2][::-1]) <= int(t[3:5])): print(t[:2]+':'+t[:2][::-1]) else: print(str(int(t[:2])+1)+':'+str(int(t[:2])[::-1])) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
```python s1 = input().lower() s2 = input().lower() f = 0 for i in range(len(s1)): if ord(s1[i]) > ord(s2[i]): f = 1 break elif ord(s1[i]) < ord(s2[i]): f = -1 break print(f) ```
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()) arr = [[]] for i in range(n): for j in range(n): arr[i][j] = int(input()) som = 0 for i in range(n): for j in range(n): som += arr[i][j] if som == 0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has *n* burles. One bottle of Ber-Cola costs *a* burles and one Bars bar costs *b* burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly *n* burles. In other words, you should find two non-negative integers *x* and *y* such that Vasya can buy *x* bottles of Ber-Cola and *y* Bars bars and *x*·*a*<=+<=*y*·*b*<==<=*n* or tell that it's impossible.
```python n = int(input()) a = int(input()) b = int(input()) def main(): total = n if total%a == 0: print("YES") print(total//a,0) return if total%b == 0: print("YES") print(0,total//b) return counter = 0 while total>0: if total%b == 0: print("YES") print(counter,total//b) return total -= a counter += 1 print("NO") return main() ```
MatrixStudio/Codeforces-Python-Submissions
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to *n* clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if *n*<==<=5, then after the third throw the child number 2 has the ball again. Overall, *n*<=-<=1 throws are made, and the game ends. The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
```python n = int(input()) id = 1 for i in range(n - 1): id += i + 1 id %= n if id == 0: print(n, end=' ') else: print(id, end=' ') ```
MatrixStudio/Codeforces-Python-Submissions
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are *n* friends, and *i*-th of them is standing at the point *x**i* meters and can move with any speed no greater than *v**i* meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the *n* friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.
```python n = int(input()) x = [int(i) for i in input().split()] v = [int(i) for i in input().split()] def search(n,x,v,t): lmax = max([x[i]-t*v[i] for i in range(n)]) rmin = min([x[i]+t*v[i] for i in range(n)]) if lmax<=rmin: return True return False def binary(n,x,v): l,r = 0,10**9 while abs(r-l)>10**-6: mid = (l+r)/2 if search(n,x,v,mid): r = mid else: l = mid return l print(binary(n,x,v)) ```
MatrixStudio/Codeforces-Python-Submissions
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least *i* is found so that name*i* does not yet exist in the database.
```python def register_users(n, requests): registered_users = set() # Set to store registered user names responses = [] # List to store system responses for request in requests: if request not in registered_users: registered_users.add(request) responses.append("OK") else: i = 1 while f"{request}{i}" in registered_users: i += 1 new_username = f"{request}{i}" registered_users.add(new_username) responses.append(new_username) return responses n = int(input()) # Number of requests requests = [input() for _ in range(n)] # List of requests responses = register_users(n, requests) for response in responses: print(response) ```
MatrixStudio/Codeforces-Python-Submissions
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic. How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
```python num=[] count=0 for i in range(5): num.append(int(input())) if num[0]==1 or num[1]==1 or num[2]==1 or num[3]==1: print(num[4]) else: for i in range(1,num[4]+1): if i%num[0]==0 or i%num[1]==0 or i%num[2]==0 or i%num[3]==0: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has an array, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array *a**i*, *a**j* (*i*<=≠<=*j*); - he simultaneously increases number *a**i* by 1 and decreases number *a**j* by 1, that is, executes *a**i*<==<=*a**i*<=+<=1 and *a**j*<==<=*a**j*<=-<=1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
```python import collections n=int(input()) A=[int(x) for x in input().split()] while True: A.sort() B=A[:] flag=1 for i in range(n//2): while(A[n-i-1]-1>A[i]): A[n-i-1]-=1 A[i]+=1 flag=0 if flag: break D=collections.Counter(A) print(max(D.values())) ```
MatrixStudio/Codeforces-Python-Submissions
Tattah's youngest brother, Tuftuf, is new to programming. Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava. Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has *n* unsigned integer datatypes of sizes (in bits) *a*1,<=*a*2,<=... *a**n*. The *i*-th datatype have size *a**i* bits, so it can represent every integer between 0 and 2*a**i*<=-<=1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer *x*, such that *x* fits in some type *i* (in *a**i* bits) and *x*·*x* does not fit in some other type *j* (in *a**j* bits) where *a**i*<=&lt;<=*a**j*, then Tuftuf will stop using Gava. Your task is to determine Tuftuf's destiny.
```python n = int(input()) A = list(map(int, input().split())) A.sort() per = 0 per2 = True while per < n-1: if A[per] < A[per+1]: if A[per+1] < A[per] * 2: per2 = False print(A[per],A[per+1]) break else: per+=1 else: per+=1 if per2: print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times. Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise. Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
```python import sys t = int(sys.stdin.readline()) arr = list(map(int, sys.stdin.readline().split())) chest = biceps = back = 0 for i in range(len(arr)): if i % 3 == 0: chest += arr[i] elif i % 3 == 1: biceps += arr[i] else: back += arr[i] if chest > biceps and chest > back: print("chest") elif biceps > chest and biceps > back: print("biceps") else: print("back") ```
MatrixStudio/Codeforces-Python-Submissions
Mike has a string *s* consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.
```python def iter(s): rev = s[::-1] count = 0 length_string = len(s) for i in range(length_string): if(s[i]!=rev[i]): count+=1 if count==2: print("YES") else: print("NO") s = input() iter(s) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously). Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
```python a=(input()) b=lift(map(int,input().split())) c=0 d=e=b[0] for i in b: if d>i: d=i c+=1 if d<i: e=i c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of *n* vertices. Vertex 1 is the root of the tree. Alice starts at vertex 1 and Bob starts at vertex *x* (*x*<=≠<=1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one. The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it. You should write a program which will determine how many moves will the game last.
```python n, x = map(int, input().split()) mas = [[] * (1) for i in range(n + 2)] for i in range(n - 1): a, b = map(int, input().split()) mas[a].append(b) mas[b].append(a) queue = [] queue.append(1) dist = [100002] * (n + 1) dist[0] = 0 dist[1] = 0 visit = [-1] * (n + 1) visit[1] = 0 while len(queue) > 0: z = queue.pop(0) for i in range(len(mas[z])): if dist[mas[z][i]] > dist[z] + 1: dist[mas[z][i]] = dist[z] + 1 if visit[mas[z][i]] == -1: visit[mas[z][i]] = 0 queue.append(mas[z][i]) print((max(dist) - dist[x] + dist[x]) * 2) ```
MatrixStudio/Codeforces-Python-Submissions
Anton has the integer *x*. He is interested what positive integer, which doesn't exceed *x*, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.
```python import math n=int(input()) x=math.log10(n) v=int(x) if(v==x): print(n-1) else: num=n s=0 c=0 while(num>10): s=s+(num%10) c=c+1 num=int(num/10) k=num-1 if(num==10): s=s+1 else: s=s+num s1=c*9 + k if(s1>s): print(k,end="") while(c>0): print("9",end="") c=c-1 else: print (n) ```