source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has *n* buses and *m* trolleys, the buses are numbered by integers from 1 to *n*, the trolleys are numbered by integers from 1 to *m*. Public transport is not free. There are 4 types of tickets: 1. A ticket fo...
```python import sys; c1, c2, c3, c4 = map(int, sys.stdin.readline().split(' ')); nbBuses, nbTrolleys = map(int, sys.stdin.readline().split(' ')); buses = map(int, sys.stdin.readline().split(' ')); trolleys = map(int, sys.stdin.readline().split(' ')); minBusesCost = 0; for nbRide in buses: minBusesCost += min(c2, n...
MatrixStudio/Codeforces-Python-Submissions
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is di...
```python a,b,c=map(int,input().split()) for i in range(9): y=a*10+i #print(y) if (y%b)==0: #print(y) y=y*(10**(c-1)) print(y) exit(0) print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Lavrenty, a baker, is going to make several buns with stuffings and sell them. Lavrenty has *n* grams of dough as well as *m* different stuffing types. The stuffing types are numerated from 1 to *m*. Lavrenty knows that he has *a**i* grams left of the *i*-th stuffing. It takes exactly *b**i* grams of stuffing *i* and ...
```python n, m, c, d = map(int, raw_input().split()) arr=[0] * 1001 for i in range(c, n+1): arr[i] = arr[i-c] + d for l in range(0, m): a, b, c, d = map(int, raw_input().split()) for i in range(0, a/b): j = n while(j >= c): arr[j] = max(arr[j], arr[j - c] + d) j -= 1 print arr[n] ```
MatrixStudio/Codeforces-Python-Submissions
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)...
```python n,q=map(int,input().split()) a=sorted(map(int,input().split())) b=[0]*n for _ in[0]*q: l,r=map(int,input().split()) b[l-1]+=1 if r<n:b[r]-=1 c=[b[0]] for i in range(1,n):c+=c[-1]+b[i], c=sorted(c) print(sum(a[i]*c[i] for i in range(n))) ```
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*. Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits....
```python number=input() res=[] for i in number: if 5<=int(i): res.append(9-int(i)) else: res.append(int(i)) if res[0]==0: res[0]=9 print(''.join(list(map(str,res)))) ```
MatrixStudio/Codeforces-Python-Submissions
Soon a school Olympiad in Informatics will be held in Berland, *n* schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the *n* participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly...
```python x = int(input()) f = [0, 0] s = [0, 0] t = [0, 0] str = input().split(' ') f[0] = int(str[0]) f[1] = int(str[1]) str = input().split(' ') s[0] = int(str[0]) s[1] = int(str[1]) str = input().split(' ') t[0] = int(str[0]) t[1] = int(str[1]) maxf = x - s[0] - t[0] if(maxf > f[1]): maxf = f[1] ...
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
```python n = input() lucky_digits = n.count('4') + n.count('7') lucky_count = 0 for digit in str(lucky_digits): if digit == '4' or digit == '7': lucky_count += 1 if lucky_count == len(str(lucky_digits)): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with th...
```python def sol(row, col, board, new_board = ""): for i in range(row): for j in range(col): if board[i][j] == "-": new_board += "-" elif (i + j) % 2 == 0: new_board += "B" else: new_board += "W" new_board += "\n" return new_board ...
MatrixStudio/Codeforces-Python-Submissions
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1. Note that all c...
```python a, f = int(input()), 0 k = a - 2 for i in range(2, a): s = 0 b = a while True: s = s * 10 + b%i if b // i == 0: break b = b//i f += sum([int(i) for i in str(s)]) r = 2 while True: if f%r == 0 and k%r == 0: f //= r k //= r ...
MatrixStudio/Codeforces-Python-Submissions
You are given an array of *n* elements, you must make it a co-prime array in as few moves as possible. In each move you can insert any positive integral number you want not greater than 109 in any place in the array. An array is co-prime if any two adjacent numbers of it are co-prime. In the number theory, two integ...
```python from math import * n=int(input()) a=list(map(int,input().split(" "))) l=[] l.append(a[0]) for i in range(1,n): if(gcd(a[i],a[i-1])!=1): l.append(1) l.append(a[i]) print(len(l)-n) print(*l) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly. An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. ...
```python #!/usr/bin/env python3 def pow(b,e): if e == 1: return b if e%2 == 0: result = pow(b,e//2) result = result * result return result else: result = pow(b,e//2) result = result * result * b return result return result n = int(input("")) if n...
MatrixStudio/Codeforces-Python-Submissions
One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his...
```python n, k = [int(x) for x in input().split()] l = list(input()) s = list(set(l)) f = -1 for i in s: count = 0 for j in l: if i == j: count -= -1 f = max(f, count) if f > k: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Let's consider a table consisting of *n* rows and *n* columns. The cell located at the intersection of *i*-th row and *j*-th column contains number *i*<=×<=*j*. The rows and columns are numbered starting from 1. You are given a positive integer *x*. Your task is to count the number of cells in a table that contain num...
```python n, x = map(int, input().split()) cn = 0 if n >= x: cn += 2 n = x // 2+1 if x == 1: cn -= 1 for i in range(2, n): if x % i == 0: cn += 1 print(cn) ```
MatrixStudio/Codeforces-Python-Submissions
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of *n* square cells (that is, on a 1<=×<=*n* table). At the beginning of the game Alice puts *k* ships on the field without telling their positions to Bob. Each ship looks as a 1<=×<=*a* rectangle (that is,...
```python from bisect import bisect_left def solve(n, k, a, m, x): pre = [0]*(n+2) pos = [0]*(n+2) d = [-1]*(n+2) for i in range(1, n+1): pre[i] = pre[i-1] + (i in x) pos[i] = pos[i-1] + ((i%(a+1)==0) and (i+a <= n) and (i-1 not in x) and (i+a not in x)) l =...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python n=int(input()) x,y,z=[],[],[] for i in range(n): s=list(map(int,input().split())) x.append(s[0]) y.append(s[1]) z.append(s[2]) if sum(x)==0 and sum(y)==0 and sum(z)==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordin...
```python n,l=map(int,input().split()) li=list(map(int,input().split())) count=0 for i in range(1,n): k= li[i]-li[i-1] if k-(2*l)==0: count+=1 if k-(2*l)>0: count+=2 print(count+2) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python string = str(input()) text = 'hello' pointer = 0 for j in range(len(string)): if string[j] == text[pointer]: pointer += 1 if pointer == len(text): break if pointer == len(text): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's ...
```python n = int(input()) a = int(input()) b = int(input()) c = int(input()) m = min(a,b,c) if m == a: n -= 1 dist = 0 if n > 0: dist += n*a print(dist) elif m == b: n -= 1 dist = 0 if n > 0: dist += n*b print(dist) else: n -= 1 dist = 0 ...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as *n* days. Right now his task is to make a series of reports about the company's performance for the last *n* days. We know that the main information in a day report is value *a**i*, the company's profit on the *i*-th day. ...
```python n=int(input()) a=list(map(int,input().split())) po=0 ne=0 no=0 l=[] for i in range(n): if(a[i]<0): ne=ne+1 if(a[i]>=0): po=po+1 if(ne==2): l.append(po+ne) po=0 ne=0 if(len(l)>0): if(po>0 and ne==0 ): l[-1]=l[-1]+po if(ne>0 and po>0): l.append(ne+po) if(ne>0 and po==0): ...
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...
```python s = input() n = len(s) sml = list(map(lambda i: int('a' <= i <= 'z'), s)) cap = list(map(lambda i: int('A' <= i <= 'Z'), s)) prefsml = [0] * (n+1) for i in range(n): prefsml[i+1] = prefsml[i] + sml[i] suffcap = [0] * (n+1) for i in range(n-1, -1, -1): suffcap[i] = suffcap[i+1] + cap[i] res =...
MatrixStudio/Codeforces-Python-Submissions
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers. Let's remember how Fibonacci numbers can be calculated. *F*0<==<=0, *F*1<==<=1, and all the next numbers are *F...
```python n = int(input()) a=0 b=1 fibs = [a,b] while(b<n): newfib = a+b; a = b b = newfib fibs.append(b) test = fibs[-1-1] + fibs[-1-3] + fibs[-1-4] if(len(fibs) == 0): print("0 0 0 ") exit() elif(len(fibs) == 1): print("0 0 1") exit() if n==test: print(...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python # -*- coding: utf-8 -*- """ Created on Tue Oct 10 10:22:48 2023 @author: koray """ for word in input(): if len(word) > 10: print(word[0] + str(len(word) - 2) + word[-1]) else: print(word) ```
MatrixStudio/Codeforces-Python-Submissions
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver...
```python INT_MAX = float('inf') def main(): n = int(input()) a = [int(i) for i in input().split()] mx = -INT_MAX l = 0 r = 1 while l < n: while r < n: if max(a[l:r + 1]) - min(a[l:r + 1]) <= 1: mx = max(mx, r - l + 1) r += 1 ...
MatrixStudio/Codeforces-Python-Submissions
You have *n* distinct points on a plane, none of them lie on *OY* axis. Check that there is a point after removal of which the remaining points are located on one side of the *OY* axis.
```python n=int(input()) a=0 y1=0 for i in range(n): x,y=[int(i) for i in input().split()] if x<0: a+=1 else: y1+=1 if a<=1 or y1<=1: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
The farmer Polycarp has a warehouse with hay, which can be represented as an *n*<=×<=*m* rectangular table, where *n* is the number of rows, and *m* is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the *i*-th row and the *j*-th column is equal...
```python print("_RANDOM_GUESS_1689592554.5392647")# 1689592554.539285 ```
MatrixStudio/Codeforces-Python-Submissions
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
```python s = str(input()) uppercase_test = 0 uppercase_except_1 = 0 for i in range(len(s)): if ord(s[i])>=65 and ord(s[i])<=90: uppercase_test += 1 for i in range(1,len(s)): if ord(s[i])>=65 and ord(s[i])<=90: uppercase_except_1 += 1 if uppercase_except_1 == len(s)-1: print(st...
MatrixStudio/Codeforces-Python-Submissions
Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers ex...
```python stations = int(input()) exist =0 privious_exist=0 for _ in range(stations): privious_exist = exist exit,enter = map(int,input().split(" ")) if _ == stations : enter =0 exist = privious_exist + (enter - exit) print(exist) ```
MatrixStudio/Codeforces-Python-Submissions
Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes *P*1 watt per minute. *T*1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to *P*2 watt per minute. Finally, after *T...
```python n, p1, p2, p3, t1, t2 = list(map(int, input().split(" "))) l = [] for _ in range(n): l += list(map(int, input().split(" "))) p = 0 for i in range(len(l) // 2 - 1): x = l[2 * i + 2] - l[2 * i + 1] p += p1 * min(t1, x) + p2 * min(t2, max(0, x - t1)) + p3 * max(0, x - t1 - t2) for i in ...
MatrixStudio/Codeforces-Python-Submissions
As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and bec...
```python print("_RANDOM_GUESS_1689416376.18644")# 1689416376.1864593 ```
MatrixStudio/Codeforces-Python-Submissions
A social network for dogs called DH (DogHouse) has *k* special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network. We know that each server takes one second to recompress a on...
```python n, k = (int(p) for p in input().split()) InputVideo = [] DownLoad = [] OutputVideo = [] for o in range(n): I, D = (int(v) for v in input().split()) InputVideo.append(I) DownLoad.append(D) i = 0 for j in range(k): OutputVideo.append(InputVideo[i] + DownLoad[i]) i += 1 if i == n: ...
MatrixStudio/Codeforces-Python-Submissions
Two players play a game. Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players ...
```python n = int(input()) a = list(map(int, input().split())) a.sort() for i in range(n - 1): if i % 2 == 0: del a[-1] elif i % 2 == 1: del a[0] print(a[0]) ```
MatrixStudio/Codeforces-Python-Submissions
This problem differs from one which was on the online contest. The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=&lt;<=*a**i*<=+<=1 for *i*<=&lt;<=*n*. The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of inde...
```python n = int(input()) A = list(map(int, input().split())) m = int(input()) B = list(map(int, input().split())) F = [[0 for j in range(m)] for i in range(n)] P = [0 for j in range(m)] for i in range(n): s = -1 t = 0 for j in range(m): F[i][j] = F[i-1][j] if A[i] > B[j] and F[i...
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consis...
```python a = input() for i in range(len(a)): if a[i] == "0": print(a[:i] + a[i + 1:]) quit() print(a[:len(a) - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on the...
```python import bisect n = int(input()) s = list(input()) t = list(input()) s1 = '' t1 = '' for i in range(len(s)): s1+=s[i] t1+=t[i] for i in range(len(s)): s[i] = int(s[i]) t[i] = int(t[i]) s = sorted(s) t = sorted(t) s1 = sorted(s1) t1 = sorted(t1) win = 0 i = 0 while i<len(s): j = 0 whi...
MatrixStudio/Codeforces-Python-Submissions
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color...
```python m,n=map(int,input().split()) f=[[0 for i in range(0,n)] for j in range(0,m)] for i in range(0,m): a=list( map(int,input().split()) ) for j in range(0,n): if i>0: f[i][j]=max(f[i-1][j], f[i][j]) if j>0: f[i][j]=max(f[i][j-1], f[i][j]) f[i][j]+=a[...
MatrixStudio/Codeforces-Python-Submissions
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen $m$ changes of the following form. For some int...
```python n, m = map(int, input().split()) x = y = z = 0 while m != 0: m -= 1 a, b = map(int, input().split()) x += a if b > 0: y += b else: z += b ##print(x, y, z) ans = (n * (n - 1) // 2) * y if n & 1: ans += ((n // 2) * ((n // 2) - 1) // 2) * z else: ans += ((((n - 1) // 2...
MatrixStudio/Codeforces-Python-Submissions
You are given *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Find the number of pairs of indexes *i*,<=*j* (*i*<=&lt;<=*j*) that *a**i*<=+<=*a**j* is a power of 2 (i. e. some integer *x* exists so that *a**i*<=+<=*a**j*<==<=2*x*).
```python from math import log2 n = int(input()) lista = [*map(int, input().split())] a = 0 for _ in lista: num = log2(_) if num.is_integer() == True: a += 1 print(a) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist. Divisor of *n* is any such natural number, that *n* can be divided by it without remainder.
```python from math import sqrt def kthDivisor(n, k): p=int(sqrt(n)) alist=[] for i in range(1,p+1,1): if (n%i==0): alist.append(i) if (i !=p): alist.append(int(n/i)) alist.sort() print(alist) if k >len(alist): print(-1) ...
MatrixStudio/Codeforces-Python-Submissions
You are given a following process. There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. ...
```python if __name__ == '__main__': n, m = input().split() n = int(n) m = int(m) squares = input().split(" ") cont = [0] * n for i in squares: cont[int(i) - 1] += 1 print(min(cont)) ```
MatrixStudio/Codeforces-Python-Submissions
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment o...
```python dias = int(input()) dinero = list(map(int,input().split())) canti_num_ord = 1 j = 1 for i in range(1,dias): if dinero[i] >= dinero[i-1]: j += 1 else: canti_num_ord = j j = 1 print(max(canti_num_ord,j)) ```
MatrixStudio/Codeforces-Python-Submissions
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to...
```python n = int(input()) if n < 10: print(n) elif n < 90 * 2 + 9: x = (n - 10) // 2 + 10 if n % 2: print(x % 10) else: print(x // 10) elif n < 900 * 3 + 90 * 2 + 9: x = (n - 10 - 90 * 2) // 3 + 100 print(x) if (n - 10 - 90 * 2) % 3 == 1: print(x % 10) ...
MatrixStudio/Codeforces-Python-Submissions
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running *R* meters after they finished swimming exactly *S* meters. A winner is a such person that nobody else finishes running before him/her (there ma...
```python print("_RANDOM_GUESS_1689183198.028277")# 1689183198.0283232 ```
MatrixStudio/Codeforces-Python-Submissions
Zxr960115 is owner of a large farm. He feeds *m* cute cats and employs *p* feeders. There's a straight road across the farm and *n* hills along the road, numbered from 1 to *n* from left to right. The distance between hill *i* and (*i*<=-<=1) is *d**i* meters. The feeders live in hill 1. One day, the cats went out to ...
```python print("_RANDOM_GUESS_1693418570.8905473")# 1693418570.8905644 ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python n=input() upp=0 for i in n: if i.isupper(): upp+=1 if upp>len(n)/2: n=n.upper() else: n=n.lower() print(n) ```
MatrixStudio/Codeforces-Python-Submissions
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size ...
```python try: import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as ...
MatrixStudio/Codeforces-Python-Submissions
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions shoul...
```python td=list(map(int,input().split())) t=td[0] d=td[1] l=[] for i in range(1,t+1): if(i%2==0): l.append("1") else: l.append("0") for i in l: print(i,end='') ```
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....
```python def min_number_of_taxis(n, groups): count = [0] * 5 for group in groups: count[group] += 1 taxis = count[4] taxis += count[3] count[1] = max(0, count[1] - count[3]) taxis += count[2] // 2 count[2] %= 2 if count[2] == 1: taxis += 1 count[1]...
MatrixStudio/Codeforces-Python-Submissions
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the ...
```python def fib(limit): a=[1,2] while a[-1]<=limit: a.append(a[-1]+a[-2]) return a n=int(input()) lst=fib(n) s="" pos=0 for i in range(1,n+1): if lst[pos]==i: pos+=1 s+="O" else: s+="o" print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*). You have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input...
```python n, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] cnt, ind, mx = 0, [], 0 for i in range(n): if a[i] > 0: cnt += 1 ind.append(i) mx = max(mx, a[i]) def p(a): pref = [0] for i in range(len(a)): pref.append(pref[-1] + a[i]) ...
MatrixStudio/Codeforces-Python-Submissions
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve th...
```python n, m = list(map(int, input().split())) total_time_dk = 4 * 60 min_time_dk = total_time_dk - m total = 0 y = 0 for i in range(1, n+1): answer_time = 5 x = answer_time * i y += x if min_time_dk - y >= 0: total += 1 print(total) ```
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 manag...
```python planDays,chosenDays=map(int,input().split()) total=[0 for _ in range(planDays)] for i in range(planDays): products,clients=map(int,input().split()) if (i+1)% chosenDays ==0: products=2*products if products >= clients: total[i]= clients elif products < clients and pr...
MatrixStudio/Codeforces-Python-Submissions
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has *n* instruments, it takes *a**i* days to learn *i*-th instrument. Being busy, Amr dedicated *k* days to learn how to play the maximum possible number of instruments. Amr asked for ...
```python n, k = map(int,input().split()) sum=0 l2=[] l=sorted([(x,i) for i,x in enumerate(map(int,input().split()),1)]) for i,j in l: sum=sum+i if(sum<=k): l2.append(j) print(len(l2)) for h in l2: print(h, end=' ') ```
MatrixStudio/Codeforces-Python-Submissions
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of ...
```python s=input() x=[s[0]] for i in range(1,len(s)-1): if s[i]!='/': x.append(s[i]) elif s[i]=='/' and s[i+1]!='/': x.append('/') for k in range(len(x)): print(x[k],end='') ```
MatrixStudio/Codeforces-Python-Submissions
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are *n* flights that must depart today, the *i*-th of them is planned to depart at the *i*-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. Thi...
```python import itertools k, n = map(int, input().split()) data = list(map(int, input().split())) min_v = [] min_value = 99999 v = [] for i in range(k): v.append(i + n + 1) variants = list(itertools.permutations(v, k)) for variant in variants: summ = 0 for i in range(len(variant)): summ...
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers ...
```python n=int(input()) m=int(input()) parameter=m*n Maximum_number_of_dominoes=parameter//2 print(Maximum_number_of_dominoes) ```
MatrixStudio/Codeforces-Python-Submissions
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the n...
```python from collections import defaultdict post = defaultdict(list) n = int(input()) for _ in range(n): c, b, a = input().split() post[a.lower()].append(c.lower()) posters = set(["polycarp"]) def dfs(person, count): c = count for friend in post[person]: if friend in posters...
MatrixStudio/Codeforces-Python-Submissions
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ...
```python sh = [int(w) for w in input().split()] e = [int(q) for q in input().split()] a = sh[0] b = sh[1] x = e[0] y = e[1] z = e[2] n = a+b ka = 2*x+1*y kb = 1*y+3*z d = (ka+kb)-n print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take...
```python x=list(map(int,input().split())) a=x[0] b=x[1] n=x[2] if(n%2==0): print("1") else: print("0") ```
MatrixStudio/Codeforces-Python-Submissions
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers *X* and *Y* realised that they have different bases, which complicated their relations. You're given a number *X* represented in base *b**x* and a number *Y* represented in base *b**y*. Compare those two numbers.
```python n1 = 0 n, b = map(int, input().split()) a = list(map(int, input().split())) a.reverse() for i in range(n): n1 += a[i] * (b ** i) n2 = 0 n, b = map(int, input().split()) a = list(map(int, input().split())) a.reverse() for i in range(n): n2 += a[i] * (b ** i) if n1 < n2: print("<") if ...
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python def sol(): s=input() u=0 l=0 for i in s: if ord(i)<93: u=u+1 else: l=l+1 if l>=u: print(s.lower()) else: print(s.upper()) sol() ```
MatrixStudio/Codeforces-Python-Submissions
Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the *Ox* axis from west to east, and ...
```python n = int(intput()) for i in range(n+1): m = input() print((n-4)/2) ```
MatrixStudio/Codeforces-Python-Submissions
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius. He has a *n*<=×<=*n* chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by b...
```python import itertools n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] r_diag = {} for i in range(-n+1, n): diag_total = 0 # for j in range(0, n): # x, y = i+j, j # if 0 <= x < n and 0 <= y < n: # diag_total += arr[x][y] r_diag[i%(2*n-1)] = sum([ar...
MatrixStudio/Codeforces-Python-Submissions
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas: Here, "mod" means the operation of taking the residue after dividing. The expression means applying ...
```python def main(): n = int(input()) nums = map(int, input().split()) chunk = [] base = 0 for i in range(n + 1): base ^= i chunk.append(base) Q = 0 for i, num in enumerate(nums): q = num chunks, res = divmod(n, i + 1) q ^= chunk[res] if chu...
MatrixStudio/Codeforces-Python-Submissions
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some...
```python n = int(input()) string = input() alphabets = "abcdefghijklmnopqrstuvwxyz" count = 0 flag = 1 for i in alphabets: if i not in string: count += 1 length = len(set(string)) if length > count or n > 26: flag = 0 if(flag == 1): print(n - len(string)) else: print("-1") ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportio...
```python def code(*args): arr, n = args result = float(sum(arr)/n) return "{:.12f}".format(result) if __name__ == "__main__": # Take inputs here n = int(input()) arr = list(map(int, input().split())) result = code(arr, n) # Pass arguments print(result) ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and ...
```python n,w=list(map(int,input().split())) while(n%2==0 and w%2==0): if((n+w)%2==0) print("YES") else: print("NO") print("NO") #5l7 ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
```python a, b = map(int, input().split()) ans = 0 mn = min(a, b) for i in range(1, mn + 1): ans += i print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Reca company makes monitors, the most popular of their models is AB999 with the screen size *a*<=×<=*b* centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio *x*:<=*y* became popular with users. That's why the company wants to reduce monitor AB999...
```python import sys from collections import defaultdict as dd from collections import deque def eprint(*args): print(*args, file=sys.stderr) pl=1 from math import * import copy #sys.setrecursionlimit(10**6) if pl: input=sys.stdin.readline def li(): return [int(xxx) for xxx in input().split()] de...
MatrixStudio/Codeforces-Python-Submissions
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
```python n = int(input()) x = list(map(int,input().split())) n = int(input()) x = list(map(int,input().split())) x = [*set(x)] c = 0 for i in x: if i > min(x) and i <max(x): c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of caramel. Each s...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys s = '^>v<' ch2int = {} for i, c in enumerate(s): ch2int[c] = i a, b, n = sys.stdin.read().split() a = ch2int[a]; b = ch2int[b]; n = int(n) iscw = s[a] == s[(b+n)%n] isccw = s[a] == s[(b-n)%n] if iscw and not isccw: print('cw') ...
MatrixStudio/Codeforces-Python-Submissions
Let's denote a function You are given an array *a* consisting of *n* integers. You have to calculate the sum of *d*(*a**i*,<=*a**j*) over all pairs (*i*,<=*j*) such that 1<=≤<=*i*<=≤<=*j*<=≤<=*n*.
```python def set(x) : if(x not in m) : m[x] = 0 n = int(input()) a = list(map(int, input().split())) m = {} ans, total = 0, 0 for i in range(0, n) : x = a[i]; set(x), set(x - 1), set(x + 1) ans = ans + (i - m[x] - m[x - 1] - m[x + 1]) * x; ans = ans -(total - m[x] * x - m[x - 1] * (x - 1) - m[x + 1] * (x...
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python # -*- coding: utf-8 -*- """ Created on Thu Apr 29 22:39:01 2021 @author: Corey.Smith """ s = input() i=0 for l in s: i = [i,i+1][l.upper()==l] print([s.lower(),s.upper()][i>len(s)/2]) ```
MatrixStudio/Codeforces-Python-Submissions
Mike is trying rock climbing but he is awful at it. There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=&lt;<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ...,...
```python n = int(input()) a = [int(x) for x in input().split()] val = [] mv = 0 for i in range(1,n): mv = max(mv,a[i]-a[i-1]) z = 1000 for i in range(1,n-1): z = min(z, a[i+1]-a[i-1]) if z <= mv: print(mv) else: print(z) ```
MatrixStudio/Codeforces-Python-Submissions
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$...
```python n = int(input()) a = [] s = input().split() ans = 0 for i in range(n): if set(s[i]) not in a: a.append(set(s[i])) ans += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* cities and *n*<=-<=1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings...
```python from collections import defaultdict def solve(): n = int(input()) graph = defaultdict(list) for _ in range(n-1): x,y = map(int, input().split()) graph[x].append(y) graph[y].append(x) dep = defaultdict(int) dep[0]=-1 sum=0 total=0 ...
MatrixStudio/Codeforces-Python-Submissions
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choos...
```python n,m,k=map(int,input().split()) l = [[0 for _ in range(n+2)] for _ in range(m+2)]#baohuquan temp=1 if k<=3: print(0) else: for c in range(1,k+1): j,i=map(int,input().split()) l[i][j]=1 if l[i][j+1]+l[i+1][j]+l[i+1][j+1]==3 or l[i][j+1]+l[i-1][j]+l[i-1][j+1]==3 or l[i][j...
MatrixStudio/Codeforces-Python-Submissions
The cows have just learned what a primitive root is! Given a prime *p*, a primitive root is an integer *x* (1<=≤<=*x*<=&lt;<=*p*) such that none of integers *x*<=-<=1,<=*x*2<=-<=1,<=...,<=*x**p*<=-<=2<=-<=1 are divisible by *p*, but *x**p*<=-<=1<=-<=1 is. Unfortunately, computing primitive roots can be time consumin...
```python def power(x, y, p): result = 1 x = x % p while y > 0: if y % 2 == 1: result = (result * x) % p y = y // 2 x = (x * x) % p return result def phi(n): result = n p = 2 while p * p <= n: if n % p == 0: while n % p ...
MatrixStudio/Codeforces-Python-Submissions
After waking up at *hh*:*mm*, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is *H* points, moreover each minute without food increases his hunger by *D* points. At any time Andrew can visit the store where tasty buns are...
```python import math first = input().split(" ") hh = int(first[0]) mm = int(first[1]) t = hh * 60 + mm disc = 20 * 60 second = input().split(" ") h = int(second[0]) d = int(second[1]) c = int(second[2]) n = int(second[3]) if(t > disc): print(0.8 * math.ceil(h/float(n)) * c) else: wait = 0.8 *...
MatrixStudio/Codeforces-Python-Submissions
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a set of digits, your task is to find the maximum integer that you can mak...
```python import decimal from errno import ETIMEDOUT import heapq as hq import os import sys from collections import Counter as ctr, deque as dq etd=dq() from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file....
MatrixStudio/Codeforces-Python-Submissions
There are *n* pearls in a row. Let's enumerate them with integers from 1 to *n* from the left to the right. The pearl number *i* has the type *a**i*. Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type. Split the row of the pearls to the maximal ...
```python #!/usr/bin/python3 n = int(input()) a = [int(x) for x in input().split()] r = [] s = set() l = 0 for i, x in enumerate(a): if x in s: r.append([l + 1, i + 1]) l = i + 1 s = set() else: s.add(x) if l == 0: print(-1) else: if s: r[-1][1] = n print(len(r)) print('\n'.join('{0} {...
MatrixStudio/Codeforces-Python-Submissions
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a*...
```python # Read the number of elements in the sequence n = int(input()) # Read the sequence of elements elements = list(map(int, input().split())) # Count the frequency of each element frequency = {} for num in elements: frequency[num] = frequency.get(num, 0) + 1 # Initialize the dp array dp = [0] *...
MatrixStudio/Codeforces-Python-Submissions
One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current ...
```python n = [int(x) for x in input().split()] p = [int(x) for x in input().split()] i = 0 for j in range(len(p) - 1): num = p[n[1]-1] p.append(num) p.pop(0) i = i+1 if len(set(p)) == 1: print(i) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is inc...
```python n = int(input()) flag = False for i in range(1, n + 1): tempNum = n * i + i for j in range(2, int(tempNum / 2) + 1): if tempNum % j == 0: flag = True break if flag == True: print(i) break ```
MatrixStudio/Codeforces-Python-Submissions
Array of integers is unimodal, if: - it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arra...
```python arr=[] n=int(input("Number of elements in array:")) for i in range(0,n): ele=int(input()) arr.append(ele) def f(m,n,flag): if flag==1: return m<n elif flag==2: return m==n else: return m>n def is_unimodal(a, lst): flag=1 for i in range(1,n): if f(lst[i-1], ls...
MatrixStudio/Codeforces-Python-Submissions
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
```python n=int(input()) f=list(map(int,input().split())) s=k=0 while k<n and len(f)!=0: k+=max(f) f.remove(max(f)) s+=1 if len(f)==0: print(-1) else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
```python a = input() b = input() aux = "" if (len(a)%2 == 0): for i in range(0,len(a),2): if a[i] == b[i]: aux = aux + "0" else: aux = aux + "1" if (a[i+1] == b[i+1]): aux = aux+"0" else: aux = aux+"1" else: if (a[0] == b[0]): aux = aux+"0" else: ...
MatrixStudio/Codeforces-Python-Submissions
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts *k* days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp k...
```python ## 808B n,k=map(int,input().split()) l=list(map(int,input().split())) ans=0 if k>=n: ans=sum(l)/(n-k+1) print(ans) else: i=n-k+1 j=[l[i] for i in range(n-k+1)] s=sum(j) while i<n: j.pop(0) j.insert(i,l[i]) i+=1 # print(j) s+=sum(j) print(s/(n-k+1)) ```
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python n, m, a = [int(input()) for i in range(3)] n1 = (n // a) + 1 m1 = (m // a ) + 1 print(n1 * m1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a permutation of integers from 1 to *n*. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from *l* to *r*. All segments are equiprobable. 1. Let *k*<==<=*r*<=-<=*l*<=+<=1, i.e...
```python MAX = 500005 n = int(input()) v = [0]*MAX AIB = [0]*MAX AIB2 = [0]*MAX def add1(pos, val): global AIB while pos < MAX: AIB[pos] += val pos += pos & (-pos) def add2(pos, val): global AIB2 while pos < MAX: AIB2[pos] += val pos += pos & (-pos) ...
MatrixStudio/Codeforces-Python-Submissions
You are given a non-negative integer *n*, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes. Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a no...
```python s = "00" + input() l = len(s) for i in range(l): for j in range(i + 1, l): for k in range(j + 1, l): ans = s[i] + s[j] + s[k] if (int(ans) % 8 == 0): print("YES") print(int(ans)) exit() print("NO") ```
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 o...
```python n, m = map(int, input().split()) flats = {} for i in range(m): flat, floor = map(int, input().split()) if floor not in flats.keys(): flats[floor] = [] flats[floor].append(flat) floors = sorted(flats.keys()) def check(): for i in range(1, len(floors)): a,b=min(flats[floors...
MatrixStudio/Codeforces-Python-Submissions
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
```python i = input() i = int(i) s = input() if s[0] == 'S' and s[i-1] == 'F': print ('YES') else: print ('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in f...
```python from queue import Queue import numpy as np import pandas as pd from bisect import bisect_left from sortedcontainers import SortedSet def ColorfulFields(): n, m, k, t = map(int, input().split()) wastes = SortedSet() for i in range(k): x, y = map(int, input().split()) w...
MatrixStudio/Codeforces-Python-Submissions
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds *n* is defined....
```python using namespace std; int main() { int n; while(cin>>n) { int p1=0,p2=0; while(n--) { int P1,P2; cin>>P1>>P2; p1+=(P1>P2); p2+=(P2>P1); } if(p1>p2) cout<<"Mishka"<<endl; else ...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors. Polycaprus calculated that the optimal celling price for such scissors would be *p* bourles. However, ...
```python p,d=input().split() s=p[::-1] z="" x="" for i in range(len(d)): if s[i]=="9": z=z+"0" x=x+z else: b=int("1"+s[i])-9 if int(str(b)+x)<=int(d): x=x+str(b) z=z+str(b) s=str(int(p)-int(b))[::-1] else: br...
MatrixStudio/Codeforces-Python-Submissions
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: - In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to ze...
```python i=input;i();print(len(set(i().split())-{'0'})) ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has *n* cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a c...
```python s=input() c=0 for i in range(len(s)): if s[i] in ['a','e','i','o','u']: c+=1 if s[i].isdigit(): if int(s[i])%2!=0: c+=1 print (c) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and his friends went to a picnic. The guys had *n* soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the *i*-th bottle is from brand *a**i*, besides, you can use it to open other bottles of brand *b**i*. You can use...
```python # http://codeforces.com/problemset/problem/315/A get=lambda:list(map(int,input().split())) n=int(input()) a=[] b=[] for i in range (n): x,y=get() a.append(x) b.append(y) d=n for i in range(n): for j in range(n): if a[i]==b[j] and i!=j: d-=1 break...
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote...
```python n = int(input()) ratings = [(i,int(x)) for x in enumerate(input().split())] out = [0]*n ratings = sorted(ratings, key = lambda x: x[0], reverse=True) pos = 0 score = 0 for r in rating: r_score = r[1] if r_score <> score: score = r_score pos +=1 out[r[0]] = pos print (' ...
MatrixStudio/Codeforces-Python-Submissions
You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number...
```python n, k, m = [int(z) for z in input().split()] a = [int(z) for z in input().split()] d = dict() for i in range(n): mod = a[i] % m if mod in d: d[mod].append(a[i]) else: d[mod] = [a[i]] for elem in d: if len(d[elem]) >= k: print("Yes") for i in range(k):...