source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak. There is a sequence *a* that consists of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Let's denote *f*(*l*,<=*r*,<=*x*) the number of indices *k* such that: *l*<=≤<=*k*<=≤<=*r* and *a**k*<==<=*x*. His task is to calculate the number of pairs of indicies *i*,<=*j* (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*) such that *f*(1,<=*i*,<=*a**i*)<=&gt;<=*f*(*j*,<=*n*,<=*a**j*). Help Pashmak with the test.
```python import sys input = lambda: sys.stdin.readline().rstrip() from collections import deque,defaultdict,Counter from itertools import permutations,combinations from bisect import * from heapq import * from math import ceil,gcd,lcm,floor,comb alph = 'abcdefghijklmnopqrstuvwxyz' #pow(x,mod-2,mod) class Fenwick_tree: def __init__(self, numbers): self.length = numbers self.numbers = [0] * numbers self.bits = [0] * (self.length + 1) self.build_tree() def update(self, idx, value): idx += 1 while idx <= self.length: self.bits[idx]+=value idx = idx + (idx&-idx) def sum_range(self,idx): result = 0 idx += 1 while idx > 0: result += self.bits[idx] idx = idx - (idx & -idx) return result def build_tree(self): for index in range(self.length): self.update(index, self.numbers[index]) N = int(input()) A = list(map(int,input().split())) fen_tree = Fenwick_tree(10**6+1) ans = 0 dic = defaultdict(int) l,r = [],[] for i in range(N-1,-1,-1): r.append(dic[A[i]]) dic[A[i]]+=1 r = r[::-1] dic = defaultdict(int) for i in range(N): l.append(dic[A[i]]) dic[A[i]]+=1 cnt = defaultdict(int) # print(l) # print(r) fen_tree.update(r[-1],1) cnt[r[-1]]+=1 for i in range(N-2,-1,-1): ans+=fen_tree.sum_range(l[i])-cnt[l[i]] fen_tree.update(r[i],1) cnt[r[i]]+=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
```python AmountOfNum = int(input()) Array = list(map(int,input().split()))[:AmountOfNum] New = set(Array) New1 = sorted(New) if(len(New1)>1): print(New1[1]) else: print("NO") ```
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%10<5: print (n//10*10) elif n%10==5: print (n//10*10 or n//10*10+10) else: print (n//10*10+10) ```
MatrixStudio/Codeforces-Python-Submissions
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time. You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
```python str = input() numA = 0 numB = 0 numC = 0 check = True for x in str: if(x == 'a'): numA+=1 elif(x == 'b'): numB+=1 elif(x == 'c'): numC+=1 if((x == 'a'and (numB != 0 or numC != 0)) or (x == 'b'and numC != 0 )): check = False break if (numA == numC or numB == numC) and check: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
```python def helper(n,m,a): a=sorted(a) ans=sum(a[:m]) print(-ans) n,m=list(map(int,input().split())) a=list(map(int,input().split())) helper(n,m,a) ```
MatrixStudio/Codeforces-Python-Submissions
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
```python t = input() print(t[0].capitalize()+t[1:]) ```
MatrixStudio/Codeforces-Python-Submissions
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users). As a reminder, a prefix of a string *s* is its substring which occurs at the beginning of *s*: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string *a* is alphabetically earlier than a string *b*, if *a* is a prefix of *b*, or *a* and *b* coincide up to some position, and then *a* has a letter that is alphabetically earlier than the corresponding letter in *b*: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
```python first_name, last_name = input().split() first_done = first_name.lower() last_done = last_name.lower() login = first_name[0] for i in range(1, len(first_name) - 1): if ord(first_done[i]) < ord(last_done[0]): login += first_name[i] else: break login += last_name[0] print(login) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club. For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX". Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
```python s=input() a=s.split("WUB") print(a) r="" for i in range(len(a)): if a[i]!="": if i==len(s)-1: r=r+a[i] else: r=r+a[i]+" " print(r) ```
MatrixStudio/Codeforces-Python-Submissions
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent such three displays with indices $i &lt; j &lt; k$ that the font size increases if you move along the road in a particular direction. Namely, the condition $s_i &lt; s_j &lt; s_k$ should be held. The rent cost is for the $i$-th display is $c_i$. Please determine the smallest cost Maria Stepanovna should pay.
```python import sys inf = float('inf') input = lambda: sys.stdin.readline().strip() I = lambda: input() II = lambda: int(input()) MII = lambda: map(int, input().split()) LI = lambda: list(input().split()) LII = lambda: list(map(int, input().split())) GMI = lambda: map(lambda x: int(x) - 1, input().split()) LGMI = lambda: list(map(lambda x: int(x) - 1, input().split())) MOD = 10**9+7 class BIT: def __init__(self, n): self.n = n self.tree = [inf]*n def update(self, i, v): while i < self.n: self.tree[i] = min(self.tree[i], v) i += i & -i def query(self, i): res = inf while i: res = min(res, self.tree[i]) i -= i & -i return res def solve2(): n = II() a, b = LII(), LII() ids = sorted(range(n), key=lambda i: (a[i], -i)) # f[i][j]: 前i个数中长为j+1的递增子序列的b之和的最小值,从f[i][j-1]转移 # 第二个维度优化掉,初始相当于f[i][0], 第一个循环后得到f[i][1]…… f = b[:] for _ in range(2): g = [inf] * n t = BIT(n+1) for i in ids: g[i] = t.query(i)+b[i] t.update(i+1, f[i]) f = g res = min(f) print(res if res < inf else -1) def solve1(): n = II() a = LII() b = LII() res = inf for j in range(n): left = inf for i in range(j): if a[i] < a[j]: left = min(left, b[i]) right = inf for k in range(j+1, n): if a[k] > a[j]: right = min(right, b[k]) res = min(res, b[j]+left+right) print(res if res < inf else -1) return solve2() ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
```python n, x = [int(i) for i in input().split()] count = 0 for i in range(n): a, d = list(input().split()) if a == "+": x += int(d) else: if int(d) > x: count += 1 else: x -= int(d) print(x, count) ```
MatrixStudio/Codeforces-Python-Submissions
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" — people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy.
```python n = int(input()) print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
```python s = input() print(s[0].upper() + s [1:]) ```
MatrixStudio/Codeforces-Python-Submissions
Sean is trying to save a large file to a USB flash drive. He has *n* USB flash drives with capacities equal to *a*1,<=*a*2,<=...,<=*a**n* megabytes. The file size is equal to *m* megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
```python n=int(input()) m=int(input()) l=[] for i in range(n): a=int(input()) l.append(a) l.sort(reverse=True) c=0 for i in range(n): c+=l[i] if(c>=m): print(i+1) break ```
MatrixStudio/Codeforces-Python-Submissions
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?
```python n = int(input()) bags = list(map(int, input().split())) ##check if sum is even or odd ##if even, find all even bags ##if odd, find all odd bags s = sum(bags) if s%2==0: for i in bags: if i%2==0: print(i) else: for i in bags: if i%2==1: print(i) ```
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 s1=list(input()) s2=list(input()) s1.sort() s2.sort() ans="" n=len(s1) for i in range(n): if i % 2 == 0: ans+=s1[0] del(s1[0]) else: ans+=s2[-1] del(s2[-1]) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1. Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers. Given this information, is it possible to restore the exact floor for flat *n*?
```python n, m = map(int, input().split()) list1 = [] ans = [] for i in range(m): list1.append(list(map(int, input().split()))) for i in range(1, 101): if len(ans) > 1: print(-1) break for j in range(len(list1)): if list1[j][0] // i + min(1, list1[j][0] % i)!= list1[j][1]: break else: ans.append(i) else: if len(ans) == 1: if n % ans[-1] > 0: print(n // ans[-1] + 1) else: print(n // ans[-1]) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game. Initially you have a sequence of *n* integers: 1,<=2,<=...,<=*n*. In a single step, you can pick two of them, let's denote them *a* and *b*, erase them from the sequence, and append to the sequence either *a*<=+<=*b*, or *a*<=-<=*b*, or *a*<=×<=*b*. After *n*<=-<=1 steps there is only one number left. Can you make this number equal to 24?
```python A = int(input()); ans = """YES 1 * 2 = 2 3 * 4 = 12""" if A >= 5: if A % 2: ans = """YES 2 + 1 = 3 5 - 3 = 2 3 * 2 = 6 4 * 6 = 24""" for a in range(int(A/2 - 5/2)+1): ans += '\n%d - %d = 1'%(2*a+5, 2*a+4) for a in range(int(A/2 - 5/2)+1): ans += "\n1 * 24 = 24" else: for a in range(int(A/2 - 6/2)+1): ans += "\n%d - %d = 1"%(2*a+6, 2*a+5) ans += "\n2 * 12 = 24" for a in range(int(A/2 - 6/2)+1): ans += "\n1 * 24 = 24" elif A <= 3: ans = 'NO' else: ans += '\n12 * 2 = 24' print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for *k* burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of *r* burles (1<=≤<=*r*<=≤<=9). What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of *r* burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.
```python x=input().split(" ") i=0; b=True while b: i+=1 if (int(x[0])*i) % 10 == 0 or ((int(x[0])*i - int(x[1])) % 10) == 0 : b=False print(i) ```
MatrixStudio/Codeforces-Python-Submissions
After the lessons *n* groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the *i*-th group consists of *s**i* friends (1<=≤<=*s**i*<=≤<=4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
```python def s(n): if n == 1 or n == 3: return 3 elif n == 2: return 2 elif n == 4: return 1 x = int(input()) arr = [int(i) for i in input().split()] arr.sort(key=s, reverse=True) c = 0 t = 1 for i in arr: if c + i > 4: c = 0 t += 1 c += i print(t) ```
MatrixStudio/Codeforces-Python-Submissions
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab. After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has *h*2 health points and an attack power of *a*2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle. Vova's character has *h*1 health points and an attack power of *a*1. Also he has a large supply of healing potions, each of which increases his current amount of health points by *c*1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that *c*1<=&gt;<=*a*2. The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by *a*1) or drink a healing potion (it increases Vova's health by *c*1; Vova's health can exceed *h*1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by *a*2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack. Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases. Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
```python if __name__ == "__main__": h1,a1,c1 = map(int,input().split()) h2,a2 = map(int,input().split()) tmp = [] while h2>0: if a2>=h1: tmp.append("HEAL") h1 = h1+c1 h1 = h1-a2 else: tmp.append("STRIKE") h2 = h2-a1 h1 = h1-a2 n=len(tmp) print(n) for i in tmp: print(i) ```
MatrixStudio/Codeforces-Python-Submissions
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.
```python n,d=map(int,input().split()) o=0 if n in [1,3,5,7,8,10,12]: if d==7 or d==6: o=6 else: o=5 if n in [4,6,9,11]: if d==7: o=6 else: o=5 if n==2: if d==7: o=5 else: o=4 print(o) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers *a*1,<=*a*2,<=...,<=*a**n*. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
```python import sys input=sys.stdin.readline def main(): n = int(input()) a = list(map(int, input().split())) a.sort() m, nm = a[1]-a[0], 1 for i in range(1, n-1): if a[i+1]-a[i] < m: m, nm = a[i+1]-a[i], 1 elif a[i+1]-a[i]==m: nm +=1 print(m,nm) main() ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo has an *n*<=×<=*m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a**ij*. In one move the penguin can add or subtract number *d* from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
```python def f(m, arr): ans = 0 for x in range(len(arr)): ans+=abs(m-arr[x])/d return ans nmd = [int(x) for x in input().split()] n = nmd[0] m = nmd[1] d = nmd[2] status = True arr = [] for x in range(m): arr+=[int(i) for i in input().split()] for x in arr: if x%d != 0: status = False break if status == True: l = 0 r = 1e4 while (r > l+2): m1 = l + (r-l)//3 m2 = m1 + (r-l)//3 if (f(m1,arr) > f(m2,arr)): l = m1 else: r = m2 print(int(min(f(l,arr), f(l+1,arr), f(l+2,arr)))) else: print("-1") ```
MatrixStudio/Codeforces-Python-Submissions
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets: - 1+2*3=7 - 1*(2+3)=5 - 1*2*3=6 - (1+2)*3=9 Note that you can insert operation signs only between *a* and *b*, and between *b* and *c*, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2. It's easy to see that the maximum value that you can obtain is 9. Your task is: given *a*, *b* and *c* print the maximum value that you can get.
```python a=int(input()) b=int(input()) c=int(input()) print(max(a+c+b,a*c*b,a+c*b,a*c+b,a*(b+c),(a+b)*c)) ```
MatrixStudio/Codeforces-Python-Submissions
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump. For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out. Noora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem.
```python n, f = map(int, input().split()) a=[] c =0 for i in range(n): x, y = map(int, input().split()) c =c + min(x, y) a.append(min(2 * x, y) - min(x, y)) a.sort(reverse=True) for i in range(f): if i < n: c += max(a[i], 0) else: break print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has *n* days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this *n* days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the *i*-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 1. on this day the gym is closed and the contest is carried out; 1. on this day the gym is open and the contest is not carried out; 1. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
```python # !/bin/env python3 # coding: UTF-8 # ✪ H4WK3yE乡 # Mohd. Farhan Tahir # Indian Institute Of Information Technology and Management,Gwalior # Question Link # # # ///==========Libraries, Constants and Functions=============/// import sys sys.setrecursionlimit(2000) inf = float("inf") mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() # ///==========MAIN=============/// def recurse(arr, i, flag): if i == len(arr): return 1 if dp[i][flag] != inf: return dp[i][flag] if arr[i] == 0: dp[i][flag] = min(dp[i][flag], 1+recurse(arr, i+1, 2)) elif arr[i] == 1: if flag != 1: dp[i][flag] = min(dp[i][flag], recurse(arr, i+1, 1), 1+recurse(arr, i+1, 2)) else: dp[i][flag] = min(dp[i][flag], 1+recurse(arr, i+1, 2)) elif arr[i] == 2: if flag != 0: dp[i][flag] = min(dp[i][flag], recurse(arr, i+1, 0), 1+recurse(arr, i+1, 2)) else: dp[i][flag] = min(dp[i][flag], 1+recurse(arr, i+1, 2)) elif arr[i] == 3: if flag == 0: dp[i][flag] = min(dp[i][flag], 1+recurse(arr, i+1, 2), recurse(arr, i+1, 1)) elif flag == 1: dp[i][flag] = min(dp[i][flag], 1+recurse(arr, i+1, 2), recurse(arr, i+1, 0)) elif flag == 2: dp[i][flag] = min(dp[i][flag], 1+recurse(arr, i+1, 2), recurse(arr, i+1, 0), recurse(arr, i+1, 1)) return dp[i][flag] def main(): n = int(input()) arr = get_array() print(recurse(arr, 0, 2)-1) if __name__ == "__main__": dp = [[inf for _ in range(3)] for _ in range(101)] main() ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times. Please output the maximum number of cake cells that the cakeminator can eat.
```python # -*- coding: utf-8 -*- """ Created on Fri Nov 19 21:18:28 2021 @author: odraode """ ''' Testo dell'esercizio su 'https://codeforces.com/problemset/problem/330/A' - diff 800 ''' def countPieces(k): ris =0 for i in range(len(k)): if(k[i]=='.'): ris+=1 return ris r,c = input().split(' ') r = int(r) c = int(c) matrix = [ [ 0 for i in range(c) ] for j in range(r) ] for x in range(r): l = input() for y in range(c): # matrix[c][y]='S' if(l[y]=='S') else matrix[c][y]='.' if(l[y]=='S'): matrix[x][y]='S' else: matrix[x][y]='.' ate = 0 for x in range(r): if('S' not in matrix[x]): ate+=c for y in range(c): matrix[x][y]=0 for x in range(c): l=[] for y in range(r): l.append(matrix[y][x]) if('S' not in l): ate+=countPieces(l) print(ate) ```
MatrixStudio/Codeforces-Python-Submissions
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are *n* warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers. Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
```python import sys sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,m=I() g=[[0]*n for i in range(n)] ed=[] an=n*n dg=[0]*n for i in range(m): x,y=I() x-=1;y-=1 dg[x]+=1;dg[y]+=1 g[x][y]=1 g[y][x]=1 ed.append([x,y]) for i in range(m): a,b=ed[i] for j in range(n): if j!=a and j!=b and g[a][j] and g[j][b]: an=min(an,dg[a]+dg[b]+dg[j]-6) if an==n*n: an=-1 print(an) ```
MatrixStudio/Codeforces-Python-Submissions
A map of some object is a rectangular field consisting of *n* rows and *n* columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly *k* islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island). Find a way to cover some cells with sand so that exactly *k* islands appear on the *n*<=×<=*n* map, or determine that no such way exists.
```python n, k = [int(x) for x in input().split()] if (n ** 2 + 1) // 2 < k: print("NO") else: print("YES") count = 0 x = True for i in range(n): lst = [] for j in range(n): if x and count < k: lst.append('L') count += 1 x = False else: lst.append('S') x = True print(''.join(lst)) ```
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 import io import os #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t, x1, y1, x2, y2 = map(int, input().split()) xmove = x2 - x1 ymove = y2 - y1 xneed = abs(xmove) yneed = abs(ymove) if xmove < 0: dx = 'W' else: dx = 'E' if ymove < 0: dy = 'S' else: dy = 'N' directs = input() if directs.count(dx) < xneed or directs.count(dy) < yneed: print(-1) exit() done = 0 cnt = -1 for m in range(t): if done == 0: if directs[m] == dx: xneed -= 1 elif directs[m] == dy: yneed -= 1 if xneed and yneed < 1: done = 1 break cnt += 1 print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
```python x = int(input()) # Input the coordinate of the friend's house # Calculate the minimum number of steps needed min_steps = (x + 4) // 5 # Integer division (//) ensures the result is rounded up print(min_steps) ```
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 coordinates=int(input()) x= list(map(int,input().split())) y= list(map(int,input().split())) z= list(map(int,input().split())) if (sum(x)+sum(y)+sum(z)==0): print('YES') else: print('NO') ```
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 n = int(input()) count = 0 if n <= 9: print("0") else: while n >= 9: n = sum(map(int, str(n))) count = count+1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size *a* can climb into some car with size *b* if and only if *a*<=≤<=*b*, he or she likes it if and only if he can climb into this car and 2*a*<=≥<=*b*. You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.
```python a, b, c, m = [int(x) for x in input().split()] possible = True if m > 2*c or m > b: print(-1) possible = False sm = max(m, c) if sm > 2*m or sm > 2*c: print(-1) possible = False me = max(b, 2*m + 1) if me > 2*b: print(-1) possible = False la = max(a, 2*m + 2) if la > 2*a: print(-1) possible = False if possible: print(sm) print(me) print(la) ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes. Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
```python n = int(input()) words = [] ans = [] for i in range(n): x = input() words.append(x) if len(words[i]) > 10: y = words[i][0] + str(len(words[i])-2) + words[i][-1] ans.append(y) else: ans.append(x) for i in range(n): print(words[i]) ```
MatrixStudio/Codeforces-Python-Submissions
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive.
```python import math def primefactors(n,l): while n%2==0: if l.count(2)==0: l.append(2) n = n//2 for i in range(3,int(math.sqrt(n))+1,2): while (n % i == 0): if l.count(i)==0: l.append(i) n = n//i if n > 2: l.append(n) return len(l) n=int(input()) c=0 for i in range(6,n+1): if primefactors(i,[])==2: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1. Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers. Given this information, is it possible to restore the exact floor for flat *n*?
```python import math n,k=map(int,input().split(' ')) m=[] d=0 for i in range(k): m.append(list(map(int,input().split(' ')))) t=-1 for i in range(101): p=0 for j in m: if ((j[1]-1)*i<j[0]) and (j[0]<=i*j[1]): p+=1 #print(i) if (p==k) and (math.ceil(n/t)!= math.ceil(n/i)): t=i d+=1 #print(i) if d==1: print(math.ceil(n/t)) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define *i* modulo *j* as the remainder of division of *i* by *j* and denote it by . A Modular Equation, as Hamed's teacher described, is an equation of the form in which *a* and *b* are two non-negative integers and *x* is a variable. We call a positive integer *x* for which a solution of our equation. Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations. Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers *a* and *b* determines how many answers the Modular Equation has.
```python a, b = map(int, input().split()) if a == b: print(infinity) elif a < b: print(0) else: c = a - b s = [(c // i) for i in range(1, min(c, 40000)) if a % (c // i) == b] +\ [i for i in range(1, min(c, 40000)) if a % i == b] s = set(s) print(len(s)) ```
MatrixStudio/Codeforces-Python-Submissions
For a positive integer *n* let's define a function *f*: *f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n* Your task is to calculate *f*(*n*) for a given integer *n*.
```python n=int(input()) sum=0 for i in range(1,n+1): if i%2==0: f=i else: f=-i sum=sum+f print(sum) ```
MatrixStudio/Codeforces-Python-Submissions
The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are *n* blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths) Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe) After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way. Thus, if the blinds consist of *k* pieces each *d* in length, then they are of form of a rectangle of *k*<=×<=*d* bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than *l* bourlemeter. The window is of form of a rectangle with side lengths as positive integers.
```python n,x=map(int,input().split()) l=sorted(list(map(int,input().split()))) ans=0 for i in range (x,101): s=0 for j in l: s+=j-j%i ans=max(s,ans) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do 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 a = list(input()) b = list(input()) for i in range(len(a)): if a[i]==b[i]: a[i]=0 else: a[i]=1 print(''.join(map(str,a))) ```
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 n=int(input()) l=list(map(int,input().split())) c=0 mini=l[0] maxi=l[0] for i in range(1,len(l)): if l[i] > maxi: c+=1 maxi=l[i] elif l[i] < mini: c+=1 mini=l[i] print(c) ```
MatrixStudio/Codeforces-Python-Submissions
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=&lt;<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=&lt;<=5). You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
```python lis1=[] for i in range(0,5): lis=list(map(int,input().split())) lis1.append(lis) row=0 col=0 for i in range (0,5): for j in range(0,5): if lis[i][j]==1: row=i col=j print(row+col-6+2) break ```
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()) x1=y1=z1=0 for i in range(n): x,y,z=input().split() x1=x1+int(x) y1=y1+int(y) z1=z1+int(z) if x1==0 and y1==0 and z1==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not. You are given $n$ bracket sequences $s_1, s_2, \dots , s_n$. Calculate the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. Operation $+$ means concatenation i.e. "()(" + ")()" = "()()()". If $s_i + s_j$ and $s_j + s_i$ are regular bracket sequences and $i \ne j$, then both pairs $(i, j)$ and $(j, i)$ must be counted in the answer. Also, if $s_i + s_i$ is a regular bracket sequence, the pair $(i, i)$ must be counted in the answer.
```python def string_value(str): ans=0 valid = True for char in str: if (ans<0 and char=="("): valid=False if char==")": ans-=1 else: ans+=1 ans=0 for char in reversed(str): if (ans<0 and char==")"): valid=False if char=="(": ans-=1 else: ans+=1 return valid, ans num = int(input()) vals = [] for i in range(num): valid, ans = string_value(input()) if valid: vals.append(ans) ans=0 if len(vals)>0: vals = sorted(vals) prev=vals[0] occured=1 occurances = {} keys=[] for i in vals[1:]: if prev!=i: keys.append(prev) occurances[prev] = occured occured = 1 prev=i else: occured += 1 occurances[prev] = occured keys.append(prev) j=0 k=len(keys)-1 while j<=k: if -keys[j]==keys[k]: ans+=occurances[keys[j]]*occurances[keys[k]] if abs(keys[j])>abs(keys[k]): j+=1 else: k-=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You have two variables *a* and *b*. Consider the following sequence of actions performed with these variables: 1. If *a*<==<=0 or *b*<==<=0, end the process. Otherwise, go to step 2;1. If *a*<=≥<=2·*b*, then set the value of *a* to *a*<=-<=2·*b*, and repeat step 1. Otherwise, go to step 3;1. If *b*<=≥<=2·*a*, then set the value of *b* to *b*<=-<=2·*a*, and repeat step 1. Otherwise, end the process. Initially the values of *a* and *b* are positive integers, and so the process will be finite. You have to determine the values of *a* and *b* after the process ends.
```python line = input() a, b = list(map(int, line.strip().split())) def helper(a, b): if a == 0 or b == 0: print(a, b) else: if a >= 2 * b: a = a - 2 * b helper(a, b) else: if b >= 2 * a: b = b - 2 * a helper(a, b) else: print(a, b) helper(a, b) ```
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 a = [int(x) for x in input().split()] fl = False for i in range(6): for j in range(6): for k in range(6): if (i == j or k == j or i == k): continue if a[i] + a[j] + a[k] == sum(a) / 2 and sum(a) % 2 == 0: fl = True if (fl): print('YES') else: print('NO') ```
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 def main(): _ = input() scores = list(int(_) for _ in input().split()) amazings = 0 worst = best = scores[0] for score in scores: if score < worst: amazings += 1 worst = score elif score > best: amazings += 1 best = score print(amazings) if __name__ == "__main__": main() ```
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 = 2 * int(input()) table = [c for c in input().strip() for _ in range(4)] t = dict() for c in table: if c in t: t[c] += 1 else: t[c] = 1 t['.'] = 0 ans = True for k in t: v = t[k] if v > k: ans = False print("YES" if ans else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
```python n=int(input()) c=0 d=0 for i in range(1,n+1): for j in range(1,n+1): if((i+j)==n): c=c+1 if(i%2==0 and j%2==0): print("YES") elif(i%2!=0 and j%2!=0): print("NO") elif(i%2!=0 or j%2==0): print("NO") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Your friend Mishka and you attend a calculus lecture. Lecture lasts *n* minutes. Lecturer tells *a**i* theorems during the *i*-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array *t* of Mishka's behavior. If Mishka is asleep during the *i*-th minute of the lecture then *t**i* will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — *a**i* during the *i*-th minute. Otherwise he writes nothing. You know some secret technique to keep Mishka awake for *k* minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and *n*<=-<=*k*<=+<=1. If you use it on some minute *i* then Mishka will be awake during minutes *j* such that and will write down all the theorems lecturer tells. You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
```python import sys input = sys.stdin.readline L = lambda:list(map(int,input().split())) n,k = map(int,input().split()) # duration + time stay awake t = L() #theorems b = L() #behaviour asleep = 0 extra = 0 for i in range(n): if b[i] == 1: extra += t[i] s = extra for i in range(k): if b[i] == 0: s += t[i] big = s for i in range(1,n-k + 1): if b[i-1] == 0: s -= t[i-1] if b[i+k-1] == 0: s += t[i+k-1] #print("t= ",t[i],t[i+1],t[i+2]) #print("b= ",b[i],b[i+1],b[i+2]) #print("s= ",s) big = max(big,s) print(big) ```
MatrixStudio/Codeforces-Python-Submissions
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that. All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.
```python s=input() k=int(input()) months = ['January','February','March','April','May','June','July','August','September','October','November','December'] ind=months.index(s) tmp=(ind+1+k)%12 print(months[tmp-1]) ```
MatrixStudio/Codeforces-Python-Submissions
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
```python n = int(input()) l = list(map(int,input().split())) r = float('Inf') a,b = 0,0 for i in range(n-1): if abs(l[i]-l[i+1]) < r: r = abs(l[i]-l[i+1]) a,b = i,i+1 if abs(l[n-1]-l[0]) < r: r = abs(l[n-1]-l[0]) a,b = n-1,0 print(a+1,b+1) ```
MatrixStudio/Codeforces-Python-Submissions
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is. Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent. To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand. But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
```python var = int(input()) x = "".join(input().split()) input() search = input().split() s1 = s2 = 0 for val in search: s1 += x.index(val) + 1 s2 += var - x.rindex(val) print(s1,s2) ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* points on a line with their coordinates *x**i*. Find the point *x* so the sum of distances to the given points is minimal.
```python n = int(input()) a = input().split(" ") a = sorted([int(i) for i in a]) print(a[int((n-1) / 2)]) ```
MatrixStudio/Codeforces-Python-Submissions
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place. But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams. Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania. It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
```python w,y=[int(x) for x in input().split()] l=[w,y] l.sort() n=7-l[1] for j in range (1,n+1): if n%j==0 and 6%j==0: ans=int(n/j) ans1=int(6/j) print("{0}/{1}".format(ans,ans1)) ```
MatrixStudio/Codeforces-Python-Submissions
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are *n* trees located along the road at points with coordinates *x*1,<=*x*2,<=...,<=*x**n*. Each tree has its height *h**i*. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [*x**i*<=-<=*h**i*,<=*x**i*] or [*x**i*;*x**i*<=+<=*h**i*]. The tree that is not cut down occupies a single point with coordinate *x**i*. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
```python from itertools import pairwise from math import inf n = int(input()) #数量 l = [] for _ in range(n): l += list(map(int,input().split())), l += (inf, 1), # print(l) tem = -inf ans = 0 for (x1, h1), (x2 ,h2) in pairwise(l): if x1-h1> tem: tem = x1 ans += 1 elif x1 + h1 < x2: tem = x1 + h1 ans += 1 else: tem = x1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A string $s$ of length $n$ can be encrypted by the following algorithm: - iterate over all divisors of $n$ in decreasing order (i.e. from $n$ to $1$), - for each divisor $d$, reverse the substring $s[1 \dots d]$ (i.e. the substring which starts at position $1$ and ends at position $d$). For example, the above algorithm applied to the string $s$="codeforces" leads to the following changes: "codeforces" $\to$ "secrofedoc" $\to$ "orcesfedoc" $\to$ "rocesfedoc" $\to$ "rocesfedoc" (obviously, the last reverse operation doesn't change the string because $d=1$). You are given the encrypted string $t$. Your task is to decrypt this string, i.e., to find a string $s$ such that the above algorithm results in string $t$. It can be proven that this string $s$ always exists and is unique.
```python def solve(): size = int(input()) s = input() for i in range(1, size + 1): if not (size % i): s = s[0:i][::-1] + s[i:] print(s) if __name__ == "__main__": solve() ```
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 ans=[0,0,0] f=0 n=int(input()) s=[list(map(int,input().split())) for i in range(n)] for i in range(n): ans[0]=+s[i][0] ans[1]=+s[i][1] ans[2]=+s[i][2] for x in ans: if x!=0: f=1 if f==1: print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got *n* positive integers. He wonders, how many of those integers have not more than *k* lucky digits? Help him, write the program that solves the problem.
```python a,b= map(int,input().split()) c=list(map(int,input().split())) d=0 for j in range(a): if str(c[j]).count('4')+str(c[j]).count('7')<=b: d+=1 print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for *n* items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to *n* by changing the number of as few items as possible. Let us remind you that a set of *n* numbers forms a permutation if all the numbers are in the range from 1 to *n*, and no two numbers are equal.
```python def main(): n = int(input()) a = list(map(int,input().split())) used = set() original = set(a) not_used = set(range(1,n+1)) - original for i in range(n): if a[i] > n or a[i] in used: temp = next(iter(not_used),None) if temp is not None: a[i] = temp not_used.remove(temp) used.add(temp) else: used.add(a[i]) print(*a) if __name__ == '__main__': main() ```
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 x=int(input()) gift=list(map(int,input().split(' '))) array=[] for t in range(x): array.append(0) for a,b in enumerate(gift): array[b-1]=a+1 for d in array: print(d,end=' ') ```
MatrixStudio/Codeforces-Python-Submissions
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=&gt;<=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency). The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer? The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
```python import queue def get_ans(): qlo = queue.PriorityQueue() qhi = queue.PriorityQueue() n,m = map(int,input().split()) l = list(map(int,input().split())) for i in l: qlo.put(i) qhi.put(-i) # MAX hi = 0 nhi = 0 while nhi < n and not qhi.empty(): nhi+=1 x = qhi.get() hi-=x x = x + 1 if x != 0: qhi.put(x) # MIN lo = 0 nlo = 0 while nlo < n and not qlo.empty(): nlo+=1 x = qlo.get() lo+=x x = x - 1 if x != 0: qlo.put(x) return hi,lo hi,lo = get_ans() print(hi, lo) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel is playing a game with numbers now. Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* &gt; *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum of all numbers as small as possible. Please help Ciel to find this minimal sum.
```python casos = int(input()) limite = int(input()) numeros = [x for x in range(0,limite+1)] contadorCorrectos = 0 for k in range(casos): #Comparar cada numero numero = int(input()) contadorDigito = 0 while numero>0: #Procesar el ultimo dgito digito = numero%10 numero//=10 if digito in numeros: contadorDigito+=1 if contadorDigito >=limite+1: contadorCorrectos+=1 print(contadorCorrectos) ```
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 s=input() u=0 l=0 for i in s: if i.islower()==True: l+=1 else: u +=1 if l >= u : print(s.lower()) else: print(s.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
Ann and Borya have *n* piles with candies and *n* is even number. There are *a**i* candies in pile with number *i*. Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly *n*<=/<=2 piles contain number of candies that is a square of some integer and exactly *n*<=/<=2 piles contain number of candies that is not a square of any integer.
```python import sys input = lambda: sys.stdin.readline().rstrip() N = int(input()) A = list(map(int, input().split())) ans = 0 B = [] C = [] for a in A: t = int(a**0.5) if t*t!=a: B.append(a) else: C.append(a) if len(B)<N//2: C.sort() t = N//2-len(B) for i in range(t): if C[i]==0: ans+=2 else: ans+=1 exit(print(ans)) C = [] for b in B: t = int(b**0.5) t1 = t*t t2 = (t+1)**2 C.append(min(abs(t1-b),abs(t2-b))) C.sort() t = len(B)-N//2 for i in range(t): ans+=C[i] print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*: - *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE Each child happens to be good at exactly one of these three subjects. The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team. What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
```python #https://codeforces.com/problemset/problem/490/A number_of_students = int(input()) speciality_list = [int(x) for x in input().split(" ")] programming, math, pe = [], [], [] for x in range(number_of_students): if(speciality_list[x] == 1): programming.append(x+1) elif(speciality_list[x] == 2): math.append(x+1) else: pe.append(x+1) groups = min([len(programming), len(math), len(pe)]) if (groups == 0): print(0) else: for x in range(groups): print(str(programming[x]) + " " + str(math[x]) + " " + str(pe[x])) ```
MatrixStudio/Codeforces-Python-Submissions
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were *x* details in the factory storage, then by the end of the day the factory has to produce (remainder after dividing *x* by *m*) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory. The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by *m*). Given the number of details *a* on the first day and number *m* check if the production stops at some moment.
```python a,m=map(int,input().split()) if a/m==0: print('Yes') else: print('No') ```
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 size = int(input()) string = input() output_str = '' i = 0 while i < size-1: if string[i] != string[i+1]: output_str += 'D' i+= 1 i+=1 print(size - len(output_str)) ```
MatrixStudio/Codeforces-Python-Submissions
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase. Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then — zero or more lowercase letters. To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
```python import re letter = input() uppercaseGroup = r'[A-Z]+' lowercaseGroup = r'[a-z]+' firstUpperCase = False lastUpperCase = False if re.search(uppercaseGroup, letter[0]): firstUpperCase = True if re.search(uppercaseGroup, letter[len(letter)-1]): lastUpperCase = True lower = re.split(uppercaseGroup, letter) upper = re.split(lowercaseGroup, letter) if firstUpperCase: upper[0] = '' lower = list(filter(lambda group: group != '', lower)) upper = list(filter(lambda group: group != '', upper)) lower = list(map(lambda group: len(group), lower)) upper = list(map(lambda group: len(group), upper)) acc = 0 for group in range(len(upper)-1, -1, -1): acc += upper[group] upper[group] = acc acc = 0 for group in range(len(lower)): acc += lower[group] lower[group] = acc minOperations = float("inf") for group in range(len(upper)): leftSum = upper[group] + (lower[group-1] if (group != 0) else 0) rightSum = lower[group] + (upper[group+1] if (group+1 != len(upper)) else 0) minOperations = min(leftSum, rightSum, minOperations) print(minOperations if minOperations != float("inf") else 0) ```
MatrixStudio/Codeforces-Python-Submissions
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner. For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
```python n, k = map(int, input().split()) PowersOfThePlayer = list((map(int, input().split()))) PowerOfTheWinner=None if len(PowersOfThePlayer)==2: PowerOfTheWinner=max(PowersOfThePlayer) if PowersOfThePlayer[0] == max(PowersOfThePlayer) and PowerOfTheWinner == None: PowerOfTheWinner=PowersOfThePlayer[0] if k<=len(PowersOfThePlayer) and PowerOfTheWinner == None: if PowersOfThePlayer[0]> max(PowersOfThePlayer[1:]): PowerOfTheWinner=PowersOfThePlayer[0] if PowerOfTheWinner == None: WinsOfThePlayer=[0]*len(PowersOfThePlayer) while True: Winer=None Loser=None Player1=PowersOfThePlayer[0] Player2=PowersOfThePlayer[1] if Player1 > Player2: Winer=Player1 Loser=Player2 WinsOfThePlayer[0]=WinsOfThePlayer[0]+1 else: Winer=Player2 Loser=Player1 WinsOfThePlayer[1]=WinsOfThePlayer[1]+1 if max(WinsOfThePlayer)==k or PowersOfThePlayer[0]==max(PowersOfThePlayer): IndexPowerWin=WinsOfThePlayer.index(max(WinsOfThePlayer)) PowerOfTheWinner=PowersOfThePlayer[IndexPowerWin] break else: IndexLoser=PowersOfThePlayer.index(Loser) TempPower=PowersOfThePlayer.pop(IndexLoser) PowersOfThePlayer.append(TempPower) TempWin=WinsOfThePlayer.pop(IndexLoser) WinsOfThePlayer.append(TempWin) print(PowerOfTheWinner) ```
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 n1 = input() n2 = input() final = "" x = list(zip(n1,n2)) print(list(x)) for i in x: a,b = i if a==b: final+="0" else: final+="1" print(final) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. It is guaranteed that all the values are integer powers of $2$ (i.e. $a_i = 2^d$ for some non-negative integer number $d$). Polycarp wants to know answers on $q$ queries. The $j$-th query is described as integer number $b_j$. The answer to the query is the minimum number of coins that is necessary to obtain the value $b_j$ using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value $b_j$, the answer to the $j$-th query is -1. The queries are independent (the answer on the query doesn't affect Polycarp's coins).
```python n, q = map(int, input().split()) temp = 0 at = 1 d = {} dd = {} for i in range(32): d[at] = [temp, 0] dd[temp] = [at, 0] temp+=1 at*=2 l = [int(x) for x in input().split()] for i in range(n): dd[d[l[i]][0]][1]+=1 # print(d) # print(dd) for _ in range(q): t = int(input()) c = 0 coin = 0 for i in range(30, -1, -1): # print(i) c = min(dd[i][1], (t//dd[i][0])) t-= (c*(dd[i][0])) coin+=c # print(i, t) # print(t) if(t !=0): print(-1) else: print(coin) ```
MatrixStudio/Codeforces-Python-Submissions
Young Timofey has a birthday today! He got kit of *n* cubes as a birthday present from his parents. Every cube has a number *a**i*, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to *n* in their order. Dima performs several steps, on step *i* he reverses the segment of cubes from *i*-th to (*n*<=-<=*i*<=+<=1)-th. He does this while *i*<=≤<=*n*<=-<=*i*<=+<=1. After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
```python N = int(input()) - 1 _arr = list(map(int, input().split())) i = 0 while i < N - i: if (i + 1) % 2 != 0: _t = _arr[i] _arr[i] = _arr[N - i] _arr[N - i] = _t i += 1 _arr = list(map(str, _arr)) print(' '.join(_arr)) ```
MatrixStudio/Codeforces-Python-Submissions
Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point *x*. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach *x*.
```python #**************************************** #** Solution by BAZOOKA ** #** Sponsored by RED BULL** #** Team Galaxy ** #** I love ❤Kateryna Gret❤ ** #****************************************/ n, i=abs(int(input())), 0 while n>0 or n%2==1: i+=1; n-=i print(i) #**************************************** #** Solution by BAZOOKA ** #** Sponsored by RED BULL** #** Team Galaxy ** #** I love ❤Kateryna Gret❤ ** #****************************************/ ```
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 # Read input n = int(input()) arr = list(map(int, input().split())) arr.sort() if arr[0] != 1: print(1) else: f = 0 for i in range(len(arr)-1): if arr[i+1] - arr[i] > 1: f= 1 break if f: print(arr[i]+1) else: print(arr[-1]+1) ```
MatrixStudio/Codeforces-Python-Submissions
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string *s*, consisting of lowercase English letters and a positive integer *k*. Your task is to reorder the letters in the string *s* in such a way that the resulting string is a *k*-string.
```python k = int(input()) s = input() a = set() for i in s: a.add(i) a = list(a) check = -1 for i in a: if(s.count(i)!=k): print(check) else: check = 1 if(check == 1): for i in range(k): for j in a: print(j,end="") ```
MatrixStudio/Codeforces-Python-Submissions
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of *n* integers. A sequence *a*1, *a*2, ..., *a**n*, consisting of *n* integers, is Hungry if and only if: - Its elements are in increasing order. That is an inequality *a**i*<=&lt;<=*a**j* holds for any two indices *i*,<=*j* (*i*<=&lt;<=*j*). - For any two indices *i* and *j* (*i*<=&lt;<=*j*), *a**j* must not be divisible by *a**i*. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with *n* elements.
```python import sys n=int(input()) sys.stdout.write(str(n)) a=n+1 b=n*2 for idx in range(a, b): sys.stdout.write(" " + str(idx)) ```
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 s = input() U = 0 L = 0 for i in range(len(s) - 1): if s[i].isupper(): U += 1 else: L += 1 if L < U: print(s.upper()) elif U < L: print(s.lower()) elif U == L: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
```python from collections import Counter def ans(arr): dummy = Counter(arr) max_ = max(list(dummy.values())) for i in dummy.keys(): if(dummy[i] == max_): return(i) if __name__ == '__main__': n = int(input()) temp = [] for _ in range(n): temp.append(input()) print(ans(temp)) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
```python n = int(input()) arr = [] for i in range(n): arr.append(int(input())) arr.sort() ans = 0 a,b =0,n//2 while a<n//2 and b<n: if arr[a]*2<=arr[b]: ans+=1 a+=1 b+=1 else: b+=1 print(n-ans) ```
MatrixStudio/Codeforces-Python-Submissions
A positive integer is called a 2-3-integer, if it is equal to 2*x*·3*y* for some non-negative integers *x* and *y*. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not. Print the number of 2-3-integers on the given segment [*l*,<=*r*], i. e. the number of sich 2-3-integers *t* that *l*<=≤<=*t*<=≤<=*r*.
```python def bsl(l, rb, k): while l < rb: mid = (l + rb) // 2 if nums[mid] >= k: rb = mid else: l = mid+1 return l def bsr(l, r, k): while l < r: mid = (l + r + 1) // 2 if nums[mid] <= k: l = mid else: r = mid - 1 return l if __name__ == '__main__': stop = int(2e9) nums = [] i = 1 while i <= stop: nums.append(i) i *= 2 ts = len(nums) for i in range(ts): cur = nums[i] * 3 while cur <= stop: nums.append(cur) cur *= 3 nums.sort() ln = len(nums) l, r = map(int, input().split()) le, re = 0, ln-1 while le < ln and nums[le] < l: le += 1 while re >= 0 and nums[re] > r: re -= 1 #print(le, re, nums[le], nums[re], nums[le:re+1]) # if l == r and nums[le] == l: # print(1) #else: # print(re - le + 1 ) print(re-le+1) ```
MatrixStudio/Codeforces-Python-Submissions
Imp likes his plush toy a lot. Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies. Initially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly *x* copied toys and *y* original toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies.
```python x,y=[int(i) for i in input().split()] z=y-1 if y==2 and x%2==0: print ('No') elif x%z==0: print('Yes') else: print('No') ```
MatrixStudio/Codeforces-Python-Submissions
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=&gt;<=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency). The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer? The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
```python n = int(input()) def cus_fact(na): l = [] sr = "" for j in range(na): sr += str(j) + " " l.append(str(j)) if n >= 1: sr += str(na) sr += " " + ' '.join(l[::-1]) sr = sr.rstrip() # print("S : ", s) return sr lst = [] for i in range(n+1): s = cus_fact(i) print(" "*(n-i)*2, end="") print(s) lst.append(s) for i in range(n-1, -1, -1): print(" "*(n-i)*2, end="") print(lst[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are *n* applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). *q* events are about to happen (in chronological order). They are of three types: 1. Application *x* generates a notification (this new notification is unread). 1. Thor reads all notifications generated so far by application *x* (he may re-read some notifications). 1. Thor reads the first *t* notifications generated by phone applications (notifications generated in first *t* events of the first type). It's guaranteed that there were at least *t* events of the first type before this event. Please note that he doesn't read first *t* unread notifications, he just reads the very first *t* notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
```python #code n=int(input()) s1=input() x1=s1.split() s2=input() x2=s2.split() dic=dict() st=set() m=0 for i in range(n): if int(x1[i])==0: continue elif int(x2[i])==0: if 0 in st: dic[0]=dic[0]+1 m=max(m,dic[0]) else: st.add(0) dic[0]=1 m=max(m,dic[0]) elif int(x1[i])/int(x2[i]) in st: dic[int(x1[i])/int(x2[i])]=dic[int(x1[i])/int(x2[i])]+1 m=max(m,dic[int(x1[i])/int(x2[i])]) else: st.add(int(x1[i])/int(x2[i])) dic[int(x1[i])/int(x2[i])]=1 m=max(m,dic[int(x1[i])/int(x2[i])]) print(m) ```
MatrixStudio/Codeforces-Python-Submissions
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of *n* distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers *x* and *y* from the set, such that the set doesn't contain their absolute difference |*x*<=-<=*y*|. Then this player adds integer |*x*<=-<=*y*| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
```python import random import time n = int(input()) list = list(map(int, input().split())) a=max(list) c=len(list) if c%2==0: print("Bob") else: print("Alice") ```
MatrixStudio/Codeforces-Python-Submissions
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square. A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
```python from math import * n=int(input()) l=list(map(int,input().split())) l.sort(reverse=True) for i in l: if i > 0 and sqrt(i)!=int(sqrt(i)): print(i) exit() for i in l: if i < 0: print(i) exit() ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
```python li='doG is mY fAv' li=li.swapcase() li=li.split(' ') print(li) s='' for i in li[::-1]: s+=i+' ' print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes. Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
```python t = int(input()) #test cases for i in range(t): word_list = input().split() # print (word_list) for word in word_list: if len(word) > 10: word_letters = [*word] print(f"{word_letters[0]}{len(word)-2}{word_letters[-1]}") else: print(word) ```
MatrixStudio/Codeforces-Python-Submissions
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \to 2 \to \ldots n \to 1$. Flight from $x$ to $y$ consists of two phases: take-off from planet $x$ and landing to planet $y$. This way, the overall itinerary of the trip will be: the $1$-st planet $\to$ take-off from the $1$-st planet $\to$ landing to the $2$-nd planet $\to$ $2$-nd planet $\to$ take-off from the $2$-nd planet $\to$ $\ldots$ $\to$ landing to the $n$-th planet $\to$ the $n$-th planet $\to$ take-off from the $n$-th planet $\to$ landing to the $1$-st planet $\to$ the $1$-st planet. The mass of the rocket together with all the useful cargo (but without fuel) is $m$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $1$ ton of fuel can lift off $a_i$ tons of rocket from the $i$-th planet or to land $b_i$ tons of rocket onto the $i$-th planet. For example, if the weight of rocket is $9$ tons, weight of fuel is $3$ tons and take-off coefficient is $8$ ($a_i = 8$), then $1.5$ tons of fuel will be burnt (since $1.5 \cdot 8 = 9 + 3$). The new weight of fuel after take-off will be $1.5$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well. Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
```python n = int(input()) m = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] flag = 1 for i in range(n): if a[i] == 1 or b[i] == 1: print(-1) flag = 0 break if flag: wt = m wt += wt/(b[0]-1) for i in range(n-1,0,-1): wt += wt/(a[i]-1) wt += wt/(b[i]-1) wt += wt/(a[0]-1) print(wt-m) ```
MatrixStudio/Codeforces-Python-Submissions
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly *x* bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days?
```python x=int(input()) d=0 if n%2==0: d=1 else: d=2 ```
MatrixStudio/Codeforces-Python-Submissions
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation. We will consider an extremely simplified subset of Python with only two types of statements. Simple statements are written in a single line, one per line. An example of a simple statement is assignment. For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty. You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
```python dp = [1] for i in range(int(input()) - 1): if input() == 's': for j in range(1, i + 1): dp[j - 1] += dp[j] dp.append(0) else: dp.append(0) for j in range(i + 1, 0, -1): dp[j] = dp[j - 1] dp[0] = 0 print(dp) input() print(sum(dp)) ```
MatrixStudio/Codeforces-Python-Submissions
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different. For example, if *X*<==<=10910<==<=11011012, *Y*<==<=4110<==<=1010012, then: Write a program, which takes two non-negative integers *A* and *B* as an input and finds two non-negative integers *X* and *Y*, which satisfy the following conditions: - *A*<==<=*X*<=+<=*Y* - *B* <==<= *X* xor *Y*, where xor is bitwise exclusive or. - *X* is the smallest number among all numbers for which the first two conditions are true.
```python a,b=int(input()),int(input()) if a<b or (a-b)%2!=0: # 除不尽会有进位错误 print("-1") else: print(int((a-b)/2),int(a-(a-b)/2)) # 需要使用 int 抹掉小数点 ```
MatrixStudio/Codeforces-Python-Submissions
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place. But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams. Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania. It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
```python a,b = map(int,input().split()) m = max(a,b) if m == 1: print("6/1") elif m == 2: print("5/1") elif m == 3: print("4/1") elif m == 4: print("3/1") elif m == 5: print("2/1") elif m == 6: print("1/1") ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes. Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
```python def check_word(word: str) -> str: if len(word) > 10: ans = word[0] + str(len(word) - 2) + word[-1] else: ans = word return ans num = int(input()) while num != 0: word = input() anss = check_word(word) num -= 1 print(anss) ```
MatrixStudio/Codeforces-Python-Submissions
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence. Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring. Substring is a continuous subsequence of a string.
```python import sys def main(): s1 = input() s2 = input() print(s1.count(s2)) main() ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers *a*1,<=*a*2,<=...,<=*a**n*. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
```python n = int(input()) dist = list(map(int, input().rstrip().split())) dist.sort() min_dist = 10**9 count = 0 for i in range(n-1): x = dist[i+1] - dist[i] if x < min_dist: min_dist = x count = 1 elif x == min_dist: count += 1 print(min_dist , count) ```
MatrixStudio/Codeforces-Python-Submissions
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner. For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
```python # n = number of people # k = number of wins in a row # p = power of player n, k = map(int, input().split()) p = list(map(int, input().split())) current_player_power = p[0] current_player_wins = 0 for i in range(1, n): if p[i] < current_player_power: current_player_wins +=1 else: current_player_power = p[i] current_player_wins =1 if current_player_wins == k: break print(current_player_power) ```
MatrixStudio/Codeforces-Python-Submissions
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet. Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if: - on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.
```python n = int(input()) li = [] for _ in range(n): li.append(input()) #print(li) corner = li[0][0] middle = li[0][1] for a in range(n): for b in range(n): if a==b or a+b == n-1: if li[a][b] != corner: #print(0,a,b) print("NO") exit() else: if li[a][b] != middle: #print(1,a,b) print("NO") exit() print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Iahub got bored, so he invented a game to be played on paper. He writes *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices *i* and *j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) and flips all values *a**k* for which their positions are in range [*i*,<=*j*] (that is *i*<=≤<=*k*<=≤<=*j*). Flip the value of *x* means to apply operation *x*<==<=1 - *x*. The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
```python import sys input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) d = [0 for _ in range(n)] mx = 0 cnt = 0 for i in range(n): if a[i] == 1: a[i] = -1 cnt += 1 else: a[i] = 1 for i in range(n): if i == 0: d[i] = max(a[i],0) else: d[i] = max(d[i-1] + a[i],0) mx = max(mx,d[i]) print(cnt - 1 if cnt == n else cnt+mx) ```