source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
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 number = 0 n = input() for i in range(len(n)): if str(n)[i] == '7' or str(n)[i] == '4': number += 1 if str(len(str(number))) in '47 74 444 447 474 477 744 747 774 777 4444 4447 \ 4474 4477 4744 4747 4774 4777 7444': print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo adores integer segments, that is, pairs of integers [*l*; *r*] (*l*<=≤<=*r*). He has a set that consists of *n* integer segments: [*l*1; *r*1],<=[*l*2; *r*2],<=...,<=[*l**n*; *r**n*]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [*l*; *r*] to either segment [*l*<=-<=1; *r*], or to segment [*l*; *r*<=+<=1]. The value of a set of segments that consists of *n* segments [*l*1; *r*1],<=[*l*2; *r*2],<=...,<=[*l**n*; *r**n*] is the number of integers *x*, such that there is integer *j*, for which the following inequality holds, *l**j*<=≤<=*x*<=≤<=*r**j*. Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by *k*.
```python n,k=map(int,input().split()) x=0 for i in range(0,n): a,b=map(int,input().split()) if a<b: x=x+1 if n==x: print(n) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array consisting of *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to *n* defining the order elements of the array are destroyed. After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
```python def lowbit(i): return i&-i def update(idx,i): while idx<=n: bit[idx]+=i idx+=lowbit(idx) def get_sum(i): res = 0 while i: res+=bit[i] i-=lowbit(i) return res def get_down(i): if i-1 in point_set: down_mapper[i] = get_down(i-1) return down_mapper[i] def get_up(i): if i+1 in point_set: up_mapper[i] = get_up(i+1) return up_mapper[i] n = int(input()) arr = list(map(int,input().split())) bit = [0]*(n+1) point_set = set() deque = list(map(int,input().split())) down_mapper = dict((i,i-1) for i in range(1,n+1)) up_mapper = dict((i,i) for i in range(1,n+1)) res = [0] tmp = 0 for i in reversed(deque[1:]): update(i,arr[i-1]) point_set.add(i) up = get_up(i) down = get_down(i) tmp = max(tmp,get_sum(up)-get_sum(down)) res.append(tmp) print(*reversed(res),sep="\n") ```
MatrixStudio/Codeforces-Python-Submissions
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
```python from collections import Counter def isSq(n): ans=int(n**0.5) if ans**2==n: return True return False def solve(): n,k=list(map(int,input().split())) arr=[int(i) for i in input().split()] count=Counter(arr) if len(count)>=k: print("YES") else: print("NO") solve() ```
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 countOnes(n): count = [0] * (n + 1) count[1] = 1 for i in range(2, n + 1): if i % 2 == 0: count[i] = count[i // 2] else: count[i] = count[i // 2] + 1 return count def solve(n, l, r): count = countOnes(n) return sum(count[l:r + 1]) n, l, r = map(int, input().split()) print(solve(n, l, r)) ```
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 inp=input() small=0 uper=0 innt=0 for i in inp: if i.islower(): small+=1 elif i.isupper(): uper+=1 elif i.isdigit(): innt+=1 print(small,uper,innt) if small>=1 and uper>=1 and innt>=1 and len(inp)>=5: print('Correct') else: print('Too weak') ```
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 s= input() t= input() def rev(s): return s[::-1] re=rev(s) if(s !=' ' and t !=' '): if re== t: print("YES") else: print("NO") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.
```python import math a,b = map(int, input().split()) x = a * (math.log(b)); y = b * (math.log(a)); if y > x: print(">") elif x > y: print("<") elif x == y: print("=") ```
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 n=int(input()) l=list(map(int,input().split())) dic={} for i in range(n): a=l[:] a.pop(i) dic[i+1]=max(a) c=list(dic.values()) c=list(set(c)) c.remove(max(c)) m=max(c) for i in dic: if dic[i]==m: k=i print(k,m) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the *i*-th star on the pedal axle has *a**i* (0<=&lt;<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*) teeth, and the *j*-th star on the rear wheel axle has *b**j* (0<=&lt;<=*b*1<=&lt;<=*b*2<=&lt;<=...<=&lt;<=*b**m*) teeth. Any pair (*i*,<=*j*) (1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (*i*,<=*j*) has a gear ratio, equal to the value . Since Vasya likes integers, he wants to find such gears (*i*,<=*j*), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (*i*,<=*j*) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears. In the problem, fraction denotes division in real numbers, that is, no rounding is performed.
```python n=int(input()) a=list(map(int,input().split())) m=int(input()) b=list(map(int,input().split())) ratio=[] for i in a: for j in b: if(j%i==0): ratio.appennd(j//i) n=max(ratio) print(ratio.count(n)) ```
MatrixStudio/Codeforces-Python-Submissions
They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so. Limak is a little polar bear who loves to play. He has recently got a rectangular grid with *h* rows and *w* columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through *h* from top to bottom. Columns are numbered 1 through *w* from left to right. Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid. Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?
```python h, w = map(int, input().split()) s = [] for i in range(h): s.append(list(input())) s[i].append('#') s.append(['#']*(w+1)) v = [[0]*(w+2)] g = [[0]*(w+2)] for i in range(h+1): v.append([0]*(w+2)) g.append([0]*(w+2)) for i in range(len(s)): count = 0 for j in range(1, len(s[0])): if s[i][j] == '.' and s[i][j-1] == '.': count += 1 if i == 0: g[i][j] = count else: g[i][j] = count + g[i-1][j] for j in range(len(s[0])): count = 0 for i in range(1, len(s)): if s[i][j] == '.' and s[i-1][j] == '.': count += 1 if j == 0: v[i][j] = count else: v[i][j] = count + v[i][j-1] q = int(input()) g = g[:h] g.insert(0, [0]*(w+1)) for i in range(len(g)): g[i] = g[i][:w] g[i].insert(0, 0) v = v[:h] v.insert(0, [0]*(w+1)) for i in range(len(v)): v[i] = v[i][:w] v[i] .insert(0, 0) for i in g: print(i) print() for i in v: print(i) for i in range(q): count = 0 u1, u2, d1, d2 = map(int, input().split()) count += g[d1][d2] count -= g[d1][u2] count -= g[u1-1][d2] count += g[u1-1][u2] count += v[d1][d2] count -= v[u1][d2] count -= v[d1][u2-1] count += v[u1][u2] print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time. You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
```python p=input() x=p.find("b") y=p.find("c") a=p[:x] b=p[x:y] c=p[y:] if(a=="" or b=="" or c==""): print("NO") else: if(len(c)==len(a) or len(c)==len(b)): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
```python n,k,m=[int(i) for i in input().split()] l=[int(i) for i in input().split()] lmain=[] for i in range(n): lmain.append(l[i]) l[i] = l[i]%m l1=[] for i in range(m): l1.append(0) for i in range(n): l1[l[i]]+=1 f=0 save=-1 for i in range(m): if (l1[i]>=k): f=1 save=i break if (f==0): print ('No') else: print ('Yes',end= "\n") count=0 l3=[] for i in range(n): if (count==k): break if (l[i]==save): l3.append(lmain[i]) count+=1 for i in l3: print (i, end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are *n* people in the queue. For each person we know time *t**i* needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
```python def max_happy_people(n, times): times.sort() # Сортировка времен обслуживания по возрастанию happy_count = 0 # Счетчик довольных людей total_waiting_time = 0 # Общее время ожидания for i in range(n): if times[i] >= total_waiting_time: # Проверка условия для довольного человека happy_count += 1 total_waiting_time += times[i] # Обновление общего времени ожидания else: # Человек будет недоволен, переносим его в конец очереди без увеличения времени ожидания times.append(times[i]) return happy_count # Чтение входных данных n = int(input()) times = list(map(int, input().split())) # Вызов функции и вывод результата print(max_happy_people(n, times)) ```
MatrixStudio/Codeforces-Python-Submissions
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process. Help the dwarfs find out how many triangle plants that point "upwards" will be in *n* years.
```python n=int(input()) m=pow(10,9)+7 if n==0: print(1) else: print((pow(2,2*n-1,m)+pow(2,n-1,m))%m) ```
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 a=int(input()) f=[1,1] if a>2: for i in range(3,a+1): p=f[i-3]+f[i-2] f.append(p) for x in range(1,a+1): if x in f: print("O",end="") else: print("o",end="") ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```python a = input() b = input() c = (bin(int(a,2)+int(b,2))) c = c.replace("0b","") print(c) ```
MatrixStudio/Codeforces-Python-Submissions
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below: There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers *a* and *b* (*a*·*b*<==<=12), after that he makes a table of size *a*<=×<=*b* from the cards he put on the table as follows: the first *b* cards form the first row of the table, the second *b* cards form the second row of the table and so on, the last *b* cards form the last (number *a*) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses. Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers *a* and *b* to choose. Help her win the game: print to her all the possible ways of numbers *a*,<=*b* that she can choose and win.
```python n = int(input()) otv = [] result = "" counter = 0 flag = True for _ in range(n): temp = input() for i in range(12): if 12 % (i+1) == 0 and temp[i] == "X": for j in range((i*2)+1, 12, i+1): if temp[j] != temp[i]: flag = False break if flag: counter += 1 otv.append(f"{round(12/(i+1))} x {i+1} ") flag = True otv = sorted(otv, key=lambda x: int(x.split()[0].strip('x'))) result += str(counter) + " " + "".join(otv) + "\n" result = result.replace(" x ", "x") counter = 0 otv = [] else: print(result)# 1689471988.4487488 ```
MatrixStudio/Codeforces-Python-Submissions
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number). Your task is to find out if a given integer is a triangular number.
```python n=int(input()) if n<0: print('NO') else: sum,a=0,1 while(sum<=n): sum=sum+a if sum==n: print('YES') break a=a+1 print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are *n* planes on Earth, numbered from 1 to *n*, and the plane with number *i* likes the plane with number *f**i*, where 1<=≤<=*f**i*<=≤<=*n* and *f**i*<=≠<=*i*. We call a love triangle a situation in which plane *A* likes plane *B*, plane *B* likes plane *C* and plane *C* likes plane *A*. Find out if there is any love triangle on Earth.
```python t= int(input()) l=list(map(int,(input().split()))) found=False for i in range(len(l)): start=l[i]-1 count=0 while count<2: start=l[start]-1 count+=1 if start==i: found=True print("YES") break if not found: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia [https://en.wikipedia.org/wiki/Japanese_crossword](https://en.wikipedia.org/wiki/Japanese_crossword)). Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of *n* squares (e.g. japanese crossword sized 1<=×<=*n*), which he wants to encrypt in the same way as in japanese crossword. Help Adaltik find the numbers encrypting the row he drew.
```python n = int(input()) s = tuple(input()) bCount = 0 temp = [] ans = [] for b in s: n -= 1 if b == "B": bCount += 1 elif b == "W": ans.append(bCount) bCount -= bCount if n == 0: ans.append(bCount) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berland). You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
```python n = int(input()) a = [int(a) for a in input().split()] m = max(a) add = 0 for i in a: add += (m-i) print(add) ```
MatrixStudio/Codeforces-Python-Submissions
You are given array *a* with *n* elements and the number *m*. Consider some subsequence of *a* and the value of least common multiple (LCM) of its elements. Denote LCM as *l*. Find any longest subsequence of *a* with the value *l*<=≤<=*m*. A subsequence of *a* is an array we can get by erasing some elements of *a*. It is allowed to erase zero or all elements. The LCM of an empty array equals 1.
```python import sys n, m = map(int, sys.stdin.buffer.readline().decode('utf-8').split()) a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) dp = [0]*(m+1) for x in a: if x <= m: dp[x] += 1 for i in range(m, 0, -1): for j in range(2, m+1): if i*j > m: break dp[i*j] += dp[i] lcm = dp.index(max(dp)) ans = [i for i, x in enumerate(a, start=1) if lcm % x == 0] sys.stdout.buffer.write( (str(lcm) + ' ' + str(len(ans)) + '\n' + ' '.join(map(str, ans))).encode('utf-8') ) ```
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*. Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
```python x = int(input()) x_str = str(x) result = '' if x_str[0] > '4': result += str(9 - int(x_str[0])) else: result += x_str[0] for digit in x_str[1:]: result += min(digit, str(9 - int(digit))) result_int = int(result) print(result_int) ```
MatrixStudio/Codeforces-Python-Submissions
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw *n* people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
```python n = int(input()) a = [] b = [] for i in range(n): s = input() a.append(s) for j in a: if(j=="ABSINTH" or j=="BEER" or j=="BRANDY" or j=="CHAMPAGNE" or j=="GIN" or j=="RUM" or j=="SAKE" or j=="TEQUILA" or j=="VODKA" or j=="WHISKEY" or j=="WINE"): b.append(j) if(j=="0" or j=="1" or j=="2" or j=="3" or j=="4" or j=="5" or j=="6" or j=="7" or j=="8" or j=="9" or j=="10" or j=="11" or j=="12" or j=="13" or j=="14" or j=="15" or j=="16" or j=="17"): b.append(j) print(len(b)) ```
MatrixStudio/Codeforces-Python-Submissions
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order. There will be *n* problems. The *i*-th problem has initial score *p**i* and it takes exactly *t**i* minutes to solve it. Problems are sorted by difficulty — it's guaranteed that *p**i*<=&lt;<=*p**i*<=+<=1 and *t**i*<=&lt;<=*t**i*<=+<=1. A constant *c* is given too, representing the speed of loosing points. Then, submitting the *i*-th problem at time *x* (*x* minutes after the start of the contest) gives *max*(0,<= *p**i*<=-<=*c*·*x*) points. Limak is going to solve problems in order 1,<=2,<=...,<=*n* (sorted increasingly by *p**i*). Radewoosh is going to solve them in order *n*,<=*n*<=-<=1,<=...,<=1 (sorted decreasingly by *p**i*). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie. You may assume that the duration of the competition is greater or equal than the sum of all *t**i*. That means both Limak and Radewoosh will accept all *n* problems.
```python def score(p, t, c): x, s = 0, 0 for pi, ti in zip(p, t): x += ti s += max(0, pi - c * x) return s n, c = map(int, input().split()) p = list(map(int, input().split())) t = list(map(int, input().split())) s1 = score(p, t, c) p.reverse() t.reverse() s2 = score(p, t, c) print("Tie" if s1 == s2 else ["Radewoosh","Limak"][s1 > s2]) ```
MatrixStudio/Codeforces-Python-Submissions
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1. Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used. Help Sherlock complete this trivial task.
```python # https://codeforces.com/problemset/problem/776/B from math import sqrt def is_prime(x): if x == 2 or x == 3: return True if x%2 == 0 or x%3 == 0: return False tmp = 5 while tmp < sqrt(x) + 1: if x % tmp == 0: return False tmp += 2 if x % tmp == 0: return False tmp += 4 return True if __name__ == '__main__': n = int(input()) A = [2]*n for i in range(n): if is_prime(i+2): A[i] = 1 print(2) for i in range(n): print(A[i], end=' ') print() ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake. However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change. Can you help B find out exactly what two errors he corrected?
```python n=int(input()) a=sum(list(map(int,input().split()))) b=sum(list(map(int,input().split()))) c=sum(list(map(int,input().split()))) print(a-b) print(b-c) ```
MatrixStudio/Codeforces-Python-Submissions
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3. You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
```python word = input() znak = word[1] word = word.replace(znak,'') s=[] for i in range(len(word)): s.append(word[i]) s = sorted(s) print(*s,sep=znak) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a string *A*. Find a string *B*, where *B* is a palindrome and *A* is a subsequence of *B*. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest". A palindrome is a string that reads the same forward or backward. The length of string *B* should be at most 104. It is guaranteed that there always exists such string. You do not need to find the shortest answer, the only restriction is that the length of string *B* should not exceed 104.
```python a=input() a1=[] a2=[] for i in a: a1.append(i) a2.append(i) a2.reverse() if a1==a2: print(a) else: a3=a1+a2 print(*a3,sep='') ```
MatrixStudio/Codeforces-Python-Submissions
It seems that Borya is seriously sick. He is going visit *n* doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor. Doctors have a strange working schedule. The doctor *i* goes to work on the *s**i*-th day and works every *d**i* day. So, he works on days *s**i*,<=*s**i*<=+<=*d**i*,<=*s**i*<=+<=2*d**i*,<=.... The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
```python n = int(input()) for i in range(n): si, di = list(map(int, input().split())) if i == 0: sum = si else: while si < sum: si += di sum = si print(sum) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*. Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square. Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way.
```python n = int(input()) if n%2==0: n=n//5 print(n) ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo adores strings. But most of all he adores strings of length *n*. One day he wanted to find a string that meets the following conditions: 1. The string consists of *n* lowercase English letters (that is, the string's length equals *n*), exactly *k* of these letters are distinct. 1. No two neighbouring letters of a string coincide; that is, if we represent a string as *s*<==<=*s*1*s*2... *s**n*, then the following inequality holds, *s**i*<=≠<=*s**i*<=+<=1(1<=≤<=*i*<=&lt;<=*n*). 1. Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist. String *x*<==<=*x*1*x*2... *x**p* is lexicographically less than string *y*<==<=*y*1*y*2... *y**q*, if either *p*<=&lt;<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or there is such number *r* (*r*<=&lt;<=*p*,<=*r*<=&lt;<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=&lt;<=*y**r*<=+<=1. The characters of the strings are compared by their ASCII codes.
```python n,k=map(int,input().split()) if k>n: print(-1) elif k==1: if n==1: print('a') else: print(-1) else: alph="" for i in range(26): alph+=(chr(i+97)) ans=alph[:k] n-=k if n%2: z=ans[0]+ans[1]+'ab'*(n//2)+'a'+ans[2:] else: z=ans[0]+ans[1]+'ab'*(n//2)+ans[2:] print(z) ```
MatrixStudio/Codeforces-Python-Submissions
Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
```python n = int(input()) s = input() if n <= 3: print(s); exit() else: if n&1: print(s[:3] + "-", end = "") for i in range(3, n - 2, 2): print(s[i:i+2] + "-", end = "") print(s[n-2:]) else: for i in range(0, n - 2, 2): print(s[i:i+2] + "-", end = "") print(s[n-2:]) ```
MatrixStudio/Codeforces-Python-Submissions
You have *n* devices that you want to use simultaneously. The *i*-th device uses *a**i* units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·*a**i* units of power. The *i*-th device currently has *b**i* units of power stored. All devices can store an arbitrary amount of power. You have a single charger that can plug to any single device. The charger will add *p* units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·*p* units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible. You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power. If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
```python def max_usage_time(n, p, devices): total_power = sum(a for a, _ in devices) min_time = min(b / (total_power - a) for a, b in devices) return min_time if min_time * p >= 1 else -1 # Input n, p = map(int, input().split()) devices = [tuple(map(int, input().split())) for _ in range(n)] # Calculate and print the result result = max_usage_time(n, p, devices) print(f'{result:.10f}') ```
MatrixStudio/Codeforces-Python-Submissions
A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with *n* rows and *m* columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.
```python n, m = list(map(int, input().split())) lst = [list(input()) for i in range(n)] a = [] b = [] for i in range(n): flag = True for j in lst[i]: if j == '*': flag = False if not flag: a.append(i) for x in range(m): flag = True for i in lst: if i[x] == '*': flag = False if not flag: b.append(x) # print(a, b) tmp = a[-1] + 1 lst = lst[a[0]:tmp] tmp = b[-1] + 1 for i in range(len(lst)): lst[i] = lst[i][b[0]:tmp] for i in lst: print(' '.join(i)) ```
MatrixStudio/Codeforces-Python-Submissions
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself. This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on. If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all. Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.
```python n = int(input()) l = 1 r = n while(l != r): mid = (l+r) // 2 k = n t1 = 0 while(k > 0): t1 +=min(mid,k) k -= min(mid,k) k -= k//10 if(t1 >= (n+1)//2): r = mid else: l = mid+1 print(l) ```
MatrixStudio/Codeforces-Python-Submissions
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly *x* chunks. Now he wonders whether he can buy exactly this amount of chicken. Formally, Ivan wants to know if he can choose two non-negative integers *a* and *b* in such a way that *a* small portions and *b* large ones contain exactly *x* chunks. Help Ivan to answer this question for several values of *x*!
```python for _ in range(int(input())): x=int(input()) if x%3==0 or x%7==0 or (x%7)%3==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly *n*1 balls and second player's box contains exactly *n*2 balls. In one move first player can take from 1 to *k*1 balls from his box and throw them away. Similarly, the second player can take from 1 to *k*2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
```python inputs = input() n1 = int(inputs[0]) n2 = int(inputs[2]) k1 = int(inputs[4]) k2 = int(inputs[6]) if n1 >= n2 or n2 >= n1: if k1 > k2: print("First") elif k2 > k1: print("Second") elif k1 == k2: if n1 > n2: print("First") elif n2 > n1: print("Second") ```
MatrixStudio/Codeforces-Python-Submissions
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
```python from math import ceil def main(): trans = { "--" : "2", "-." : "1", "." : "0", } code = input() res = "" ch = 0 while ch < len(code): for key in trans: if code[ch:ch+len(key)] == key: ch += len(key) res += trans[key] print(res) if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
You've got an *n*<=×<=*m* pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture. A picture is a barcode if the following conditions are fulfilled: - All pixels in each column are of the same color. - The width of each monochrome vertical line is at least *x* and at most *y* pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than *x* or greater than *y*.
```python from sys import stdin input = stdin.readline n,m,x,y=map(int,input().split()) A=[input() for i in range(n)] Z=[] for j in range(m): cnt=0 for i in range(n): if A[i][j]=="#": cnt+=1 Z.append(cnt) # print(Z) def rec(last,streak,i): if i==m: return 0 if x<=streak<=y else 10**10 if last==1: if streak<x: return n-Z[i]+rec(1,streak+1,i+1) elif x<=streak<y: return min(n-Z[i]+rec(1,streak+1,i+1),Z[i]+rec(0,1,i+1)) elif streak==y: return Z[i]+rec(0,1,i+1) else: if streak<x: return Z[i]+rec(0,streak+1,i+1) elif x<=streak<y: return min(n-Z[i]+rec(1,1,i+1),Z[i]+rec(0,streak+1,i+1)) elif streak==y: return n-Z[i]+rec(1,1,i+1) ans=min(n-Z[0]+rec(1,1,1),Z[0]+rec(0,1,1)) # if A==["."*m]*n: # ans=n*x print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars. Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
```python #include <iostream> #include <vector> #define _USE_MATH_DEFINES #include <math.h> #include <stdlib.h> #include <stdio.h> #include <algorithm> #include <climits> using namespace std; int main() { int n; cin >> n; int razlozhenie, cur; cin >> razlozhenie; while(razlozhenie % 2 == 0) razlozhenie /= 2; while(razlozhenie % 3 == 0) razlozhenie /= 3; for(int i = 1; i < n; i++) { cin >> cur; while(cur % 2 == 0) cur /= 2; while(cur % 3 == 0) cur /= 3; if(cur != razlozhenie) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; } ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
```python n,x=input().split() n=int(n);x=int(x) distressed=0 for i in range(n): a,b=input().split() b=int(b) if a=='+': x+=b elif x>=b: x-=b else: distressed+=1 print(x,distressed) ```
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()) hid = 7-x for i in range(n): hid = 7-x a, b = map(int, input().split()) if hid in [7-a, 7-b, a, b]: print("NO") break else: x = hid else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam. You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=*n*). The answer to the query *l**i*,<=*r**i* is the number of such integers *i* (*l**i*<=≤<=*i*<=&lt;<=*r**i*), that *s**i*<==<=*s**i*<=+<=1. Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
```python def count_pref(s: str) -> list[int]: pref = [0] * (len(s)) for i in range(1, len(pref)): pref[i] += pref[i-1] if s[i-1] == s[i]: pref[i] += 1 return pref def process(pref: list[int], queries: list[list[int]]) -> list[int]: res = [] for query in queries: i, j = query value = pref[j-1] - pref[i-1] res.append(value) return res if __name__ == "__main__": sequence = input().strip() n = int(input().strip()) pref = count_pref(sequence) queries = [] for _ in range(n): query = list(map(int, input().strip().split())) queries.append(query) ans = process(pref, queries) print("\n".join(map(str, ans))) ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes). The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
```python n=input() a=[x for x in n] if n.count('0')>0: a.remove('0') print(''.join(a)) else: del a[-1] print(''.join(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters. Help her to find the maximum number of "nineteen"s that she can get in her string.
```python def printMatrix(matrix): for matrixrow in matrix: row = '' for value in matrixrow: row += str(value) + ' ' print(row) n = int(input()) w = [[0 for i in range(n)] for i in range(n)] a = [[0 for i in range(n)] for i in range(n)] b = [[0 for i in range(n)] for i in range(n)] for i in range(n): row = input().split(' ') for e in range(n): w[i][e] = int(row[e]) for i in range(n): for e in range(n): a[e][i] = a[i][e] = (w[i][e]+w[e][i]) / 2 b[e][i] = w[e][i] - a[e][i] printMatrix(a) printMatrix(b) ```
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 s=input() s=list(s) p=int(input()) f=0 #lst = list(map(int, input().strip().split(' '))) i=0 k=len(s)//p while(i<=len(s)-k): t=[] for j in range(i,i+k): t.append(s[j]) if s[i:i+k]==t[::-1]: i+=k else: print('NO') f=1 break if f==0: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
```python x = [] d = [] for i in ' '*int(input()): x2, d2 = map(int, input().split()) x.append(x2) d.append(d2) f = 0 kol = 0 for i in range(len(x)): for j in range(len(x)): if x[i]+d[i] == x[j] and x[j] + d[j] == x[i] and kol != 2: f = 1 kol += 1 print('YES' if f == 1 else 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
```python n=int(input()) list1=list( map(int,input().split())) list2= list (map(int,input().split())) MergedList=list1+list2 X=set(MergedList()) if len(X)==n: print("I become the guy.") else: print("Oh, my keyboard!") ```
MatrixStudio/Codeforces-Python-Submissions
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds. If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows: 1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw. Given the length of the text and the information about participants, determine the result of the game.
```python s,v1,v2,t1,t2=map(int,input().split()) z1=s*v1+2*t1 z2=s*v2+2*t2 if z1>z2: print("Second") elif z2>z1: print("First") else: print("Friendship") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding *s* of some word, your task is to decode it.
```python """ abcd bcad abcd """ n = int(input()) s = input() ans = [' '] * n if len(s) % 2 == 0: l = (n - 1) // 2 r = (n) // 2 i = 0 j = 1 ans[l] = s[i] ans[r] = s[j] while j + 2 < n: j += 2 i += 2 l -= 1 r += 1 ans[l] = s[i] ans[r] = s[j] else: m = n // 2 ans[m] = s[0] l = m - 1 r = m + 1 i = 1 j = 2 while i + 1 < n: ans[l] = s[i] ans[r] = s[j] l -= 1 r += 1 i += 2 j += 2 print("".join(ans)) ```
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 import sys (n, m) = [int(x) for x in sys.stdin.readline().split()] n_one = sys.stdin.readline().count("-") one = n - n_one for i in range(0, m): (l, r) = [int(x) for x in sys.stdin.readline().split()] q = r - l + 1 if q % 2 == 1: print(0) else: if q / 2 <= one and q / 2 <= n_one: print(1) else: print(0) ```
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 n = int(input()) strings = dict() length = [] for i in range(n): a = input() strings[len(a)] = a length.append(len(a)) length.sort() for j in range(n): length[j] = strings[length[j]] pos = True for k in range(n - 1): if length[k] not in length[k + 1]: pos = False if pos: print("YES") for o in length: print(o) else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Duff is in love with lovely numbers! A positive integer *x* is called lovely if and only if there is no such positive integer *a*<=&gt;<=1 such that *a*2 is a divisor of *x*. Malek has a number store! In his store, he has only divisors of positive integer *n* (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible. Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.
```python import math def check_square_division(n): for i in range(2, math.floor(math.sqrt(n))): if n % (i ** 2) == 0: return False return True def main(): n= int(input()) divisors = [] for i in range(1, n+1): if n % i == 0: divisors.append(i) final_answer = -1 for divisor in reversed(divisors): if check_square_division(divisor): final_answer = divisor break print(final_answer) if __name__ == "__main__": main() ```
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 =input() n =int(n) X = 0 for i in range(1,n+1): a, b =input().split() a =int(a) b =int(b) if(b - a >= 2): x=x+1 print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: for given value of *n*. Fedya managed to complete the task. Can you? Note that given number *n* can be extremely large (e.g. it can exceed any integer type of your programming language).
```python def expression(n): if (n%4): return 0 else: return 4 n = int(input()) result = expression(n) print(result) ```
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 def gcd(a, b): rem = 0 while b != 0: rem = a%b a = b b = rem return a a, b = map(int, input().split()) if b-a == 1: print (-1) else: found = False for i in range(a, b+1): for j in range(i+1, b+1): for k in range(j+1, b+1): if gcd(i, j) == 1 and gcd(j, k) == 1 and gcd(i, k) != 1: found = True print (i, j, k) break if found: break if found: break if not found: print (-1) ```
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 n = int(input()) st = list(input()) if not "1" in st: print(0) quit() print("1", end = "") for i in st: if i == "0": print(i, end = "") print() ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```python data = input() l=u = 0 for x in data: if x.islower(): l+=1 else: u+=1 if l>=u: print(data.lower()) else: print(data.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test. You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
```python n=int(input()) l=list(map(int,input().split())) l.sort() if l[0]>1: print(1) else: for i in range(len(l)-1): if l[i+1]-l[i]>1: print(l[i]+1) break else: print(l[-1]+1) ```
MatrixStudio/Codeforces-Python-Submissions
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect. Ostap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell. Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.
```python n,k = map(int,input().split()) s = input() first = s.index('G') last = s.index('T') if first < last: if s[first+k] == 'T': print("YES") elif s[first+k] == '#': print("NO") elif first+k > last: print("NO") elif s[first+k] == '.': if s[(first+k)+1] == '#': print("NO") else: print("YES") else: if s[first-k] == 'T': print("YES") elif s[first-k] == '#': print("NO") elif s[first-k] == '.': if s[(first-k)-1] == '#': print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure. Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
```python n=int(input()) if n==3: print (2) print ('1 3') exit() if n==2: print (1) print (1) a=[] b=[] for i in range (1,n+1): if i%2==0: a.append(i) else : b.append(i) c=a+b print (n) print (" ".join(map(str,c))) ```
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 p=int(input()) for i in range(p): sedd=input() if(len(sedd)<=10): print(sedd) else: print(sedd[0]+str(len(sedd)-2)+sedd[len(sedd)-1]) ```
MatrixStudio/Codeforces-Python-Submissions
A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following *m* days. Determine the number of days starting from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.
```python n,p,m=map(int,input().split()) l2=[] ld=[] lt=[] k=0 for i in range(n): d,t=map(int,input().split()) ld.append(d) lt.append(t) for i in range(1,m+1): if i in ld: k+=lt[ld.index(i)] l2.append(k) s=0 for i in range(m): if l2[i]<p*(i+1): s+=1 print(s) ```
MatrixStudio/Codeforces-Python-Submissions
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
```python def has_different_digits(year): year_str = str(year) return len(set(year_str)) == len(year_str) def next_year(current_year): current_year+=1 while has_different_digits(current_year) is not True: current_year+=1 return current_year y= int(input()) result = next_year(y) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of *n* vertices. Vertex 1 is the root of the tree. Alice starts at vertex 1 and Bob starts at vertex *x* (*x*<=≠<=1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one. The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it. You should write a program which will determine how many moves will the game last.
```python import sys sys.setrecursionlimit(10 ** 6) n, x = map(int, input().split()) x -= 1 G = [[] for i in range(n)] for i in range(n - 1): a, b = map(int, input().split()) G[a - 1].append(b - 1) G[b - 1].append(a - 1) INF = float('inf') dista = [0] * n distb = [-1] * n def dfsa(u, par, d): dista[u] = d for w in G[u]: if w == par: continue dfsa(w, u, d + 1) def dfsb(u, par, d): distb[u] = d for w in G[u]: if w == par: continue if d + 1 >= dista[w]: distb[w] = d + 1 continue dfsb(w, u, d + 1) dfsa(0, -1, 0) dfsb(x, -1, 0) num = 0 for i in range(n): if distb[i] != -1: num = max(num, dista[i] * 2) print(num) ```
MatrixStudio/Codeforces-Python-Submissions
Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles. The hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has *a*, *b*, *c*, *a*, *b* and *c* adjacent tiles, correspondingly. To better visualize the situation, look at the picture showing a similar hexagon for *a*<==<=2, *b*<==<=3 and *c*<==<=4. According to the legend, as the King of Berland obtained the values *a*, *b* and *c*, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same?
```python a,b,c = map(int,input().split()) t = min(a,b,c)-1 s=a+b+c p=0 for k in range(t): s+=(s-3) print(s*2-((t+1)*6)) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of *s*.
```python n=int(input()) c=[] maxx=[] for i in range(n): m=int(input()) c.append(m) if len(c)==2 : if c.count(1)==c.count(0): print(2) else : for a in range(n): for b in range(n): q=c[a:b] if q.count(1)==q.count(0): maxx.append(len(q)) else : pass print (max(maxx)) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
```python n=int(input()) l1=list(map(int,input().split())) s=0 d=0 le=len(l1) if(le%2==0): while len(l1)>0: if(l1[0]>=l1[-1]): s=s+l1[0] l1.pop(0) else: s=s+l1[-1] l1.pop(-1) if(l1[0]>=l1[-1]): d=d+l1[0] l1.pop(0) else: d=d+l1[-1] l1.pop(-1) else: while len(l1)>1: if(l1[0]>=l1[-1]): s=s+l1[0] l1.pop(0) else: s=s+l1[-1] l1.pop(-1) if(l1[0]>=l1[-1]): d=d+l1[0] l1.pop(0) else: d=d+l1[-1] l1.pop(-1) s=s+l1[0] print(s,d) ```
MatrixStudio/Codeforces-Python-Submissions
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \to 2 \to \ldots n \to 1$. Flight from $x$ to $y$ consists of two phases: take-off from planet $x$ and landing to planet $y$. This way, the overall itinerary of the trip will be: the $1$-st planet $\to$ take-off from the $1$-st planet $\to$ landing to the $2$-nd planet $\to$ $2$-nd planet $\to$ take-off from the $2$-nd planet $\to$ $\ldots$ $\to$ landing to the $n$-th planet $\to$ the $n$-th planet $\to$ take-off from the $n$-th planet $\to$ landing to the $1$-st planet $\to$ the $1$-st planet. The mass of the rocket together with all the useful cargo (but without fuel) is $m$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $1$ ton of fuel can lift off $a_i$ tons of rocket from the $i$-th planet or to land $b_i$ tons of rocket onto the $i$-th planet. For example, if the weight of rocket is $9$ tons, weight of fuel is $3$ tons and take-off coefficient is $8$ ($a_i = 8$), then $1.5$ tons of fuel will be burnt (since $1.5 \cdot 8 = 9 + 3$). The new weight of fuel after take-off will be $1.5$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well. Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
```python import sys from math import * from collections import Counter,defaultdict,deque input=sys.stdin.readline mod=10**9+7 def get_ints():return map(int,input().split()) def get_int():return int(input()) def get_array():return list(map(int,input().split())) def input():return sys.stdin.readline().strip() # for _ in range(int(input())): n=get_int() m=get_int() o=m a=get_array() b=get_array() s=[a[0]] for i in range(1,n-1): s.append(b[i]) s.append(a[i]) s.append(b[-1]) s.append(a[-1]) s.append(b[0]) if 1 in s: print(-1) for j in s[::-1]: m=m*j/(j-1) print(m-o) ```
MatrixStudio/Codeforces-Python-Submissions
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door. The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters. Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
```python a = list(input()) b= list(input()) c = list(input()) for i in c: if i in a: a.remove(i) elif i in b: b.remove(i) else: print("NO") quit() if len(a) ==0 and len(b)==0: print("YES") else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```python n=list(map(str,input().split())) m=list(map(str,input().split())) lst=[] for i in n: for j in m: if i!=j: x=1 lst.append(x) else: y=0 lst.append(y) print(''.join(lst)) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not. One day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*.
```python import sys n = sys.stdin.readline() t = map(int, sys.stdin.readline().split()) count = {} for i in xrange(-10, 11): count[i] = 0; ret = 0 for x in t: count[x] += 1 for x in t: ret += count[-x] if x == 0: ret -= 1 print ret / 2 ```
MatrixStudio/Codeforces-Python-Submissions
You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it.
```python import re input() s = input() arr = ['vaporeon', 'jolteon', 'flareon', 'espeon', 'umbreon', 'leafeon', 'glaceon', 'sylveon'] for res in arr: if re.match(s, res): print(res) break ```
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,m=map(int,input().split()) num=[(int(x) for x in input().split())for i in range(n)] x=0 for i in range(m): if i in num: x+=1 print(['NO','YES'][x!=m]) ```
MatrixStudio/Codeforces-Python-Submissions
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=&gt;<=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency). The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer? The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
```python def get_cost(command,zlotys,passengers,cost = 0): while passengers: cost += command(zlotys) zlotys[zlotys.index(command(zlotys))] -= 1 if not zlotys[zlotys.index(command(zlotys))]: zlotys.pop(zlotys.index(command(zlotys))) passengers -= 1 return cost passengers,planes = map(int,input().split()) zlotys = [int(x) for x in input().split()] expensive = get_cost(max,zlotys[:],passengers) cheap = get_cost(min,zlotys,passengers) print (expensive,cheap) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
```python def division(): n = int(input()) a = [(int(num), i) for i, num in enumerate(input().split(), 1)] a.sort() for i in range(n // 2): print(a[i][1], a[n - 1 - i][1]) division() ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
```python word1 = str(input()).lower() word2 = str(input()).lower() if (word1 == word2): print(0) elif (word1 < word2): print(-1) else: print(1) ```
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 def charToInt(c): #'a'->0 return ord(c)-ord('a') def intToChar(x): #0->'a' return chr(ord('a')+x) s=input() t=input() tt=[charToInt(c) for c in t] ss=[charToInt(c) for c in s] n=len(tt) for i in range(n-1,-1,-1): ss[i]+=1 if ss[i]==26: ss[i]-=1 else: break s=''.join([intToChar(x) for x in ss]) if s==t: print('No such string') else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
```python def main(): n = int(input()) arr = list(map(int, input().split())) even = 0 odd = 0 for i in arr: if i % 2 == 0: even += 1 else: odd += 1 for i in range(n): if even == 1: if arr[i] % 2 == 0: print(i + 1) exit() else: if arr[i] % 2 != 0: print(i + 1) exit() main() ```
MatrixStudio/Codeforces-Python-Submissions
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: You should count, how many there are pairs of integers (*a*,<=*b*) (0<=≤<=*a*,<=*b*) which satisfy the system.
```python # your code goes here# your code goes her n,m=map(int,input().split()) diff= n-m ans=0 for i in range(1001): for j in range(1001): eq=(i-j)*(i+j-1) if eq==diff and (i*i+j)==n and (j*j+i)==m: ans=ans+1 print(ans) ```
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 n,l,r = map(int,input().split(' ')) x = n len = 0 def lon(c): if c > 0: return 1 + lon(c // 2) + lon(c // 2) else: return 0 len =lon(x) def f(n,left,right): if right < l or left > r: return 0 else: mid = (left + right) // 2 if mid <= r and mid >= l: if n == 1: return 1 else: return n % 2 + f(n // 2,left,mid - 1) + f(n // 2,mid + 1,right) elif mid > r: return 0 + f(n // 2,left,mid - 1) elif mid < l: return 0 + f(n // 2,mid + 1,right) print(f(n,1,len)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands. Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends *l* bytes to each participant of the chat, where *l* is the length of the message. As Polycarp has no time, he is asking for your help in solving this problem.
```python ans = 0 try: n = 0 while True: s = input() if s[0] == '+': n += 1 elif s[0] == '-': n -= 1 else: ans += len(s.split(':')[1]) * n except: pass print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions. It is guaranteed that the result will be positive integer number.
```python # for _ in range(int(input())): n,k = input().split() n = int(n) k=int(k) while k !=0: if n%10 >=k: n = n-k k=0 elif n%10 ==0: n = n//10 k -=1 else: temp = n%10 n -= temp k -=temp # print(n) print(n) ```
MatrixStudio/Codeforces-Python-Submissions
Yaroslav has an array that consists of *n* integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav.
```python n = int( input() ) a = list( map( int, input().strip().split( ' ' ) ) ) m = max( set( a ), key=a.count ) if (n == 1): print( "YES" ) elif (m > n / 2): print( "NO" ) else: print( "YES" ) ```
MatrixStudio/Codeforces-Python-Submissions
A sequence *a*0,<=*a*1,<=...,<=*a**t*<=-<=1 is called increasing if *a**i*<=-<=1<=&lt;<=*a**i* for each *i*:<=0<=&lt;<=*i*<=&lt;<=*t*. You are given a sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 and a positive integer *d*. In each move you may choose one element of the given sequence and add *d* to it. What is the least number of moves required to make the given sequence increasing?
```python n,d = map(int,input().split()) a = list(map(int,input().split())) ans = 1 for i in range(1,n): if a[i] <= a[i-1]: ans += (a[i - 1] - a[i]) // d + 1 a[i] = d*((a[i - 1] - a[i]) // d + 1) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* switches and *m* lamps. The *i*-th switch turns on some subset of the lamps. This information is given as the matrix *a* consisting of *n* rows and *m* columns where *a**i*,<=*j*<==<=1 if the *i*-th switch turns on the *j*-th lamp and *a**i*,<=*j*<==<=0 if the *i*-th switch is not connected to the *j*-th lamp. Initially all *m* lamps are turned off. Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards. It is guaranteed that if you push all *n* switches then all *m* lamps will be turned on. Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other *n*<=-<=1 switches then all the *m* lamps will be turned on.
```python def adding(a, b): res = "" tracker = True for i in range(len(a)): res += str(int(a[i]) + int(b[i])) if int(a[i]) == 0 and int(b[i]) == 1: tracker = False return res, tracker if __name__ == "__main__": n, m = list(map(int, input().rstrip().split())) switches = [] while n > 0: switches.append(input().rstrip()) n -= 1 total = "" for i in range(m): total += "0" #print(total) #print(switches) tracker = False for i in range(len(switches)): total, tracker = adding(total, switches[i]) #print(total) if tracker: print("YES") else: print("NO") ```
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 import random n = int(input()) # the length of the string options = ['a', 'b', 'c'] output = [] i = 0 while len(output) < n: if i % 3 == 0: i = 0 next = options[i] output.append(next) i += 1 print("".join(output)) ```
MatrixStudio/Codeforces-Python-Submissions
One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
```python import math def input_list_int(): return list(map(int, input().split())) n, _k = input_list_int() a = input_list_int() k = _k - 1 s = False el = a[k] for i in range(k, n): if a[i] != el: print(-1) exit() j = 0 for i in range(k): if a[i] != a[k+1]: j = i print(j+1) ```
MatrixStudio/Codeforces-Python-Submissions
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*s**p*2... *s**p**k* (1 <=≤<= *p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**k* <=≤<= |*s*|) a subsequence of string *s* = *s*1*s*2... *s*|*s*|, where |*s*| is the length of string *s*. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba". String *x* = *x*1*x*2... *x*|*x*| is lexicographically larger than string *y* = *y*1*y*2... *y*|*y*| if either |*x*| &gt; |*y*| and *x*1<==<=*y*1, *x*2<==<=*y*2, ...,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=&lt;<=|*x*|, *r*<=&lt;<=|*y*|) that *x*1<==<=*y*1, *x*2<==<=*y*2, ..., *x**r*<==<=*y**r* and *x**r*<=<=+<=<=1<=&gt;<=*y**r*<=<=+<=<=1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post". String *s* = *s*1*s*2... *s*|*s*| is a palindrome if it matches string *rev*(*s*) = *s*|*s*|*s*|*s*|<=-<=1... *s*1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
```python ans = "" s = input() for m in range(1 << len(s)): f = "".join([s[i] for i in range(len(s)) if m & (1 << i)]) if f == f[::-1]: ans = max(ans,f) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
The input contains a single integer *a* (0<=≤<=*a*<=≤<=35). Output a single integer.
```python n = int(input()) print(2 ** n if n < 35 else 33940307968) ```
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 s=input() t=input() print("YES") if s[::-1]==t else print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given *a*, *b* and *n* who wins the game.
```python a, b, n = map(int, input().split()) while n > 0: temp_a, temp_n = a, n while temp_n > 0: temp_a, temp_n = temp_n, temp_a % temp_n n -= temp_a if n > 0: temp_b, temp_n = b, n while temp_n > 0: temp_b, temp_n = temp_b, temp_b % temp_n n -= temp_b if n == 0: print(1) elif n < 0: print(0) elif n == 0: print(0) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that. All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.
```python #include<bits/stdc++.h> using namespace std; int main(void){ string s; cin>>s; int k; cin>>k; map<string,int>m; m["January"]=1; m["February"]=2; m["March"]=3; m["April"]=4; m["May"]=5; m["June"]=6; m["July"]=7; m["August"]=8; m["September"]=9; m["October"]=10; m["November"]=11; m["December"]=12; int y; int z; for(auto x:m){ if(x.first==s){ y=x.second+k; z=y%12; } } for(auto y:m){ if(y.second==z){ cout<<y.first<<endl; } } } ```
MatrixStudio/Codeforces-Python-Submissions
On one quiet day all of sudden Mister B decided to draw angle *a* on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex *n*-gon (regular convex polygon with *n* sides). That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices *v*1, *v*2, *v*3 such that the angle (where *v*2 is the vertex of the angle, and *v*1 and *v*3 lie on its sides) is as close as possible to *a*. In other words, the value should be minimum possible. If there are many optimal solutions, Mister B should be satisfied with any of them.
```python n,k=map(int,input().split()) if n==3:print("1 2 3") else: ans=3 t=180/n for i in range(4,n+1): if abs(k-(i-2)*t)<abs(k-(ans-2)*t): ans=i print(*[1,2,ans]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≤<=*i*,<=*j*<=≤<=*n* and *a**i*<=≥<=*a**j*.
```python n=int(input()) b=list(map(int,input().split())) b.sort() k=-1 r=n-1 l=0 p=-1 for i in range(n): m=b[i]*2-1 while l <= r: mid=(r+l)//2 if b[mid]<=m: k=mid l=mid+1 else: r=mid-1 p=max(p,b[k]%b[i]) print(p) ```
MatrixStudio/Codeforces-Python-Submissions
You have two friends. You want to present each of them several positive integers. You want to present *cnt*1 numbers to the first friend and *cnt*2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends. In addition, the first friend does not like the numbers that are divisible without remainder by prime number *x*. The second one does not like the numbers that are divisible without remainder by prime number *y*. Of course, you're not going to present your friends numbers they don't like. Your task is to find such minimum number *v*, that you can form presents using numbers from a set 1,<=2,<=...,<=*v*. Of course you may choose not to present some numbers at all. A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.
```python def check(mid,c1,c2,x,y): facy=mid//y facx=mid//x one=facy two=facx cnt=mid cnt-=(one+two) cnt-=max((c1-one),0) cnt-=max((c2-two),0) return cnt>=0 c1,c2,x,y=map(int,input().strip().split()) lo=1 hi=10**9 ans=-1 while lo<=hi: mid=(lo+hi)//2 if check(mid,c1,c2,x,y): hi=mid-1 ans=mid else: lo=mid+1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear! More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<=-<=*a*<=&gt;<=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen. For example, if *c*<==<=5 and you typed words at seconds 1,<=3,<=8,<=14,<=19,<=20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen. You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
```python n,c=map(int,input().split()) sum=1 words=list(map(int,input().split())) for k in range(1,n): if words[k]-words[k-1]<=c: sum+=1 else: sum=1 print(sum) ```
MatrixStudio/Codeforces-Python-Submissions
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
```python #http://codeforces.com/problemset/problem/859/B #not done import math def GCD(a,b): #print(a,b) if a < b: a, b = b, a if a%b == 0: return b else: return GCD(b,a%b) def minLengthsCall(n): RA = minLengths(n) #if len(RA) > 2: #RA.pop() return RA def minLengths(n): #print(n) if n <= 0: return [] has = n while has > n//2: if math.sqrt(has)%1 == 0: if has == n: return [int(math.sqrt(has)),int(math.sqrt(has))] else: return [int(math.sqrt(has)),int(math.sqrt(has))]+minLengths(n-has) has -= 1 else: maxVol = 1*n pos = [1,n] #print(pos) for i in range(1,n+1): if i*(n-i) > maxVol: #print("HERE") maxVol = i*(n-i) pos = [i,n-i] return pos #RA = [int(math.sqrt(n)),int(math.sqrt(n))]+minLengths(n-int(math.sqrt(n))**2) #return RA x = 0 def minStreets(n): lengths = minLengthsCall(n) streets = [] i = 0 while i < len(lengths): #print(lengths[i],lengths[i+1]) streets.append(2*lengths[i]+2*lengths[i+1]) i += 2 i = 0 j = 2 total = 0 if len(streets) == 1: return streets[0] currentStreets = 2*lengths[0]+2*lengths[1] if streets[0] > streets[1]: maxW = streets[0] else: maxW = streets[1] #print((lengths)) del lengths[0] del lengths[0] currentW = 0 while len(lengths) > 0: if lengths[0] > lengths[1]: addW = lengths[0] width = lengths[0] height = lengths[1] else: addW = lengths[1] width = lengths[1] height = lengths[0] #print(currentStreets,height) if currentW == 0: currentStreets += 2*height currentW = addW elif addW + currentW <= maxW: currentStreets += 0 currentW += addW if currentW > maxW: currentW = 0 else: currentStreets += height currentW += addW if currentW > maxWL: currentW = 0 del lengths[0] del lengths[0] return currentStreets while True: try: case = input() temp = int(case) print(minStreets(temp)) except EOFError: break ```