source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
In the school computer room there are *n* servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are *m**i* tasks assigned to the *i*-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression *m**a*<=-<=*m**b*, where *a* is the most loaded server and *b* is the least loaded one. In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another. Write a program to find the minimum number of seconds needed to balance the load of servers.
```python num_servers=int(input()) loads=list(map(int,input().split())) loads.sort() lp=0 rp=len(loads)-1 count=0 while lp<=rp: count+=(loads[rp]-loads[lp])//2 lp+=1 rp-=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.
```python num = input() if any(char in num for char in "12356890"): print("NO") else: if len(num) == 7 or len(num) == 4: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic. How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
```python k = int(input()) l = int(input()) m = int(input()) n = int(input()) d = int(input()) l1 = set([i for i in range(0,d,k)]) l2 = set([i for i in range(0,d,l)]) l3 = set([i for i in range(0,d,m)]) l4 = set([i for i in range(0,d,n)]) l1.union(l2) l1.union(l3) l1.union(l4) print(len(l1)) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to *n*. It is known that during the day *q* tasks will come, the *i*-th of them is characterized with three integers: *t**i* — the moment in seconds in which the task will come, *k**i* — the number of servers needed to perform it, and *d**i* — the time needed to perform this task in seconds. All *t**i* are distinct. To perform the *i*-th task you need *k**i* servers which are unoccupied in the second *t**i*. After the servers begin to perform the task, each of them will be busy over the next *d**i* seconds. Thus, they will be busy in seconds *t**i*,<=*t**i*<=+<=1,<=...,<=*t**i*<=+<=*d**i*<=-<=1. For performing the task, *k**i* servers with the smallest ids will be chosen from all the unoccupied servers. If in the second *t**i* there are not enough unoccupied servers, the task is ignored. Write the program that determines which tasks will be performed and which will be ignored.
```python rlist = lambda: list(map(int, input().split())) N, Q = rlist() free = [0] * N for qi in range(Q): t, k, d = rlist() # t : time when job comes # k : number of servers # d : duration [t...t+d-1] cand = [] for i in range(N): if free[i] <= t: cand.append(i) if len(cand) < k: print(-1) continue s = 0 for j in range(k): working = cand[j] s += working + 1 free[working] = t + d print(s) ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* points on the straight line — the positions (*x*-coordinates) of the cities and *m* points on the same line — the positions (*x*-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than *r* from this tower. Your task is to find minimal *r* that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than *r*. If *r*<==<=0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than *r* from this tower.
```python import sys import math # Fast input # Fast output def print(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') file = kwargs.get('file', sys.stdout) flush = kwargs.get('flush', False) output = sep.join(map(str, args)) + end file.write(output) if flush: file.flush() def listin(): l=list(map(int,input().split())) return l def two(): n,m=map(int,input().split()) return n,m def three(): n,m,p=map(int,input().split()) return n,m,p def binarySearch(arr, x): l=0 r=len(arr)-1 while l <= r: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return l n,k=two() l1=listin() l2=listin() x=[] for i in l1: x.append(binarySearch(l2,i)) m=0 j=0 for i in x: f=float('inf') if i-1>=0: f=min(l1[j]-l2[i-1],f) if i<k: f=min(l2[i]-l1[j],f) m=max(f,m) j+=1 print(m) ```
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 a = 0 b = 0 l = 0 s = "" n = int(input()) for i in range (n): t = input() s = s + t a = a + t.count("A") b = b + t.count("B") l = l + len(t) if a + b == l and a != b: if b > a: print("B") else: print("A") else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus is a system administrator. There are two servers under his strict guidance — *a* and *b*. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers *x* and *y* (*x*<=+<=*y*<==<=10; *x*,<=*y*<=≥<=0). These numbers mean that *x* packets successfully reached the corresponding server through the network and *y* packets were lost. Today Polycarpus has performed overall *n* ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
```python # import sys # sys.stdin=open("test11.in","r") # sys.stdout=open("test11.out","w") n=int(input()) a=0 b=0 for i in range(n): l=list(map(int,input().split())) if(l[1]>=5): if(l[0]==1): a=1 elif(l[0]==2): b=1 else: if(l[0]==1): a=1 elif(l[0]==2): b=1 if(a==1): print("LIVE") else: print("DEAD") if(b==1): print("LIVE") else: print("DEAD") ```
MatrixStudio/Codeforces-Python-Submissions
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this. In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
```python s=input() n=input() if s==n: print(0) exit() m=['','a','b','c','d','e','f','g','h'] for i in range(1,len(m)): if s[0]==m[i]: x=i if n[0]==m[i]: x2=i y=int(s[1]) y2=int(n[1]) M=[] b='' xod=0 while True: if x>x2: x-=1 b+='L' if x<x2: x+=1 b+='R' if y>y2: y-=1 b+='D' if y<y2: y+=1 b+='U' xod+=1 M.append(b) b='' if x==x2 and y==y2: break print(xod) for i in range(len(M)): print(M[i]) ```
MatrixStudio/Codeforces-Python-Submissions
You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands. Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand. Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.
```python string=input() la=list(map(int,string.split())) l=la[0] r=la[1] a=la[2] while(a>0): if r<l: r+=1 else: l+=1 a-=1 if r<l: print(2*r) else: print(2*l) ```
MatrixStudio/Codeforces-Python-Submissions
Unlucky year in Berland is such a year that its number *n* can be represented as *n*<==<=*x**a*<=+<=*y**b*, where *a* and *b* are non-negative integer numbers. For example, if *x*<==<=2 and *y*<==<=3 then the years 4 and 17 are unlucky (4<==<=20<=+<=31, 17<==<=23<=+<=32<==<=24<=+<=30) and year 18 isn't unlucky as there is no such representation for it. Such interval of years that there are no unlucky years in it is called The Golden Age. You should write a program which will find maximum length of The Golden Age which starts no earlier than the year *l* and ends no later than the year *r*. If all years in the interval [*l*,<=*r*] are unlucky then the answer is 0.
```python x, y, l, r = map(int, input().split()) a=1 b=1 arr=[] ans=0 while a<=r*x: b=1 while b<=r*y: arr.append(a+b) b=b*y a=a*x arr.append(l-1) arr.append(r+1) arr.sort() for z in range(1, len(arr)) : if arr[z]<=r+1 : if arr[z]-arr[z-1]-1>ans : ans=arr[z]-arr[z-1]-1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Buses run between the cities *A* and *B*, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city *A* departs every *a* minutes and arrives to the city *B* in a *t**a* minutes, and a bus from the city *B* departs every *b* minutes and arrives to the city *A* in a *t**b* minutes. The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish. You know the time when Simion departed from the city *A* to the city *B*. Calculate the number of buses Simion will meet to be sure in his counting.
```python import math a, ta = map(int, input().split()) b, tb = map(int, input().split()) h, m = map(int, input().split(':')) x=60*h+m print(min(math.floor(1139/b), math.floor((x+ta-300-1)/b)) - max(0, math.ceil((x-tb-300+1)/b)) + 1) ```
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 t = int(input()) L = set([int(x) for x in input().split()]) for i in range(1, 3050): if i not in L: print(i) break ```
MatrixStudio/Codeforces-Python-Submissions
Yaroslav has an array, consisting of (2·*n*<=-<=1) integers. In a single operation Yaroslav can change the sign of exactly *n* elements in the array. In other words, in one operation Yaroslav can select exactly *n* array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav.
```python n = int(input()) a = list(map(int, input().split())) b = 0 for i in a: if i < 0: b += 1 b = min(b, b % n) c = sorted(map(abs, a)) print(sum(a[2 * n - 1 - b:]) - sum(a[:2 * n - 1 - b])) ```
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**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.
```python from collections import Counter n = input() counts = Counter(map(int, input().split())) score = 0 def count_total_value(i): plus = counts.get(i + 1, 0) * (i + 1) minus = counts.get(i - 1, 0) * (i - 1) val = counts.get(i) * i - (plus + minus) return val while counts: commons = counts.most_common() counts_list = list(sorted(commons, key=lambda i: -count_total_value(i[0]))) ((value, _________), *________) = counts_list try: counts.pop(value + 1) except: pass try: counts.pop(value - 1) except: pass score += value counts[value] -= 1 if not counts[value]: counts.pop(value) print(score) ```
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
```python total = 0 num = int(input()) if num%2 == 0: print(int(num/2)) print('2 '*(int(num/2))) else: print(int(num//2)) print('2 '*(int(num/2)-1)+'3') ```
MatrixStudio/Codeforces-Python-Submissions
Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
```python n = int(input()) arr = [int(x) for x in input().split()] count5 = arr.count(5) count0 = arr.count(0) num = int(count5/9) number = "5"*(num*9) + "0"*(count0) if(int(number) == 0): print(0) else: print(number) ```
MatrixStudio/Codeforces-Python-Submissions
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. During the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase English letters, string *s* is lexicographically smaller than string *t*. Vitaly wondered if there is such string that is lexicographically larger than string *s* and at the same is lexicographically smaller than string *t*. This string should also consist of lowercase English letters and have the length equal to the lengths of strings *s* and *t*. Let's help Vitaly solve this easy problem!
```python """ Link: https://codeforces.com/contest/518/problem/A Time complexity: O(n) Space complexity: O(1) """ def gen_next_string(): first_text = input() second_text = input() result = '' carry = 1 for i in range(len(first_text) - 1, -1, -1): if carry: if first_text[i] == 'z': result += 'a' else: result += chr(ord(first_text[i]) + 1) carry = 0 else: result = first_text[:i + 1] + result break if result >= second_text: return 'No such string' else: return result if __name__ == '__main__': print(gen_next_string()) ```
MatrixStudio/Codeforces-Python-Submissions
Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries: - Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.
```python n,m=[int(i) for i in input().split()] a=[int(i) for i in input().split()] e=a.count(1) f=a.count(-1) for i in range(m): b,c=[int(i) for i in input().split()] z=(c-b)+1 if(z%2!=0): print(0) else: if((e+f)>=z): print(1) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of *n* playing cards. Let's describe the house they want to make: 1. The house consists of some non-zero number of floors. 1. Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card. 1. Each floor besides for the lowest one should contain less rooms than the floor below. Please note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more. While bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of *n* cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using exactly *n* cards.
```python import sys import time import math from collections import defaultdict from functools import lru_cache INF = 10 ** 18 + 3 EPS = 1e-10 MAX_CACHE = 10 ** 12 def time_it(function, output=sys.stderr): def wrapped(*args, **kwargs): start = time.time() res = function(*args, **kwargs) elapsed_time = time.time() - start print('"%s" took %f ms' % (function.__name__, elapsed_time * 1000), file=output) return res return wrapped @lru_cache(MAX_CACHE) def find_possible_heights(n): res = 0 curr_level = 1 while True: if n % 3 == 2 and n > curr_level * 3 - 4: res += 1 n -= curr_level * 3 - 1 curr_level += 1 if n <= 0: return res @time_it def main(): n = int(input()) print(find_possible_heights(n)) def set_input(file): global input input = lambda: file.readline().strip() def set_output(file): global print local_print = print def print(*args, **kwargs): kwargs["file"] = kwargs.get("file", file) return local_print(*args, **kwargs) if __name__ == '__main__': set_input(open("input.txt", "r") if "MINE" in sys.argv else open("input.txt", "w")) set_output(sys.stdout) main() ```
MatrixStudio/Codeforces-Python-Submissions
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform *n* operations. Each operation is one of the following: 1. Add the integer *x**i* to the first *a**i* elements of the sequence. 1. Append an integer *k**i* to the end of the sequence. (And hence the size of the sequence increases by 1) 1. Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!
```python 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 perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass n = int(input()) val = [0] * (n + 1) add = [0] * (n + 1) ptr = 1 sum = 0 for i in range(n): l = [int(x) for x in input().split()] if l[0] == 1: a, x = l[1:] add[a - 1] += x sum += a * x elif l[0] == 2: k = l[1] val[ptr] = k sum += k ptr += 1 else: ptr -= 1 sum -= val[ptr] sum -= add[ptr] add[ptr - 1] += add[ptr] add[ptr] = 0 print('%.6f'%(sum / ptr)) # print(*val) # print(*add) # print() endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ```
MatrixStudio/Codeforces-Python-Submissions
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most *d* centimeters. Captain Bob has *n* soldiers in his detachment. Their heights are *a*1,<=*a*2,<=...,<=*a**n* centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1,<=2) and (2,<=1) should be regarded as different.
```python n,d=map(int,input().split()) a=list(map(int,input().split())) a.sort() c=0 for i in range(0,n): for j in range(i+1,n): if a[j]-a[i]<=d: c+=1 print(2*c) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python a = input().split(" ") num1 = int(a[0]) num2 = int(a[1]) b = (num1 * num2) // 2 print(b) ```
MatrixStudio/Codeforces-Python-Submissions
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find the maximum possible least common multiple of these three integers?
```python #!/usr/bin/env python3 import collections, itertools, functools, math, fractions import operator def lcm(a, b): return (a*b)//fractions.gcd(a, b) def solve(n): if n <= 2: return n if n%2 == 1: return lcm(n, lcm(n-1, n-2)) offset = 100 if n-offset < 0: offset = n r = 1 for i in range(n, n-offset, -1): for j in range(i, n-offset, -1): for k in range(j, n-offset, -1): r = max(r, lcm(i, lcm(j, k))) return r if __name__ == '__main__': print(solve(int(input()))) ```
MatrixStudio/Codeforces-Python-Submissions
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not. You're given a number. Determine if it is a magic number or not.
```python case = input() count =0 flag=0 for i in range(len(case)): if case[i]=='4': count+=1 bool=1 if count>2: print("NO") flag=1 break elif case[i]=='1': count = 0 bool=0 elif case[i]!= '1' and case[i]!='4': print("NO") flag=1 break if flag==0: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have *n* layers. The first layer is hate, second one is love, third one is hate and so on... For example if *n*<==<=1, then his feeling is "I hate it" or if *n*<==<=2 it's "I hate that I love it", and if *n*<==<=3 it's "I hate that I love that I hate it" and so on. Please help Dr. Banner.
```python x=int(input()) c='I hate' for i in range(x-1): c+=' that' if i%2==0:c+=' I love' else:c+=' I hate' print(c+' it') ```
MatrixStudio/Codeforces-Python-Submissions
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
```python a=input() b=input() a=list(a) b=list(b) first=-1 second=-1 lmn=0 for i in range(len(a)): if a[i]!=b[i]: if first==-1: first=i else: second=i a[first],a[second]=a[second],a[first] if a==b: lmn=1 print("YES ") break else: print("NO") break if lmn==0: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular *a* mm <=×<= *b* mm sheet of paper (*a*<=&gt;<=*b*). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part. After making a paper ship from the square piece, Vasya looked on the remaining (*a*<=-<=*b*) mm <=×<= *b* mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop. Can you determine how many ships Vasya will make during the lesson?
```python a,b=[int(i) for i in input().split()] k=1 while a!=b: if a>b: a=a-b else: b=b-a k=k+1 print(k) ```
MatrixStudio/Codeforces-Python-Submissions
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1. The potato pie is located in the *n*-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F. Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door. Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*. Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
```python from collections import defaultdict input() s, keys, n = input().lower(), defaultdict(int), 0 for i, door in zip(s[::2], s[1::2]): keys[i] += 1 if keys[door]: keys[door] -= 1 else: n += 1 print(n) ```
MatrixStudio/Codeforces-Python-Submissions
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check. Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions: - the password length is at least 5 characters; - the password contains at least one large English letter; - the password contains at least one small English letter; - the password contains at least one digit. You are given a password. Please implement the automatic check of its complexity for company Q.
```python from fractions import gcd # from datetime import date, timedelta from heapq import* import math from collections import defaultdict, Counter, deque import sys from bisect import * import itertools import copy sys.setrecursionlimit(10 ** 7) MOD = 10 ** 9 + 7 # input = sys.stdin.readline def main(): s = input() if len(s) >= 5: f,ff,fff = False,False,False for i in range(len(s)): if s[i].isnumeric(): f = True elif s[i].islower(): ff = True elif s[i].isupper(): fff = True if f and ff and fff: print("Correct") else: print("Too weak") if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa. What is the minimum number of cells with value 1 you can get after applying some number of operations?
```python print("_RANDOM_GUESS_1689338437.874004")# 1689338437.874017 ```
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python n,a,b = map(int, input().split()) print (n-a) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
```python def verif (ch,ch1) : for i in range (len(ch)) : if ch[i]!=ch1[c-i] : return 'NO' return 'YES' ch=input() ch1=input() c=len (ch) -1 print(verif(ch,ch1)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
```python n=int((input().split())[0]) m=int((input().split())[1]) l=set() for x in range(n): q=input().split() l=l|set(q) if len(l)==m: print('YES') else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
```python d={"A":[], "B":[], "C":[] } exp1=input() source,arrow,dest=[x for x in exp1] if arrow==">": d[source].append(dest) else: d[dest].append(source) exp2=input() source,arrow,dest=[x for x in exp2] if arrow==">": d[source].append(dest) else: d[dest].append(source) exp3=input() source,arrow,dest=[x for x in exp3] if arrow==">": d[source].append(dest) else: d[dest].append(source) #print(d) for k,v in d.items(): d[k]=len(v) d=sorted(d.items(),key=lambda x:x[1]) print(d) if d[0][1]==0 and d[1][1]==1 and d[2][1]==2: op=d[0][0]+d[1][0]+d[2][0] op=op[::-1] print(op) else: print("Impossible") ```
MatrixStudio/Codeforces-Python-Submissions
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly. An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
```python n = int(input()) mod = 1e9+7 dp = [[0]*4 for i in range(n+1)] dp[0][3] = 1 for i in range(1, n+1): for u in range(4): for v in range(4): if u != v: dp[i][v] = (dp[i][v] + dp[i-1][u]) % mod print(int(dp[n][3])) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python # cook your dish here def can_say_hello(word): target = "hello" i = 0 for char in word: if char == target[i]: i += 1 if i == len(target): return "YES" return "NO" word = input() result = can_say_hello(word) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer *t* Т-prime, if *t* has exactly three distinct positive divisors. You are given an array of *n* positive integers. For each of them determine whether it is Т-prime or not.
```python from math import sqrt n = int(input()) x = list(map(int, input().split())) N = max(x) primes = [i for i in range(N + 1)] primes[1] = 0 i = 2 while i <= N: if primes[i] != 0: j = i + i while j <= N: primes[j] = 0 j = j + i i += 1 primes = [i for i in primes if i != 0] for i in x: if sqrt(i) % 1 != 0: print('NO') else: if sqrt(i) in primes: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored *A*·*B*·*C* hay blocks and stored them in a barn as a rectangular parallelepiped *A* layers high. Each layer had *B* rows and each row had *C* blocks. At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (*A*<=-<=1)<=×<=(*B*<=-<=2)<=×<=(*C*<=-<=2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1<=×<=1<=×<=1 blocks and scattered them around the barn. After the theft Sam counted *n* hay blocks in the barn but he forgot numbers *A*, *B* и *C*. Given number *n*, find the minimally possible and maximally possible number of stolen hay blocks.
```python n = int(input()) x = int(sqrt(n)) while n % x: x -= 1 def f(x, y): return (x + 2) * (y + 2) + (2 * (x + y + 2) * n) // (x * y) print(f(x, n // x), f(1, 1)) ```
MatrixStudio/Codeforces-Python-Submissions
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
```python n=int(input()) a=sorted(list(map(int, input().split()))) b=[] numb=1 flag=True for i in range(1,n): q=1 if a[i]>a[i-1]: if a[i]-a[i-1]>1: flag=False break else: b.append(numb) q=0 numb=1 else: numb+=1 if q==0: b.append(numb) i=len(b)-1 #print(b) if flag: while i>=0 and b[i]!=0: b[i]-=1 if b[i]!=0: if i!=0 and b[i-1]!=0: b[i-1]-=1 else: flag=False print(b) break else: i-=1 if flag: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of *n* sticks and an instrument. Each stick is characterized by its length *l**i*. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed. Sticks with lengths *a*1, *a*2, *a*3 and *a*4 can make a rectangle if the following properties are observed: - *a*1<=≤<=*a*2<=≤<=*a*3<=≤<=*a*4 - *a*1<==<=*a*2 - *a*3<==<=*a*4 A rectangle can be made of sticks with lengths of, for example, 3 3 3 3 or 2 2 4 4. A rectangle cannot be made of, for example, sticks 5 5 5 7. Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4. You have to answer the question — what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?
```python m = {} n = int(input()) data = input().split() for i in data: if -int(i) not in m: m[-int(i)] = 1 else: m[-int(i)] += 1 ant = 0 ans = 0 for i in sorted(m): if m[i] > 1: if ant != 0: ans += ant * i m[i] -= 2 ans += (m[i]//4)*m[i] m[i] %= 4 if(m[i] > 1): if ant == 0: ant = i else: ans += i * ant ant = 0 if(m[i] % 2 == 1 and i+1 in m): m[i+1] += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
```python n=int(input()) a=[int(i) for i in input().split()] print(max(a)+1) ```
MatrixStudio/Codeforces-Python-Submissions
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*. Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end. Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened. You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.
```python # Python program for KMP Algorithm def KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] pat_indices = [0] txt_indices = [0] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 if i < N: pat_indices.append(j) txt_indices.append(i) return pat_indices def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 s = input() n = len(s) pat_indices = KMPSearch(s[:n//3], s) last_ind = pat_indices[n-1] first_word = s[:last_ind+1] middle = s[last_ind+1: n-(last_ind+1)] last_word = s[n-(last_ind+1):] if first_word in middle and first_word == last_word: print(first_word) else: print("Just a legend") ```
MatrixStudio/Codeforces-Python-Submissions
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated. Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
```python n=int(input()) a=list(map(int,input().split())) police,crime=0,0 for i in a: if i!=-1: police+=i else: if police+i>=0: police =police-1 else: crime+=1 print(crime) ```
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 *i*-th letter of her name should be 'O' (uppercase) if *i* is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to *n*. Fibonacci sequence is the sequence *f* where - *f*1<==<=1, - *f*2<==<=1, - *f**n*<==<=*f**n*<=-<=2<=+<=*f**n*<=-<=1 (*n*<=&gt;<=2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return sys.stdin.readline().split() def S(): return input() def main(): n=I() l=[0]*1010 a=1 b=1 l[a]=1 while True: a+=b if a>1000: break l[a]=1 c=a a=b b=c ans='' for x in l[1:n+1]: if x==1: ans+='O' else: ans+='o' return ans # main() print(main()) ```
MatrixStudio/Codeforces-Python-Submissions
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer. Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards. He is allowed to at most once discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number. Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?
```python import bisect import collections import copy import functools import heapq import itertools import math import random import re import sys import time import string from typing import List sys.setrecursionlimit(99999) arr = list(map(int,input().split())) s = sum(arr) cs = collections.Counter(arr) mx = 0 for k,v in cs.items(): if v==2: mx = max(mx,2*k) elif v>2: mx = max(mx,3*k) print(s-mx) ```
MatrixStudio/Codeforces-Python-Submissions
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data points — for each 1<=≤<=*i*<=&lt;<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≤<=1. A range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≤<=*i*<=≤<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≤<=1. Find the length of the longest almost constant range.
```python def solve(A, N): count = [] for i in range(100002): count.append(0) for i in range(N): A[i] = int(A[i]) count[A[0]] += 1 num = 1 L = 0 cnt = 0 for R in range(1, N): if (count[A[R]] == 0): num += 1 while (num > 2): count[A[L]] -= 1 if (count[A[L]] == 0): num -= 1 L += 1 count[A[R]] += 1 cnt = max(cnt, R - L + 1) return cnt N = int(input()) A = input() A = A.split(" ") print(solve(A, N)) ```
MatrixStudio/Codeforces-Python-Submissions
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of *r*1 cm, inner radius of *r*2 cm, (0<=&lt;<=*r*2<=&lt;<=*r*1) made of metal with density *p*1 g/cm3. The second part is an inner disk with radius *r*2 cm, it is made of metal with density *p*2 g/cm3. The disk is nested inside the ring. The Olympic jury decided that *r*1 will take one of possible values of *x*1,<=*x*2,<=...,<=*x**n*. It is up to jury to decide which particular value *r*1 will take. Similarly, the Olympic jury decided that *p*1 will take one of possible value of *y*1,<=*y*2,<=...,<=*y**m*, and *p*2 will take a value from list *z*1,<=*z*2,<=...,<=*z**k*. According to most ancient traditions the ratio between the outer ring mass *m**out* and the inner disk mass *m**in* must equal , where *A*,<=*B* are constants taken from ancient books. Now, to start making medals, the jury needs to take values for *r*1, *p*1, *p*2 and calculate the suitable value of *r*2. The jury wants to choose the value that would maximize radius *r*2. Help the jury find the sought value of *r*2. Value *r*2 doesn't have to be an integer. Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
```python n, *r1_arr = [int(x) for x in input().split()] m, *p1_arr = [int(x) for x in input().split()] k, *p2_arr = [int(x) for x in input().split()] A, B = [int(x) for x in input().split()] r1, p1, p2 = max(r1_arr), max(p1_arr), min(p2_arr) print(((p1 * B * (r1 ** 2)) / (p2 * A + p1 * B)) ** .5) ```
MatrixStudio/Codeforces-Python-Submissions
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length. He asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length.
```python def f(s,k): if len(s)%k == 0: k = len(s)//k for i in range(0,len(s),k): #print(s[i:i+k][::-1], s[i:i+k]) if s[i:i+k][::-1] != s[i:i+k]: return "NO" return "YES" return "NO" print(f(input(),int(input()))) ```
MatrixStudio/Codeforces-Python-Submissions
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations: - Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains. A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains. You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).
```python x = 0 n = int(input()) for i in range(0, n): i += 1 l = str.lower(input()) if (l == "--x" or l == "x--"): x -= 1 elif (l == "++x" or l == "x++"): x += 1 print(x) ```
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven. Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
```python if __name__ == '__main__': x = input().split(' ') number_of_wanted_cakes = int(x[0]) time_needed = int(x[1]) k_cakes = int(x[2]) time_new_oven = int(x[3]) temp_cakes = k_cakes temp_cakes_new_oven = k_cakes counter = 1 time_counter = time_needed while(temp_cakes < number_of_wanted_cakes) : temp_cakes = temp_cakes + k_cakes counter +=1 time_counter = time_counter + time_needed temp_new_oven = time_new_oven temp_timer = 0 temp_cakes_new_oven = 0 check_point = time_needed check_point_1 = time_needed + temp_new_oven tim = 0 for i in range(1000): while temp_cakes_new_oven <number_of_wanted_cakes: if i < check_point_1: if i % check_point == 0: temp_cakes_new_oven = temp_cakes_new_oven + k_cakes tim += time_needed if i == check_point_1: temp_cakes_new_oven = temp_cakes_new_oven + k_cakes tim += time_needed if i > check_point_1: if i-time_new_oven % time_needed== 0: temp_cakes_new_oven = temp_cakes_new_oven + k_cakes tim += time_needed if i % time_needed == 0: temp_cakes_new_oven = temp_cakes_new_oven + k_cakes tim += time_needed if tim > time_counter: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning. You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language. You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
```python n,m=map(int,input().split()) l=[] for i in range(m): lst=list(map(str,input().split())) l.append(lst) res=[] res=list(map(str,input().split())) for i in range(n): for j in range(m): if(l[j][0]==res[i]): len1=len(l[j][0]) len2=len(l[j][1]) if(len1<=len2): res[i]=l[j][0] else: res[i]=l[j][1] print(*res) ```
MatrixStudio/Codeforces-Python-Submissions
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written *n* correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote *m* wrong solutions and for each wrong solution he knows its running time (in seconds). Let's suppose that Valera will set *v* seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most *v* seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, *a* seconds, an inequality 2*a*<=≤<=*v* holds. As a result, Valera decided to set *v* seconds TL, that the following conditions are met: 1. *v* is a positive integer; 1. all correct solutions pass the system testing; 1. at least one correct solution passes the system testing with some "extra" time; 1. all wrong solutions do not pass the system testing; 1. value *v* is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.
```python n, m = map(int, input().split()) correct = list(map(int, input().split())) wrong = list(map(int, input().split())) if min(wrong) <= max(correct) or min(wrong) <= 2 * min(correct): print(-1) else: print(max(2 * min(correct), max(correct))) ```
MatrixStudio/Codeforces-Python-Submissions
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most *d* centimeters. Captain Bob has *n* soldiers in his detachment. Their heights are *a*1,<=*a*2,<=...,<=*a**n* centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1,<=2) and (2,<=1) should be regarded as different.
```python #!/usr/bin/env python # coding=utf-8 ''' Author: Deean Date: 2021-11-05 22:41:04 LastEditTime: 2021-11-05 22:45:34 Description: Reconnaissance FilePath: CF32A.py ''' def func(): n, d = map(int, input().strip().split()) high = list(sorted(map(int, input().strip().split()))) count = 0 for i in range(0, n - 1): for j in range(i + 1, n): if high[j] - high[i] <= d: count += 1 else: break print(2 * count) if __name__ == '__main__': func() ```
MatrixStudio/Codeforces-Python-Submissions
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers *a* and *b* such that *l*<=≤<=*a*<=≤<=*r* and *x*<=≤<=*b*<=≤<=*y* there is a potion with experience *a* and cost *b* in the store (that is, there are (*r*<=-<=*l*<=+<=1)·(*y*<=-<=*x*<=+<=1) potions). Kirill wants to buy a potion which has efficiency *k*. Will he be able to do this?
```python def main(): L, R, X, Y, K = map(int, input().split()) for i in range(L, R + 1): div_, mod_ = divmod(i * K, 1) if mod_ == 0 and X <= div_ <= Y: ans = 'YES' break else: ans = 'NO' print(ans) main() ```
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()) for i in range(n): word = input() if len(word) > 10: print(word[0:1] + str((len(word) - 2)) + word[len(word)-1:len(word)]) else: print(word) ```
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!
```python bruh = input().split() a = int(bruh[0]) b = int(bruh[1]) if a == b: print(a) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has *n* people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
```python R = lambda: map(int, input().split()) n, m = R() p = [0] * n for i in range(m): a, b, c = R() p[a - 1] -= c p[b - 1] += c print(sum(i for i in p if i > 0)) ```
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()) #f=0; #for i in range(1,n): # for j in range(i+1,n): # if((i+j==n)and((i+j)%2==n)): # f=1 #if f==1: #print("YES") #else: #print("NO") if n==2: print("NO") elif n%2==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
```python a = input().lower() b = input().lower() c = 0 h = [] n = [] k = 0 for i in range(len(a)): if a[i] != b[i]: c += 1 if c > 2: k = 1 break h.append(a[i]) n.append(b[i]) h.sort() n.sort() if k == 1: print("NO") else: if h == n: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string *s*. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" "110"); 1. replace "11" with "1" (for example, "110" "10"). Let *val*(*s*) be such a number that *s* is its binary representation. Correct string *a* is less than some other correct string *b* iff *val*(*a*)<=&lt;<=*val*(*b*). Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).
```python x=input();y=input() print('1'+y.count('0')*'0') #author:SK__Shanto__㋛ #code__define__your__smartness ```
MatrixStudio/Codeforces-Python-Submissions
Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she can spend it on reading. Help Luba to determine the minimum number of day when she finishes reading. It is guaranteed that the answer doesn't exceed *n*. Remember that there are 86400 seconds in a day.
```python TIME_IN_A_DAY = 86400 n, t = map(int, input().split()) a = list(map(int, input().split())) for i in range(len(a)): if TIME_IN_A_DAY - a[i] >= t: print(i + 1) break t -= (TIME_IN_A_DAY - a[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Petya and Vasya are playing a game. Petya's got *n* non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to *n* from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position *s*. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position *p*1, the glass from the second position to position *p*2 and so on. That is, a glass goes from position *i* to position *p**i*. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in. After all shuffling operations Petya shows Vasya that the ball has moved to position *t*. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position *s* to position *t*.
```python n,s,t=map(int,input().split()) x=[int(q) for q in input().split()] if s==t: print(0) else: s-=1 t-=1 ans=0 f=False for i in range(len(x)): if x[i]-1==t: print(ans) f=True break elif x[i]-1==s and i!=0: print(-1) break else: ans+=1 ```
MatrixStudio/Codeforces-Python-Submissions
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=&lt;<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1). During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button (<=+<=) instead of division button (÷) and got sum of numerator and denominator that was equal to *n* instead of the expected decimal notation. Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction such that sum of its numerator and denominator equals *n*. Help Petya deal with this problem.
```python n=int(input()) print(1,n-1) ```
MatrixStudio/Codeforces-Python-Submissions
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$. Games in the shop are ordered from left to right, Maxim tries to buy every game in that order. When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop. Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game. For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 &gt; a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$. Your task is to get the number of games Maxim will buy.
```python n , m = map(int,input().split()) costs = list(map(int,input().split())) bills = list(map(int,input().split())) pos = 0 cnt = 0 for i in range(n): if bills[pos] >= costs[i]: pos += 1 cnt +=1 if pos == m : break print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly. An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
```python def main(): n = int(input()) M = 1000000007 zD = 1 zABC = 0 for i in range(1, n + 1): nzD = (zABC * 3) % M nzABC = (zABC * 2 + zD) % M zD = nzD zABC = nzABC print(zD) main() ```
MatrixStudio/Codeforces-Python-Submissions
Anton likes to play chess, and so does his friend Danik. Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
```python n=int(input()) s=input() a=s.count('A') b=s.count('D') if(b>a):print('Danik') else:print('Anton') ```
MatrixStudio/Codeforces-Python-Submissions
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the *n* coders on the meeting said: 'I know for sure that either *x* or *y* did it!' The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least *p* of *n* coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects? Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.
```python import itertools n, p = tuple(map(int, str.split(input()))) c = [0] * n for _ in range(n): for i in tuple(map(int, str.split(input()))): c[i - 1] += 1 count = 0 for i, j in itertools.combinations(range(n), 2): if c[i] + c[j] >= p: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length. The output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th character of *s*1 and the *i*-th character of *s*2. For example, *f*("ab", "ba") = "aa", and *f*("nzwzl", "zizez") = "niwel". You found two strings *x* and *y* of the same length and consisting of only lowercase English letters. Find any string *z* such that *f*(*x*,<=*z*)<==<=*y*, or print -1 if no such string *z* exists.
```python x = input() y = input() z = '' st = False for i in range(len(x)): if x[i] < y[i]: st = True break elif x[i] >= y[i]: z += y[i] if not st: print(z) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, the chessboard is a square-checkered board with the squares arranged in a 8<=×<=8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke. Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements. It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
```python l,l2,count=[],[],0 b,w= 'BBBBBBBB', 'WWWWWWWW' for _ in range(8): l.append(input()) for i in range(8): if l[i] == b: count+=1 l[i]= w for i in range(8): c = [x[i] for x in l] l2.append(c) for col in l2: if 'B' in col: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
An *n*<=×<=*n* table *a* is defined as follows: - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. These conditions define all the values in the table. You are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.
```python import huy n = int(input()) print(huy.comb(n*2-2,n-1)) ```
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 n, m = map(int, input().split()) l=list(map(int,input().split())) sl=sorted(l) s=0 for i in range(m): if sl[i]<0: s-=sl[i] print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element *n*. Then he has to perform certain operations on this list. In each operation Sam must remove any element *x*, such that *x*<=&gt;<=1, from the list and insert at the same position , , sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range *l* to *r* (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?
```python def level(n): if n <= 1: return 1 return level(n // 2) + 1 def length(level_n): return 2 ** level_n - 1 def operation(lst): while max(lst) > 1: for i in range(len(lst)): if lst[i] > 1: x = lst[i] lst[i:i + 1] = [x // 2, x % 2] def check(index, lst, lv): for i in range(1, lv): n = 2 ** i if index % n == n/2: return lst[i-1] return lst[-1] n, l, r = map(int, input().split()) list1 = [n] operation(list1) count = 0 for i in range(l, r+1): count += check(i, list1, level(n)) print(count) ```
MatrixStudio/Codeforces-Python-Submissions
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* people living in it and the room can accommodate *q**i* people in total (*p**i*<=≤<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.
```python n=int(input()) c=0 for i in range(n): a=list(map(int, input().split())) if a[1]-a[0] >= 2: c+=1 print(c) ```
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 a, b = map(int, input().split()) q = 0 for _ in range(a): c,d = input().split() d = int(d) if c == "+": b = b+d else: if b-d < 0: b = b q += 1 else: b = b-d print(b,q) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials. He considers a polynomial valid if its degree is *n* and its coefficients are integers not exceeding *k* by the absolute value. More formally: Let *a*0,<=*a*1,<=...,<=*a**n* denote the coefficients, so . Then, a polynomial *P*(*x*) is valid if all the following conditions are satisfied: - *a**i* is integer for every *i*; - |*a**i*|<=≤<=*k* for every *i*; - *a**n*<=≠<=0. Limak has recently got a valid polynomial *P* with coefficients *a*0,<=*a*1,<=*a*2,<=...,<=*a**n*. He noticed that *P*(2)<=≠<=0 and he wants to change it. He is going to change one coefficient to get a valid polynomial *Q* of degree *n* that *Q*(2)<==<=0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.
```python __author__ = 'JohnHook' n, k = list(map(int, input().split())) v = list(map(int, input().split())) sum = 0 for i in range(n + 1): v[i] *= 2 ** i sum += v[i] ans = 0 for i in range(n + 1): if (sum - v[i]) % 2 ** i == 0 and abs((sum - v[i]) / 2 ** i) <= k and (i == n and abs((sum - v[i]) / 2 ** i) != 0): ans += 1 print(ans) ```
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 your help to distribute his free days between instruments so that he can achieve his goal.
```python N, K = map(int, input().split()) A = [(i+1, int(x)) for i, x in enumerate(input().split())] A.sort(key = lambda t: t[1]) answer = [] for t in A: if t[1] > K: break answer.append(t[0]) K -= t[1] print(len(answer)) print(*answer) ```
MatrixStudio/Codeforces-Python-Submissions
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
```python def minimum_horseshoes_to_buy(colors): distinct_colors = len(set(colors)) return max(0, 4 - distinct_colors) # Read input colors = list(map(int, input().split())) # Calculate the minimum number of horseshoes to buy and print the result print(minimum_horseshoes_to_buy(colors)) ```
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 bx=int(input().split()[1]) x=list(map(int,input().split())) by=int(input().split()[1]) y=list(map(int,input().split())) X=Y=0 for xi in x: X=X*bx+xi for yi in y: Y=Y*by+yi if(X>Y): print(">") elif(X<Y): print("<") else: print("=") ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) is coprime, then the pair (*a*,<=*c*) is coprime. You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (*a*,<=*b*,<=*c*), for which the statement is false, and the numbers meet the condition *l*<=≤<=*a*<=&lt;<=*b*<=&lt;<=*c*<=≤<=*r*. More specifically, you need to find three numbers (*a*,<=*b*,<=*c*), such that *l*<=≤<=*a*<=&lt;<=*b*<=&lt;<=*c*<=≤<=*r*, pairs (*a*,<=*b*) and (*b*,<=*c*) are coprime, and pair (*a*,<=*c*) is not coprime.
```python l,r=input().split(" ") l,r=int(l),int(r) if (l % 2 != 0): l+=1 if (l + 2 > r): print(-1); else: print(l,l+1,l+2) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty. For example: - by applying a move to the string "where", the result is the string "here", - by applying a move to the string "a", the result is an empty string "". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings. Write a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.
```python import sys s=input() t=input() if s == t: print(0) sys.exit(0) a=min(len(s),len(t)) for i in range(a): if s[-a:] != t[-a:]: break i-=1 print(len(s)+len(t)-i*2) ```
MatrixStudio/Codeforces-Python-Submissions
Giga Tower is the tallest and deepest building in Cyberland. There are 17<=777<=777<=777 floors, numbered from <=-<=8<=888<=888<=888 to 8<=888<=888<=888. In particular, there is floor 0 between floor <=-<=1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view. In Cyberland, it is believed that the number "8" is a lucky number (that's why Giga Tower has 8<=888<=888<=888 floors above the ground), and, an integer is lucky, if and only if its decimal notation contains at least one digit "8". For example, 8,<=<=-<=180,<=808 are all lucky while 42,<=<=-<=10 are not. In the Giga Tower, if you write code at a floor with lucky floor number, good luck will always be with you (Well, this round is #278, also lucky, huh?). Tourist Henry goes to the tower to seek good luck. Now he is at the floor numbered *a*. He wants to find the minimum positive integer *b*, such that, if he walks *b* floors higher, he will arrive at a floor with a lucky number.
```python def m(): n = eval(input()); b = 1; n+=1 while True: if "8" in str(n): print(b) ; break else: n+=1; b+=1 m() ```
MatrixStudio/Codeforces-Python-Submissions
You've got an array *a*, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a minimal by inclusion segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such, that among numbers *a**l*,<= *a**l*<=+<=1,<= ...,<= *a**r* there are exactly *k* distinct numbers. Segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*; *l*,<=*r* are integers) of length *m*<==<=*r*<=-<=*l*<=+<=1, satisfying the given property, is called minimal by inclusion, if there is no segment [*x*,<=*y*] satisfying the property and less then *m* in length, such that 1<=≤<=*l*<=≤<=*x*<=≤<=*y*<=≤<=*r*<=≤<=*n*. Note that the segment [*l*,<=*r*] doesn't have to be minimal in length among all segments, satisfying the given property.
```python n, k = map(int,input().split()) ls = list(map(int, input().split())) cnt = [0 for _ in range(100005)] i = 0 j = 0 count = 0 found = False while i < n: cnt[ls[i]] += 1 if cnt[ls[i]] == 1: count += 1 i += 1 if count == k: found = True break while count == k: cnt[ls[j]] -= 1 if cnt[ls[j]] == 0: count -= 1 j += 1 if found: print(j, i) else: print(-1,-1) ```
MatrixStudio/Codeforces-Python-Submissions
— I... I survived. — Welcome home, Chtholly. — I kept my promise... — I made it... I really made it! After several days of fighting, Chtholly Nota Seniorious miraculously returned from the fierce battle. As promised, Willem is now baking butter cake for her. However, although Willem is skilled in making dessert, he rarely bakes butter cake. This time, Willem made a big mistake — he accidentally broke the oven! Fortunately, Chtholly decided to help him. Willem puts *n* cakes on a roll, cakes are numbered from 1 to *n*, the *i*-th cake needs *a**i* seconds of baking. Willem needs Chtholly to do *m* operations to bake the cakes. Operation 1: 1 *l* *r* *x* Willem asks Chtholly to check each cake in the range [*l*,<=*r*], if the cake needs to be baked for more than *x* seconds, he would bake it for *x* seconds and put it back in its place. More precisely, for every *i* in range [*l*,<=*r*], if *a**i* is strictly more than *x*, *a**i* becomes equal *a**i*<=-<=*x*. Operation 2: 2 *l* *r* *x* Willem asks Chtholly to count the number of cakes in the range [*l*,<=*r*] that needs to be cooked for exactly *x* seconds. More formally you should find number of such *i* in range [*l*,<=*r*], that *a**i*<==<=*x*.
```python def get_int(string, n): i = j = k = 0 for s in string: k += 1 for s in string: if i == n - 1: break if s == ' ': i += 1 j += 1 i = 0 while j < k: if string[j] == ' ': break i = 10 * i + int(string[j]) j += 1 return i def get_zcy(string): strin = '' for i in string: strin = i + strin return string + strin x = input() k = get_int(x, 1) p = get_int(x, 2) sum = 0 for i in range(1, k + 1): y = f"{i}" y = get_zcy(y) sum += int(y) print(sum % p) ```
MatrixStudio/Codeforces-Python-Submissions
Nick's company employed *n* people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are *m* applications written in the following form: «employee *a**i* is ready to become a supervisor of employee *b**i* at extra cost *c**i*». The qualification *q**j* of each employee is known, and for each application the following is true: *q**a**i*<=&gt;<=*q**b**i*. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.
```python n = int(input()) quali = input().split() m = int(input()) None l = [None]*n cnt = 0 for i in range(m): a, b, c = list(map(int, input().split())) if l[b-1] == None: l[b-1] = c else: l[b-1] = min(l[b-1], int(c)) if (l.count(None) > 1): print(-1) else: for j in l: if j != None: cnt += j print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.
```python import string s = string.ascii_lowercase n = int(input()) st = input().lower() retult = None for i in s: if i in st: retult ='YES' else: print('No') break print(retult) ```
MatrixStudio/Codeforces-Python-Submissions
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice and Bob play dice. Alice has built a tower from *n* dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees). Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.
```python x = int(input()) face = int(input()) facx = 7-face message = 1 for i in range(x): z = list(map(int,input().split())) if face in z or facx in z : message*=0 else : message*=1 if message == 0: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide. He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
```python def main(): n = int(input()) a = [int(x) for x in input().split()] w = 0 for i in range(n): min_val, max_val = a[i], a[i] for j in range(i+2, n+1): if a[j-1] < min_val: min_val = a[j-1] elif a[j-1] > max_val: max_val = a[j-1] if min_val == max_val: w += 1 print(w+n) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya was given this problem for homework: You are given function (here represents the operation of taking the remainder). His task is to count the number of integers *x* in range [*a*;*b*] with property *f*(*x*)<==<=*x*. It is a pity that Petya forgot the order in which the remainders should be taken and wrote down only 4 numbers. Each of 24 possible orders of taking the remainder has equal probability of being chosen. For example, if Petya has numbers 1, 2, 3, 4 then he can take remainders in that order or first take remainder modulo 4, then modulo 2, 3, 1. There also are 22 other permutations of these numbers that represent orders in which remainder can be taken. In this problem 4 numbers wrote down by Petya will be pairwise distinct. Now it is impossible for Petya to complete the task given by teacher but just for fun he decided to find the number of integers with property that probability that *f*(*x*)<==<=*x* is not less than 31.4159265352718281828459045%. In other words, Petya will pick up the number *x* if there exist at least 7 permutations of numbers *p*1,<=*p*2,<=*p*3,<=*p*4, for which *f*(*x*)<==<=*x*.
```python a,b,c,d,e,f=map(int,input().split()) count=0 for i in range(e,f+1): k=i%a%b%c%d if i==k: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it. The robot can only move up, left, right, or down. When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits. The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions. Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.
```python n, m = map(int, input().split()) mz = [input() for _ in range(n)] instr = input() sr, sc, exitRow, exitCol = -1, -1, 0, 0 for p in range(n): for q in range(m): if mz[p][q] == 'S': sr, sc = p, q elif mz[p][q] == 'E': exitRow, exitCol = p, q cnt = 0 for perm in permutations([0, 1, 2, 3]): row, col = sr, sc success = False for u in instr: u = int(u) if u == perm[0]: row += 1 elif u == perm[1]: row -= 1 elif u == perm[2]: col += 1 elif u == perm[3]: col -= 1 if row < 0 or row >= n or col < 0 or col >= m: break if mz[row][col] == '#': break if mz[row][col] == 'E': success = True break cnt += success print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following *n* days. According to the bear's data, on the *i*-th (1<=≤<=*i*<=≤<=*n*) day, the price for one barrel of honey is going to is *x**i* kilos of raspberry. Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for *c* kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day *d* (1<=≤<=*d*<=&lt;<=*n*), lent a barrel of honey and immediately (on day *d*) sell it according to a daily exchange rate. The next day (*d*<=+<=1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day *d*<=+<=1) give his friend the borrowed barrel of honey as well as *c* kilograms of raspberry for renting the barrel. The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
```python n,m=map(int,input().split()) l=list(map(int,input().split())) d=-13546789 for i in range(0,n-1,1): if -l[i+1]+l[i]>=d: d=-l[i+1]+l[i] if d>0: print(d-m) else: print(0) ```
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 name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed. Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
```python from sys import stdin n = int(stdin.readline()) cnt = {'POLYCARP': 1} ans = 1 for i in range(n): name1, _, name2 = map(lambda s: s.strip().upper(), stdin.readline().split()) cnt[name1] = cnt[name2] + 1 ans = max(ans, cnt[name1]) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in such a way that they form $a$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".
```python from collections import * from heapq import * from bisect import * from itertools import * from functools import * from math import * from string import * import sys input = sys.stdin.readline def solve(): n = int(input()) S = [] groups = defaultdict(set) for _ in range(n): s = input().strip() S.append(s) groups[len(s)].add(s) if len(groups[len(s)]) > 1: print("NO") return S.sort(key=len) is_chain_substrs = all(S[i] in S[i + 1] for i in range(n - 1)) if is_chain_substrs: print("YES") print("\n".join(S)) else: print("NO") def main(): solve() if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer *n*?" Petya knows only 5 integer types: 1) byte occupies 1 byte and allows you to store numbers from <=-<=128 to 127 2) short occupies 2 bytes and allows you to store numbers from <=-<=32768 to 32767 3) int occupies 4 bytes and allows you to store numbers from <=-<=2147483648 to 2147483647 4) long occupies 8 bytes and allows you to store numbers from <=-<=9223372036854775808 to 9223372036854775807 5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower. For all the types given above the boundary values are included in the value range. From this list, Petya wants to choose the smallest type that can store a positive integer *n*. Since BigInteger works much slower, Peter regards it last. Help him.
```python import sys n = int(sys.stdin.readline()[:-1]) n = abs(n) if(n <= 127): print("byte") elif(n <= 32767): print("short") elif(n <= 2147483647): print("int") elif(n <= 9223372036854775807): print("long") else: print("BigInteger") ```
MatrixStudio/Codeforces-Python-Submissions
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction). Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.
```python from sys import stdin inp = stdin.readline n = int(inp()) arr = [int(x) for x in inp().split()] win = arr.index(max(arr)) arr.pop(win) print(win+1, max(arr)) ```
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. Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope with the task.
```python a = int(input()) b ="" while(a<4): if(a-7>0): b=b+"7" a=a-7 continue if(a-4>0): b=b+"4" a=a-4 if(a==0): print(b) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Hands that shed innocent blood! There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=&lt;<=*i* and *j*<=≥<=*i*<=-<=*L**i*. You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
```python n = int(input()) A = list(map(int, input().split())) for i in range(len(A)): k = i-1 while k>=i-A[i] and k>=0: A[k] = -1 k-=1 print(len(A)-A.count(-1)) ```
MatrixStudio/Codeforces-Python-Submissions
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
```python from sys import stdin, stdout import random import time def threepal(n): s = [0 for x in range(n)] all_choices = ["a", "b", "c"] preferred_choices = ["a", "b"] for i in range(2): s[i] = random.choice(preferred_choices) for i in range(2, int(n/1)): if s[i-2] == "a": s[i] = "b" else: s[i] = "a" return "".join(s) if __name__ == '__main__': # a, b = [int(x) for x in stdin.readline().rstrip().split()] # lines = stdin.readlines() # stdout.write(str(a) + "\n") n = int(input()) print(threepal(n)) def decrypt(t, n): for i in range(2, n): if n%i==0: t = t[i-1::-1] + t[i:] t = t[::-1] return t def beautifulString(s): letters = set(('a', 'b', 'c')) for i in range(len(s)): if i<len(s)-1: if s[i] != '?' and s[i] == s[i+1]: return -1 if s[i] == "?": usedLetters = set() if i<len(s)-1: usedLetters.add(s[i+1]) if i>0: usedLetters.add(s[i-1]) remaining = list(letters-usedLetters) new_character = random.choice(remaining) s[i] = new_character return "".join(s) ```
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 remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.
```python n = int(input()) s = input() a = s.count('SF') b = s.count('FS') if a > b: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden. Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length *a**i* if she chooses the *i*-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden. See the examples for better understanding.
```python k,n=map(int,input().split()) s=map(int,input().split()) q=1 for i in s: if n%i==0: q=max(q,i) print(n//q) ```
MatrixStudio/Codeforces-Python-Submissions
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice and Bob play dice. Alice has built a tower from *n* dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees). Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.
```python n = int(input()) x = int(input()) for i in range (n): a, b=map(int, input().split()) if a == 6 or b == 6: print("NO") else: print("YES") ```