source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
There are *n* boys and *m* girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to *n*<=+<=*m*. Then the number of integers *i* (1<=≤<=*i*<=&lt;<=*n*<=+<=*m*) such that positions with indexes *i* and *i*<=+<=1 contain children of different genders (position *i* has a girl and position *i*<=+<=1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
```python file=open("input.txt",'r');c=open("output.txt",'w') a,b=map(int,file.readline().split()) c.write(['BG'*b+'B'*(a-b),'GB'*a+'G'*(b-a)][a<b]) #https://codeforces.com/contest/253/status/A, siddartha19 81809690 ```
MatrixStudio/Codeforces-Python-Submissions
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input). We have a sequence of characters he has typed and we want to find the original message.
```python side = input() a = "qwertyuiop" b = "asdfghjkl;" c = "zxcvbnm,./" s = input() nova = "" for i in s: if side == "R": if i in a: nova += a[a.index(i)-1] elif i in b: nova += b[b.index(i)-1] elif i in c: nova += c[c.index(i)-1] else: if i in a: nova += a[a.index(i)+1] elif i in b: nova += b[b.index(i)+1] elif i in c: nova += c[c.index(i)+1] print(nova) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
```python the_list=input().lstrip('{').rstrip('}').split(',') for i in the_list : if i =='': the_list.remove('') print(len(set(the_list))) ```
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()) st=input() new_st='' co=0 if n%2==0: for i in range(0,n,2): new_st+=st[i:i+2]+'-' else: for j in range(0,n,2): if j==2: new_st+=st[j:j+3]+'-' else: new_st+=st[j+1:j+3]+'-' if n%2==0: print(new_st[:len(new_st)-1]) else:print(new_st[:len(new_st)-2]) ```
MatrixStudio/Codeforces-Python-Submissions
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same. The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
```python list = [int(x) for x in input().split()] list.sort() if list[0] + list[1] > list[2] or list[1] + list[2] > list[3]: print("TRIANGLE") elif list[0] + list[1] == list[2] or list[1] + list[2] == list[3]: print("SEGMENT") else: print("IMPOSSIBLE") ```
MatrixStudio/Codeforces-Python-Submissions
The year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil. The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: *a* for Mephisto, *b* for Diablo and *c* for Baal. Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a of experience, rounded down, where *x* will be the amount of experience for the killed megaboss and *y* — the number of people in the team. Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum. It is known that some heroes like others. But if hero *p* likes hero *q*, this does not mean that the hero *q* likes hero *p*. No hero likes himself. The total amount of liking in teams is the amount of ordered pairs (*p*,<=*q*), such that heroes *p* and *q* are in the same group, and hero *p* likes hero *q* (but it is not important if hero *q* likes hero *p*). In case of heroes *p* and *q* likes each other and they are in the same group, this pair should be counted twice, as (*p*,<=*q*) and (*q*,<=*p*). A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team. It is guaranteed that every hero is able to destroy any megaboss alone.
```python import math import itertools if __name__ == '__main__': N = int(input()) likes = [input() for i in range(N)] likes = [line.split() for line in likes] likes = [(words[0], words[2]) for words in likes] a, b, c = (float(val) for val in input().split()) min_diff = max(a, b, c) possible_groups = [] for i in range(1, 7 - 1): for j in range(1, 7 - i): a_e = math.floor(a / i) b_e = math.floor(b / j) c_e = math.floor(c / (7 - i - j)) diff = max(a_e, b_e, c_e) - min(a_e, b_e, c_e) if diff < min_diff: min_diff = diff possible_groups = [(i, j)] elif diff == min_diff: possible_groups.append((i, j)) max_likes = 0 for order in itertools.permutations(['Anka', 'Chapay', 'Cleo', 'Troll', 'Dracul', 'Snowy', 'Hexadecimal']): for i, j in possible_groups: likes_count = 0 seta = set(order[:i]) setb = set(order[i:(i + j)]) setc = set(order[(i + j):]) for p, q in likes: if p in seta and q in seta: likes_count += 1 if p in setb and q in setb: likes_count += 1 if p in setc and q in setc: likes_count += 1 max_likes = max(max_likes, likes_count) print(f'{min_diff} {max_likes}') ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times. Please output the maximum number of cake cells that the cakeminator can eat.
```python a,b=list(map(int,input().split())) r=0 g=0 h=0 l=[] for i in range(a): s=input() if "S" in s: r+=s.count("S") l.append(list(s)) h+=1 else: l.append(list(s)) g+=1 if h!=0 and g!=0: print(b*r) elif r==(a*b) : print(0) elif g==a: print(a*b) ```
MatrixStudio/Codeforces-Python-Submissions
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different. There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number. You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
```python hs = [] ass = [] for _ in range(int(input())): h, a = map(int, input().split()) hs.append(h) ass.append(a) count = 0 for c in hs: for g in ass: if c== g: count+=1 else: pass print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true: - Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager. Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*. What is the minimum number of groups that must be formed?
```python # https://codeforces.com/problemset/problem/115/A import sys inp = tuple(int(line) for line in sys.stdin) have_parent, have_child = set(), set() flag = -1 for i in range(1, len(inp)): if inp[i] == -1: continue else: have_parent.add(i) if i in have_child: flag = 3 break have_child.add(inp[i]) if inp[i] in have_parent: flag = 3 break if not have_parent and not have_child: print(1) elif flag == 3: print(3) else: print(2) ```
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() while (len(s) > 4): print (s[0:2], end='-') s = s[2:] if (len(s) <=3): print (s) else: print (s[0:2], s[2:4], sep='-') ```
MatrixStudio/Codeforces-Python-Submissions
Pasha has many hamsters and he makes them work out. Today, *n* hamsters (*n* is even) came to work out. The hamsters lined up and each hamster either sat down or stood up. For another exercise, Pasha needs exactly hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?
```python n = int(input()) a = raw_input().strip() up = 0 for i in a: if i == 'X': up +=1 diff = (n // 2) - up print(abs(diff)) if diff >= 0: print(a.replace('x', 'X', diff)) else: print(a.replace('X', 'x', abs(diff))) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel and her friends are in a dancing room. There are *n* boys and *m* girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: - either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); - or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.
```python x,y=map(int,input().split()) z,x1,y1=[],[],[] for i in range(1,x+1): for j in range(1,y+1): if (i not in x1) or (j not in y1): x1.append(i) y1.append(j) z.append((i,j)) print(len(z)) for i in z:print(*i) ```
MatrixStudio/Codeforces-Python-Submissions
Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer *x*. You are given multiple queries consisting of pairs of integers *l* and *r*. For each query, find the *x*, such that *l*<=≤<=*x*<=≤<=*r*, and is maximum possible. If there are multiple such numbers find the smallest of them.
```python import math n = int(input()) for _ in range(n): l, r = tuple(map(int, input().split())) t = int(math.log2(r + 1)) if 2**t - 1 >= l and 2 ** t - 1 <= r: print(2 ** t - 1) else: print(r) ```
MatrixStudio/Codeforces-Python-Submissions
You have *m*<==<=*n*·*k* wooden staves. The *i*-th stave has length *a**i*. You have to assemble *n* barrels consisting of *k* staves each, you can use any *k* staves to construct a barrel. Each stave must belong to exactly one barrel. Let volume *v**j* of barrel *j* be equal to the length of the minimal stave in it. You want to assemble exactly *n* barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed *l*, i.e. |*v**x*<=-<=*v**y*|<=≤<=*l* for any 1<=≤<=*x*<=≤<=*n* and 1<=≤<=*y*<=≤<=*n*. Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.
```python from bisect import bisect_right def bad(): print(0) exit() n, k, l_ = map(int, input().split()) a = sorted(list(map(int, input().split()))) if n == 1: print(min(a)) exit() if a[1] - a[0] > l_: bad() b = bisect_right(a, a[0] + l_) if b < n: bad() to_sum = [0] if n == 2: print(a[0] + a[n // 2]) exit() to_sum += [min(k * i, b - n + i) for i in range(1, n)] print(sum(a[i] for i in to_sum)) ```
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()) l = [i for i in range(1, n+1) if i%2!=0]+[i for i in range(1, n+1) if i%2==0] for i in range(n): try: if l[i]+1 == l[i+1] or l[i]-1 == l[i+1]: l.remove(l[i+1]) except IndexError: break print(len(l)) print(*l) ```
MatrixStudio/Codeforces-Python-Submissions
Stepan has a very big positive integer. Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020. Stepan wants to know the minimum remainder of the division by the given number *m* among all good shifts. Your task is to determine the minimum remainder of the division by *m*.
```python s = input() m = int(input()) n = len(s) s = s + s pot = [] pot.append(1) for i in range(1, 200000): pot.append((pot[i - 1] * 10) % m) cur = 0 mn = 1000000000 for i in range(0, 2 * n - 1): cur = (cur * 10 + ord(s[i]) - ord('0')) % m if i >= n: cur = (cur - (pot[n] * (ord(s[i]) - ord('0'))) % m + m) % m if i >= n - 1 and s[i - (n - 1)] != '0': mn = min(mn, cur) print(mn) ```
MatrixStudio/Codeforces-Python-Submissions
Hands that shed innocent blood! There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=&lt;<=*i* and *j*<=≥<=*i*<=-<=*L**i*. You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
```python test = 1 #test = int(input()) for _ in range(test): n = int(input()) l = list(map(int,input().split())) x = 1 k = n-1 - l[n-1] ind = n-2 while ind >= 0: if k > ind: x+=1 k = min(k,ind-l[ind]) ind-=1 print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Mr Keks is a typical white-collar in Byteland. He has a bookshelf in his office with some books on it, each book has an integer positive price. Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office. He learned that in the new office he will have not a single bookshelf, but exactly $k$ bookshelves. He decided that the beauty of the $k$ shelves is the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of the values of all the shelves. He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $k$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
```python #!/usr/bin/python3.7 import sys n, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] cur = 0 def is_submask(n, mask): return (n & mask) == mask def f(mask): s = [[False for j in range(n)] for i in range(n)] for l in range(n): cur = 0 for r in range(l, n): cur += a[r] s[l][r] = is_submask(cur, mask) dp = [[False for j in range(n)] for i in range(k)] dp[0] = s[0][:] for k1 in range(1, k): for r in range(n): for l in range(1, r + 1): dp[k1][r] |= dp[k1 - 1][l - 1] & s[l][r] return dp[k - 1][n - 1] cur = 0 for i in range(50, -1, -1): if f(cur + 2 ** i): cur += 2 ** i print(cur) ```
MatrixStudio/Codeforces-Python-Submissions
In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number *i* has price *p**i*, direction *d**i* — buy or sell, and integer *q**i*. This means that the participant is ready to buy or sell *q**i* stocks at price *p**i* for one stock. A value *q**i* is also known as a volume of an order. All orders with the same price *p* and direction *d* are merged into one aggregated order with price *p* and direction *d*. The volume of such order is a sum of volumes of the initial orders. An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order. An order book of depth *s* contains *s* best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than *s* aggregated orders for some direction then all of them will be in the final order book. You are given *n* stock exhange orders. Your task is to print order book of depth *s* for these orders.
```python n, s = list(map(int, input().split())) B = [] S = [] for i in range(n): st = list(input().split()) st[1], st[2] = int(st[1]), int(st[2]) if st[0] == 'B': B.append(st) else: S.append(st) B.sort() S.sort() i = 0 while i < len(B) - 1: if B[i][1] == B[i + 1][1]: B[i][2] += B[i + 1][2] del(B[i + 1]) else: i += 1 i = 0 while i < len(S) - 1: if S[i][1] == S[i + 1][1]: S[i][2] += S[i + 1][2] del(S[i + 1]) else: i += 1 B.reverse() for i in range(min(s, len(S))): print(*S[i]) for i in range(min(s, len(B))): print(*B[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of *n* integers. A sequence *a*1, *a*2, ..., *a**n*, consisting of *n* integers, is Hungry if and only if: - Its elements are in increasing order. That is an inequality *a**i*<=&lt;<=*a**j* holds for any two indices *i*,<=*j* (*i*<=&lt;<=*j*). - For any two indices *i* and *j* (*i*<=&lt;<=*j*), *a**j* must not be divisible by *a**i*. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with *n* elements.
```python from queue import PriorityQueue def isPrime(n): if(n==1 or n==0): return False for i in range(2,int(n**(1/2))+1): if(n%i==0): return False return True count = int(input()) s = '' for i in range(1, 100000000): if count == 0: break if(isPrime(i)): s = s+ str(i) + ' ' count -= 1 print(s.strip()) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel has *n* boxes in her room. They have the same size and weight, but they might have different strength. The *i*-th box can hold at most *x**i* boxes on its top (we'll call *x**i* the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile. Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than *x**i* boxes on the top of *i*-th box. What is the minimal number of piles she needs to construct?
```python n = int(input()) a = list(map(int,input().split())) a.sort() s=[] for i in range(n): s.sort(reverse = True) for j in range(len(s)): if i >= s[j]: s[j] += 1 break else: s.append(1) print(len(s)) ```
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
```python pos = int(input()) if pos % 5 == 0: steps = int(pos/5) print(steps) else: min = int(pos/5) stepss = min+1 print(stepss) ```
MatrixStudio/Codeforces-Python-Submissions
You've got an array *a*, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a minimal by inclusion segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such, that among numbers *a**l*,<= *a**l*<=+<=1,<= ...,<= *a**r* there are exactly *k* distinct numbers. Segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*; *l*,<=*r* are integers) of length *m*<==<=*r*<=-<=*l*<=+<=1, satisfying the given property, is called minimal by inclusion, if there is no segment [*x*,<=*y*] satisfying the property and less then *m* in length, such that 1<=≤<=*l*<=≤<=*x*<=≤<=*y*<=≤<=*r*<=≤<=*n*. Note that the segment [*l*,<=*r*] doesn't have to be minimal in length among all segments, satisfying the given property.
```python n, k = map(int, input().split()) a = [0] + list(map(int, input().split())) freq = [0] * (100001) dist = 0 for i in range(1, n+1): if freq[a[i]] == 0: dist += 1 freq[a[i]] += 1 l = 1 r = n if dist < k: print(-1, -1) else: while dist >= k: freq[a[r]] -= 1 if freq[a[r]] == 0: dist -= 1 r -= 1 r += 1 dist += 1 while dist >= k: freq[a[l]] -= 1 if freq[a[l]] == 0: dist -= 1 l += 1 l -= 1 print(l, r) ```
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()) faces = [] default = {1,2,3,4,5,6} for i in range(n): raw = set(map(int, input().split())) impr = set() for v in raw: impr.add(v) impr.add(7-v) if i == 0: impr.add(x) faces.append(default - impr) i = 1 if n == 1: print("YES") exit() faces[1] = faces[1] - faces[0] if len(faces[1]) == 2: print("NO") exit() i = 2 while i < n: exc = faces[i] - faces[i-1] if len(exc) == 0: print("NO") exit() i += 1 print("YES") ```
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 # -*- coding: utf-8 -*- """ Created on Thu Oct 5 23:07:21 2023 @author: risha """ s1=list(input().lower()) s2=list(input().lower()) c=0 for i in range(len(s1)): if s1[i]==s2[i]: c=1 else: if s1[i]<s2[i]: print("-1") elif s1[i]>s2[i]: print("1") c=0 break if c==1: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go. Dr. Evil is interested in sets, He has a set of *n* integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly *x*. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0,<=2,<=4} is 1 and the MEX of the set {1,<=2,<=3} is 0 . Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?
```python n, m = map(int,input().split()) l = list(map(int,input().split())) c = 0 for i in l : if i < m : c = c + 1 if m in l : print(abs(m - c) + 1 ) else: print(abs(m - c) ) ```
MatrixStudio/Codeforces-Python-Submissions
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to *n* (*n*<=≥<=2) burles and the amount of tax he has to pay is calculated as the maximum divisor of *n* (not equal to *n*, of course). For example, if *n*<==<=6 then Funt has to pay 3 burles, while for *n*<==<=25 he needs to pay 5 and if *n*<==<=2 he pays only 1 burle. As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial *n* in several parts *n*1<=+<=*n*2<=+<=...<=+<=*n**k*<==<=*n* (here *k* is arbitrary, even *k*<==<=1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition *n**i*<=≥<=2 should hold for all *i* from 1 to *k*. Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split *n* in parts.
```python from sys import exit n=int(input()) i=2 while i*i<=n: if n%i==0: if n%2==0: print(2) else: print(3) exit() i+=1 print(1) ```
MatrixStudio/Codeforces-Python-Submissions
You've got a string *s*<==<=*s*1*s*2... *s*|*s*| of length |*s*|, consisting of lowercase English letters. There also are *q* queries, each query is described by two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=|*s*|). The answer to the query is the number of substrings of string *s*[*l**i*... *r**i*], which are palindromes. String *s*[*l*... *r*]<==<=*s**l**s**l*<=+<=1... *s**r* (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) is a substring of string *s*<==<=*s*1*s*2... *s*|*s*|. String *t* is called a palindrome, if it reads the same from left to right and from right to left. Formally, if *t*<==<=*t*1*t*2... *t*|*t*|<==<=*t*|*t*|*t*|*t*|<=-<=1... *t*1.
```python from array import array from sys import stdin ,stdout ,setrecursionlimit from threading import stack_size , Thread setrecursionlimit(2**31-1) input=stdin.readline def print(*args, end='\n', sep=' ') -> None: stdout.write(sep.join(map(str, args)) + end) def palindrome(lef , righ): while (lef<=righ): if (st[lef]!=st[righ]):return 0 lef+=1 righ-=1 return 1 def dp(ind ,last): if ind==lenth:return if (last,ind) in mem :return mem[(last,ind)]=palindrome(last , ind) dp(ind+1,ind+1) if ind!=lenth-1: dp(ind+1 , last ) st=input().strip() ; lenth=len(st) ; mem={} def solve(): dp(0,0) for i in range(lenth): for j in range(i,lenth): if j==i :continue mem[(i,j)]+=mem[(i,j-1 )] for i in range(lenth): for j in range(1,i+1): mem[(j,i)]+=mem[(j-1,i)] for _ in range(int(input())): l,r=map(int,input().split()) l-=1 ; r-=1 if (l==0): print(mem[(r,r)]) else: print(mem[(r,r)]-mem[(l-1,r)]) stack_size(10**8) Thread(target=solve).start() ```
MatrixStudio/Codeforces-Python-Submissions
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it holds exactly *n* lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks). The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the *n* pairs she knows if there will be a class at that time or not. Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university. Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home. Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.
```python n = int(input('')) classes = input('').split(' ') #stay = '1 0 1' count = 0 for j in range(n-2): if((classes[j] == '1') and (classes[j+1] == '0') and (classes[j+2] == '1')): count = count + 1 print (count + classes.count('1')) ```
MatrixStudio/Codeforces-Python-Submissions
Only *T* milliseconds left before the start of well-known online programming contest Codehorses Round 2017. Polycarp needs to download B++ compiler to take part in the contest. The size of the file is *f* bytes. Polycarp's internet tariff allows to download data at the rate of one byte per *t*0 milliseconds. This tariff is already prepaid, and its use does not incur any expense for Polycarp. In addition, the Internet service provider offers two additional packages: - download *a*1 bytes at the rate of one byte per *t*1 milliseconds, paying *p*1 burles for the package; - download *a*2 bytes at the rate of one byte per *t*2 milliseconds, paying *p*2 burles for the package. Polycarp can buy any package many times. When buying a package, its price (*p*1 or *p*2) is prepaid before usage. Once a package is bought it replaces the regular tariff until package data limit is completely used. After a package is consumed Polycarp can immediately buy a new package or switch to the regular tariff without loosing any time. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff. Find the minimum amount of money Polycarp has to spend to download an *f* bytes file no more than in *T* milliseconds. Note that because of technical reasons Polycarp can download only integer number of bytes using regular tariff and both packages. I.e. in each of three downloading modes the number of downloaded bytes will be integer. It means that Polycarp can't download a byte partially using the regular tariff or/and both packages.
```python f, T, t0 = map(int, input().split()) a1, t1, p1= map(int, input().split()) a2, t2, p2= map(int, input().split()) def check(x, y): global f,T,t0,a1,t1,p1,a2,t2,p2 z = f - x*a1-y*a2 temp = x*a1*t1 + y*a2*t2 + z*t0 if temp<=T: return p1*x + p2*y return 1000000000000000004 k = min(t0,min(t1,t2)) if(f*k>T): print(-1) elif f*t0 <= T: print(0) else: u1 = a1*t1 - a1*t0 u2 = a2*t2 - a2*t0 j = T - t0*f val = 1000000000000000004 if(u1>=0): s = j if(s%u2==0): s//=u2 val= min(val,check(0, s)) else: s//=u2 val= min(val,check(0, s)) s+=1 val= min(val,check(0, s)) elif(u2>=0): s = j if(s%u1==0): s//=u1 val= min(val,check(s, 0)) else: s//=u1 val= min(val,check(s, 0)) s+=1 val= min(val,check(s, 0)) else: for x in range(0, 10000001): s = j - x*u1 if(s%u2==0): s//=u2 else: s//=u2 s+=1 if(s<0): break val= min(val,check(x, s)) for x in range(0, 10000001): s = j - x*u2 if(s%u1==0): s/=u1 else: s//=u1 s+=1 if(s<0): break val= min(val,check(s,x)) if(val==1000000000000000004): print(-1) else: print(val) ```
MatrixStudio/Codeforces-Python-Submissions
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one. The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
```python n,b,d = map(int,input().split()) s = list(map(int,input().split())) v = 0 ot = 0 for i in range(n): if s[i] <= b: v += s[i] if v > d: ot += 1 v = 0 if v > d: ot += 1 print(ot) ```
MatrixStudio/Codeforces-Python-Submissions
We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.
```python def truee(): l=sum(map(int,str(j))) if l==10: return 1 return 0 n=int(input()) j=19 k=1 while k!=n: j+=9 if truee()==1: k+=1 print(j) ```
MatrixStudio/Codeforces-Python-Submissions
Mr. Kitayuta has just bought an undirected graph consisting of *n* vertices and *m* edges. The vertices of the graph are numbered from 1 to *n*. Each edge, namely edge *i*, has a color *c**i*, connecting vertex *a**i* and *b**i*. Mr. Kitayuta wants you to process the following *q* queries. In the *i*-th query, he gives you two integers — *u**i* and *v**i*. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex *u**i* and vertex *v**i* directly or indirectly.
```python from collections import defaultdict def dfs(adjlist, start, visited, color): if start in visited: return for (v,c) in adjlist[start]: if c == color: visited.add(start) visited.add(v) dfs(adjlist, v, visited, color) if __name__ =='__main__': n,m = map(int, input().split()) adjlist = defaultdict(list) all_color = set() for i in range(0,m): tmp = list(map(int, input().split())) adjlist[tmp[0]].append((tmp[1],tmp[2])) adjlist[tmp[1]].append((tmp[0],tmp[2])) all_color.add(tmp[2]) num_queries = int(input()) queries = [] for i in range(0,num_queries): queries.append(list(map(int, input().split()))) color_map = {} for c in all_color: visited = set() for src in range(1,n+1): dfs(adjlist, src, visited, c) color_map[c] = visited for q in queries: count = 0 for c in all_color: if q[0] in color_map[c] and q[1] in color_map[c]: count += 1 print(count) ```
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()) mod = 10**9 +7 def power_2_k(k): if k == 0: return 1 if k % 2 == 0: lower = power_2_k(k // 2) return (lower * lower) % mod else: k -= 1 lower = power_2_k(k // 2) return (((lower * lower) % mod) * 2) % mod p = power_2_k(n) print((p * (p + 1) // 2) % mod) ```
MatrixStudio/Codeforces-Python-Submissions
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=&gt;<=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency). The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer? The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
```python n, m = map(int, input().split()) seats = sorted([int(x) for x in input().split()]) seatsc = [s for s in seats] if n >= sum(seats): sm = sum([(x * (x + 1)) // 2 for x in seats]) print(sm, sm) else: pc = 0 mncost = 0 mxcost = 0 while pc < n: ind = seats.index(max(seats)) mxcost += seats[ind] seats[ind] -= 1 pc += 1 pc = 0 while pc < n: ind = seatsc.index(min(seatsc)) mncost += seatsc[ind] seatsc[ind] -= 1 if seatsc[ind] == 0: seatsc.pop(ind) pc += 1 print(mxcost,mncost) ```
MatrixStudio/Codeforces-Python-Submissions
The prison of your city has *n* prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer *c* of the prisoners to a prison located in another city. For this reason, he made the *n* prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was. Then, the mayor told you to choose the *c* prisoners, who will be transferred to the other prison. He also imposed two conditions. They are, - The chosen *c* prisoners has to form a contiguous segment of prisoners. - Any of the chosen prisoner's crime level should not be greater then *t*. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the *c* prisoners.
```python n=list(map(int,input().split())) k=list(map(int,input().split())) c2=0 way=0 for i in k: if i<=n[1]: c2+=1 else: c2=0 if c2>n[2]: way+=1 print(way) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph *G* is given. Subset *A* of its vertices is called a vertex cover of this graph, if for each edge *uv* there is at least one endpoint of it in this set, i.e. or (or both). Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover. They have agreed to give you their graph and you need to find two disjoint subsets of its vertices *A* and *B*, such that both *A* and *B* are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).
```python nVertices, nEdges = map(int, input().split()) g = [[] for _ in range(nVertices)] edges = [] for _ in range(nEdges): u, v = map(lambda x: int(x) - 1, input().split()) g[u].append(v) g[v].append(u) edges.append((u, v)) def dfs(v, m): mark[v] = m for to in g[v]: if not mark[to]: dfs(to, m ^ 1) mark = [None] * nVertices for v in range(nVertices): if not mark[v]: dfs(v, 0) cnt1 = cnt2 = 0 for u, v in edges: cnt1 += mark[u] == 0 or mark[v] == 0 cnt2 += mark[u] == 1 or mark[v] == 1 if cnt1 != nEdges or cnt2 != nEdges: print(-1) else: ret = [] ret.append('%d\n' % mark.count(0)) vertices = [] for v in range(nVertices): if mark[v] == 0: vertices.append(v + 1) ret.append('%s\n' % ' '.join(map(str, vertices))) ret.append('%d\n' % mark.count(1)) vertices = [] for v in range(nVertices): if mark[v] == 1: vertices.append(v + 1) ret.append('%s\n' % ' '.join(map(str, vertices))) print(''.join(ret)) ```
MatrixStudio/Codeforces-Python-Submissions
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings *a* and *b*, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other. A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
```python a=input() b=input() if any(i not in iter(a) for i in b): print(max(len(b),len(a))) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important. For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong. Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
```python n = int(input()) heights = list(map(int, input().split())) position_max = -1 position_min = -1 # Find the positions of maximum and minimum heights for i in range(n): if heights[i] == max(heights): position_max = i if heights[i] == min(heights): position_min = i # Calculate the minimum number of swaps needed if position_max > position_min: min_swaps = position_max + (n - 1 - position_min) - 1 else: min_swaps = position_max + (n - 1 - position_min) print(min_swaps) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section. Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1<=×<=5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture: As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.
```python n = int(input()) arr = list(map(int, input().split())) def rain(arr,n, index): counter = 1 lindex = index - 1 rindex = index + 1 currentL = arr[index] currentR = arr[index] while(lindex >= 0): if arr[lindex] <= currentL: counter += 1 currentL = arr[lindex] lindex -= 1 else: break while(rindex < n): if arr[rindex] <= currentR: counter += 1 currentR = arr[rindex] rindex += 1 else: break return counter max_rain = rain(arr,n, 0) for i in range(1,n): r = rain(arr,n, i) if r > max_rain: max_rain = r print(max_rain) ```
MatrixStudio/Codeforces-Python-Submissions
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
```python a,b=input().split() a=int(a) b=int(b) l=[] for i in range(a): if i!=0: print(*l) l=[] for j in range(a): if j==0:l.append(b) else:l.append(0) print(*l) ```
MatrixStudio/Codeforces-Python-Submissions
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: - Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks. Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.
```python ssticks = list() ssticks[:] = map(int,input().split(' ')) ssticks.sort() ssdict = dict() for i in ssticks: ssdict[i] = 0 for i in ssticks: ssdict[i] += 1 ssticks = [] for k in ssdict: ssticks.append(ssdict[k]) if ssticks.count(4) > 0: if ssticks.count(2) > 0: print('Elephant') else: print('Bear') else: print('Alien') ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to *a*1,<=*a*2,<=...,<=*a**n*. While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to *b*1,<=*b*2,<=...,<=*b**n*. Stepan said that he swapped only cubes which where on the positions between *l* and *r*, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions *l* and *r*, inclusive, in some way). Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.
```python import sys n,l,r=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) for il in range(0,l): for ir in range(r,n): if a[il]==b[il] and a[ir]==b[ir]: print('TRUTH') exit() else: print('LIE') exit() ```
MatrixStudio/Codeforces-Python-Submissions
Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible! Your task is to write a program which calculates two things: 1. The maximum beauty difference of flowers that Pashmak can give to Parmida. 1. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.
```python from collections import Counter n=int(input()) b=list(map(int,input().split())) cnt=Counter(b) lst=list(cnt) l,r=lst[0],lst[-1] print(cnt[r]-cnt[l],cnt[r]*cnt[l]) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
```python n=int(input()) a=list(map(int,input().split(' '))) for i in range(n): if a[0]%2!=a[1]%2 and a[0]%2!=a[2]%2: print('0') break if a[i]%2!=a[i+1]%2 and a[i]%2!=a[i-1]%2: print(i+1) break ```
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 q=[int(a)for a in input().split()] w=[int(a)for a in input().split()] e=1 if q[0]>1: for r in range(1,len(w)): if w[r]-w[r-1]>q[1]: e=1 else: e+=1 print(e) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Kolya has a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits. He wants to rearrange the symbols in *s* and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar. Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut *s* into, if it is allowed to rearrange letters in *s* before cuttings.
```python mp,a,p={},[],[] n=int(input()) for i in input(): if i in mp:mp[i]+=1 else:mp[i]=1 odd=0 for i in mp: if mp[i]&1: a.append(i) mp[i]-=1 odd+=1 if mp[i]: p.append(i) m=max(1,odd) for i in range(m,n+1): if not n%i: d=n//i if odd and not d&1:continue print(i) for K in range(i-m): a.append(p[-1]) if mp[p[-1]]>1:mp[p[-1]]-=1 else:p.pop() for k in range(i): s='' for j in range(d//2): s+=p[-1] mp[p[-1]]-=2 if not mp[p[-1]]:p.pop() if odd:print(s+a.pop()+s[::-1],end=' ') else:print(s+s[::-1],end=' ') exit() ```
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=list(map(int, input().split())) distress=0 for i in range(n): query=input().split() if query[0]=='+': x+=int(query[1]) else: if x>=int(query[1]): x-=int(query[1]) else: distress+=1 print(x, distress) ```
MatrixStudio/Codeforces-Python-Submissions
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system. You are given user's friends' opinions about a list of items. You are also given a threshold *T* — the minimal number of "likes" necessary for an item to be recommended to the user. Output the number of items in the list liked by at least *T* of user's friends.
```python n, m, t = map(int,raw_input().strip().split()) x = [] for i in xrange(n): x.append(raw_input().strip()) print sum([sum([x[i][j] == 'Y' for i in xrange(n)]) >= t for j in xrange(m)]) ```
MatrixStudio/Codeforces-Python-Submissions
Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point *m* on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport. Formally, a teleport located at point *x* with limit *y* can move Pig from point *x* to any point within the segment [*x*;<=*y*], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car.
```python n, m = map(int, input().split()) a = [] for i in range(m): a.append(False) a[0] = True for _ in range(n): x, y = map(int, input().split()) for i in range(x,y): a[i] = True if False in a: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has *n* lanterns and Big Banban has *m* lanterns. Tommy's lanterns have brightness *a*1,<=*a*2,<=...,<=*a**n*, and Banban's have brightness *b*1,<=*b*2,<=...,<=*b**m* respectively. Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns. Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible. You are asked to find the brightness of the chosen pair if both of them choose optimally.
```python i,j=map(int,input().split()) li=list(map(int,input().split())) li.sort() lj=list(map(int,input().split())) lj.sort() print(li[i-2]*lj[j-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
```python #rOkY #FuCk ################################## kOpAl ##################################### t=int(input()) l=list(map(int,input().split())) l.sort() x=list(dict.fromkeys(l)) if(len(x)>1): print(x[1]) 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()) a1 = a b1 = b n1 = n count = 0 c = 0 while c != n: d = n1 - c while d > 0: a, d = d, a % d c += a a = a1 b = b1 a, b = b, a count += 1 if count % 2 == 0: print(1) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
```python import sys def I(): return int(sys.stdin.readline().rstrip()) def LI(): return list(map(int, sys.stdin.readline().rstrip().split())) def MI(): return map(int, sys.stdin.readline().rstrip().split()) def SI(): return sys.stdin.readline().rstrip() def main(): n = I() count = 0 while n > 0: if n > 5: count += 1 n -= 5 else: count += 1 n -= n print(count) if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
Petya has got 2*n* cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2*n*. We'll denote the number that is written on a card with number *i*, as *a**i*. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
```python import re import sys exit=sys.exit from bisect import bisect_left as bsl,bisect_right as bsr from collections import Counter,defaultdict as ddict,deque from functools import lru_cache cache=lru_cache(None) from heapq import * from itertools import * from math import inf from pprint import pprint as pp enum=enumerate ri=lambda:int(rln()) ris=lambda:list(map(int,rfs())) rln=sys.stdin.readline rl=lambda:rln().rstrip('\n') rfs=lambda:rln().split() cat=''.join catn='\n'.join mod=1000000007 d4=[(0,-1),(1,0),(0,1),(-1,0)] d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)] ######################################################################## n=ri() a=ris() d=ddict(set) for i in range(2*n): d[a[i]].add(i) ans=[] for x in d: if len(d[x])%2: print(-1) exit() while d[x]: j=d[x].pop() i=d[x].pop() ans.append((i,j)) for i,j in ans: print(1+i,1+j) ```
MatrixStudio/Codeforces-Python-Submissions
A median in an array with the length of *n* is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2,<=6,<=1,<=2,<=3) is the number 2, and a median of array (0,<=96,<=17,<=23) — the number 17. We define an expression as the integer part of dividing number *a* by number *b*. One day Vasya showed Petya an array consisting of *n* integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals *x*. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to *x*. Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
```python """ Module which implements the search of the minimum number of elements to be inserted in order to make the given number the median of this array. """ def min_num(positions: list, length: int, count: int): """ Return the minimum number of elements. """ result = count if ((length+1) // 2 - 1) in positions: return result if positions[-1] < ((length+1) // 2 - 1): while positions[-1] != ((length+1) // 2 - 1): result += 1 positions[-1] += 1 length += 1 if positions[0] > ((length+1) // 2 - 1): while positions[0] != ((length+1) // 2 - 1): result += 1 length += 1 return result if __name__ == "__main__": settings = [int(x) for x in input().split(" ")] array = [int(x) for x in input().split(" ")] count = 0 if settings[1] not in array: array.append(settings[1]) count += 1 settings[0] += 1 array.sort() positions = [] for i in range(len(array)): if array[i] == settings[1]: positions.append(i) print(min_num(positions, settings[0], count)) ```
MatrixStudio/Codeforces-Python-Submissions
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order. Help Kefa cope with this task!
```python n=int(input()) sub=[] seq=list (map (int , input().split())) s=1 for i in range(1,len(seq)): if seq[i]>=seq[i-1]: s=s+1 else: sub.append(s) s=1 sub.append(s) print(max(sub)) ```
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 input() x = input().split('W') y= [len(i) for i in x if len(i)>0] print(len(y)) print(*y) ```
MatrixStudio/Codeforces-Python-Submissions
You have an array *a* consisting of *n* integers. Each integer from 1 to *n* appears exactly once in this array. For some indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1) it is possible to swap *i*-th element with (*i*<=+<=1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap *i*-th element with (*i*<=+<=1)-th (if the position is not forbidden). Can you make this array sorted in ascending order performing some sequence of swapping operations?
```python R = lambda:map(int,input().split()) n = int(input()) C = list(R()) s = input() tt = 0 for i in range(n - 1): if C[i] > C[i + 1]: if s[i] == '0': print("no") tt = 1 break else: t = i while t >= 0 and C[t] > C[t + 1] and s[t] == '1': C[t + 1], C[t] = C[t], C[t + 1] t -= 1 if C[t] > C[t + 1]: print("no") tt = 1 break f = [i for i in range(1,n + 1)] if tt == 0: if f == C: print("yes") else: print("no") ```
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 n1=(input("Enter a word : ")) u=0 l=0 for i in n1: if 65<=ord(i)<=90: u+=1 else: l+=1 if u>l: print(n1.upper()) else: print(n1.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers *a*, *b*, *c*, *d* on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
```python import itertools import math import time from builtins import input, range from math import gcd as gcd import sys import queue import itertools import collections from heapq import heappop, heappush import random import os from random import randint import decimal # from sys import stdin, stdout # input, print = stdin.readline, stdout.write decimal.getcontext().prec = 18 def solve(): def rec(op, arr): mn = 1 << 60 for f in range(len(arr)): for s in range(f + 1, len(arr)): if len(arr) == 2: if op == "+": return arr[f] + arr[s] else: return arr[f] * arr[s] new_arr = arr * 1 new_arr.remove(arr[f]) new_arr.remove(arr[s]) if op == "+": new_arr.append(arr[f] + arr[s]) else: new_arr.append(arr[f] * arr[s]) mn = min(mn, rec(ops[4 - len(arr) + 1], new_arr)) return mn a = list(map(int, input().split())) ops = list(map(str, input().split())) print(rec(ops[0], a)) if __name__ == '__main__': multi_test = 0 if multi_test == 1: t = int(sys.stdin.readline()) for _ in range(t): solve() else: solve() ```
MatrixStudio/Codeforces-Python-Submissions
DZY loves chemistry, and he enjoys mixing chemicals. DZY has *n* chemicals, and *m* pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is. Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
```python def get(Array, Item): if Array[Item] == Item: return Item Array[Item] = get(Array, Array[Item]); return Array[Item] n ,m = map(int , input().split(' ')) chem = [i for i in range(1+n)] ans = 0 rank = [1]*(n+1) for _ in range(m): a, b = map(int , input().split(' ')) chem[get(chem , a)] = get(chem , b) rec = [0]*(n+1) for x in chem: rec[get(chem ,x)]+= 1 for x in rec: if x > 1: ans+=(x-1) print(2**ans) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field *n*<=×<=*m* in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot *a*<=×<=*b* squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.
```python def calc_trees(cont: list, start_row: int, start_col: int, area_h, area_w) -> int: trees = 0 for i in range(start_row, start_row + area_h): for j in range(start_col, start_col + area_w): trees += cont[i][j] n, m = [int(item) for item in input().split(' ')] cont = [] for i in range(n): # subArr = [int(item) for item in input().split(' ')] # cont.append(subArr) cont.append([int(item) for item in input().split(' ')]) a, b = [int(item) for item in input().split(' ')] # print(f'cont => {cont}') ans = n * m for i in range(n): for j in range(m): if i <= n - a and j <= m - b: temp = calc_trees(cont, i, j, a, b) if ans > temp: ans = temp if i <= n - b and j <= m - a: temp = calc_trees(cont, i, j, b, a) if ans > temp: ans = temp print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A tennis tournament with *n* participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out. The tournament takes place in the following way (below, *m* is the number of the participants of the current round): - let *k* be the maximal power of the number 2 such that *k*<=≤<=*m*, - *k* participants compete in the current round and a half of them passes to the next round, the other *m*<=-<=*k* participants pass to the next round directly, - when only one participant remains, the tournament finishes. Each match requires *b* bottles of water for each participant and one bottle for the judge. Besides *p* towels are given to each participant for the whole tournament. Find the number of bottles and towels needed for the tournament. Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).
```python n,b,p = [int(c) for c in input().split()] print((n-1)*(2*b+1), n*p) ```
MatrixStudio/Codeforces-Python-Submissions
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering. Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance. Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with $n$ vertices. Hag brought two pins and pinned the polygon with them in the $1$-st and $2$-nd vertices to the wall. His dad has $q$ queries to Hag of two types. - $1$ $f$ $t$: pull a pin from the vertex $f$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $t$. - $2$ $v$: answer what are the coordinates of the vertex $v$. Please help Hag to answer his father's queries. You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.
```python #!/usr/bin/env python3 from math import hypot [n, q] = map(int, input().strip().split()) xys = [tuple(map(int, input().strip().split())) for _ in range(n)] qis = [tuple(map(int, input().strip().split())) for _ in range(q)] dxys = [(xys[(i + 1) % n][0] - xys[i][0], xys[(i + 1) % n][1] - xys[i][1]) for i in range(n)] S = 3 * sum((x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys)) Sx = sum((dx + 2*x) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys)) Sy = sum((dy + 2*y) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys)) #Sy = sum((2*dx*dy + 3*x*dx + 3*x*dy + 6*x*y)*dy for (x, y), (dx, dy) in zip(xys, dxys)) for p in [2, 3]: while S % p == Sx % p == Sy % p == 0: S //= p Sx //= p Sy //= p xyms = [(S*x - Sx, S*y - Sy) for x, y in xys] hs = [hypot(x, y) for x, y in xyms] def to_coord(x, y): return (x + Sx) / S, (y + Sy) / S hangs = (0, 1) hang_on = None cx, cy = 0.0, 0.0 # hang on u def get_v(v): if hang_on is None: return xyms[v] else: ux, uy = xyms[hang_on] vx, vy = xyms[v] h = hs[hang_on] return ((uy * vx - ux * vy) / h, (ux * vx + uy * vy) / h) #def ss(v1, v2): # return tuple(vi + vj for vi, vj in zip(v1, v2)) #def disp(): # print ('hangs on', hang_on, 'of', hangs) # print ('center', to_coord(cx, cy)) # print ({i: to_coord(*ss(get_v(i), (cx, cy))) for i in range(n)}) #disp() for qi in qis: if qi[0] == 1: _, f, t = qi # 1-indexation s = hangs[1 - hangs.index(f - 1)] dx, dy = get_v(s) cx += dx cy += dy - hs[s] hang_on = s hangs = (s, t - 1) # print ('{} --> {}'.format(f - 1, t - 1)) # disp() else: _, v = qi # 1-indexation dx, dy = get_v(v - 1) print (*to_coord(cx + dx, cy + dy)) ```
MatrixStudio/Codeforces-Python-Submissions
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: 1. the number of good substrings of even length; 1. the number of good substrings of odd length.
```python s=input() ans_odd=0 ans_even=0 cnt_odd=[0,0] cnt_even=[0,0] for i in range(len(s)): id=ord(s[i])-ord("a") ans_odd+=1 if i%2==0: ans_even+=cnt_odd[id] ans_odd+=cnt_even[id] cnt_even[id]+=1 else: ans_odd+=cnt_odd[id] ans_even+=cnt_even[id] cnt_odd[id]+=1 print(ans_even,ans_odd) ```
MatrixStudio/Codeforces-Python-Submissions
One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all. The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*.
```python n, k = map(int, input().split()) result = 51 def dfs(remain_exams: int, slate: list): global result if remain_exams == 0: if sum(slate) == k: num_2 = len([score for score in slate if score == 2]) if num_2 < result: result = num_2 else: for i in range(2, 6): slate.append(i) dfs(remain_exams - 1, slate) slate.pop() dfs(n, []) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has *n* cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
```python needs_flipping = ['a', 'e', 'i', 'o', 'u', '1', '3', '5', '7', '9'] def flip(s): flip_count = 0 for letter in s: if letter in needs_flipping: flip_count += 1 return flip_count print(flip(input())) ```
MatrixStudio/Codeforces-Python-Submissions
Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, firstly, was not gerater than *n*, and, secondly, was divisible by *k*. Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.
```python def solver(y, k, n): x = n - y ans = [] for i in range(0,x): if (y+i+1) % k == 0: ans.append(str(i+1)) return '-1' if ans == [] else ' '.join(ans) if __name__ == "__main__": y, k, n = map(int, input().split(" ")) print(solver(y, k, n)) ```
MatrixStudio/Codeforces-Python-Submissions
Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant. The warehouse has $m$ daily food packages. Each package has some food type $a_i$. Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food. Formally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different. What is the maximum possible number of days the expedition can last, following the requirements above?
```python def get_longest(left_num, cur_depth, max_depth): if(cur_depth == max_depth): if left_num == 0: return 9999999 else: return int(food_dict[sorted_food_key[max_depth - 1]] / left_num) else: cur_long = 0 for i in range(0, left_num + 1): if i == 0: this_food_alive = 9999999 else: this_food_alive = int(food_dict[sorted_food_key[cur_depth - 1]] / i) next_food_alive = get_longest(left_num - i, cur_depth + 1, max_depth) min_val = min(next_food_alive, this_food_alive) cur_long = max(min_val, cur_long) return cur_long input_list = list(map(int, input().split())) foods = list(map(int, input().split())) particip_count = input_list[0] package_count = input_list[1] if package_count < particip_count: print(0) else: food_dict = dict() for food in foods: if food in food_dict: food_dict[food] = food_dict[food] + 1 else: food_dict[food] = 1 sorted_food_key = sorted(food_dict, key=lambda food: food_dict[food], reverse=True) if particip_count < len(sorted_food_key): sorted_food_key = sorted_food_key[:particip_count] elif particip_count > len(sorted_food_key): key_offset = 1 while particip_count > len(food_dict): food_dict[999 + key_offset] = 0 key_offset = key_offset + 1 sorted_food_key = sorted(food_dict, key=lambda food: food_dict[food], reverse=True) else: key_offset = 1 print(get_longest(particip_count, 1, particip_count)); ```
MatrixStudio/Codeforces-Python-Submissions
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has *n* students. Dean's office allows *i*-th student to use the segment (*l**i*,<=*r**i*) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students! Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (*n*<=-<=1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.
```python import numpy as np num_of_student = int(input()) sush = list() for i in range(0, num_of_student): inp = input() inp_spl = inp.split(" ") sush.append(int(inp_spl[0])) sush.append(int(inp_spl[1])) one_range = np.zeros((np.max(sush)+1,)) for i in range(0, num_of_student*2, 2): one_range[sush[i]:sush[i+1]] = i+1 count = 0 for i in one_range: if i == 1: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*. You have a sequence of integers *a*1,<=*a*2,<=...,<=*a**n*. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
```python t = int(input()) res = 0 s = sorted(list(map(int, input().split()))) for i in range(0, t): res+=abs(i+1 - s[i]) print(res) ```
MatrixStudio/Codeforces-Python-Submissions
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person. The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left. All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?
```python import sys cache = {} def max_possible(pie_slices, current_slice): if current_slice in cache: return cache[current_slice] if len(pie_slices) - 1 == current_slice: return pie_slices[current_slice] opp = pie_slices[current_slice] for cs in range(current_slice + 1, len(pie_slices)): c1 = max_possible(pie_slices, cs) if opp > c1: return opp opp += pie_slices[cs] return pie_slices[current_slice] + sum(pie_slices[current_slice + 1:]) - max_possible(pie_slices, current_slice + 1) def main(): n = int(sys.stdin.readline().strip()) pie_slices = [int(tok) for tok in sys.stdin.readline().strip().split()] b = max_possible(pie_slices, 0) print(sum(pie_slices) - b, b) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights. Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible. Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
```python n,k=map(int,input().split()) h=list(map(int,input().split())) j_min=sum(h[0:k]) j=0 for i in range(1,n-k): p=j_min-h[i-1]+h[i+k] if p<j_min: j_min=p j=i print(j) ```
MatrixStudio/Codeforces-Python-Submissions
An infinitely long railway has a train consisting of *n* cars, numbered from 1 to *n* (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?
```python n=int(input()) arr=list(map(int,input().split())) dp=[0]*(n+5) for i in a: dp[i]=dp[i-1]+1 print(n-max(dp)) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=×<=8 table. A field is represented by a pair of integers (*r*,<=*c*) — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules: - A rook moves any number of fields horizontally or vertically. - A bishop moves any number of fields diagonally. - A king moves one field in any direction — horizontally, vertically or diagonally. Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.
```python def moves(r1, c1, r2, c2): # if start and end positions are the same if r1 == r2 and c1 == c2: return 0, 0, 0 # rook rook_moves = 1 if r1 == r2 or c1 == c2 else 2 # bishop if (r1 + c1) % 2 != (r2 + c2) % 2: # different colored squares bishop_moves = -1 # unreachable elif abs(r1 - r2) == abs(c1 - c2): # on the same diagonal bishop_moves = 1 else: bishop_moves = 2 # king king_moves = max(abs(r1 - r2), abs(c1 - c2)) return rook_moves, bishop_moves, king_moves # Testing rook, bishop, king = moves(1, 1, 1, 8) print(f"Rook: {rook}, Bishop: {bishop}, King: {king}") ```
MatrixStudio/Codeforces-Python-Submissions
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that 1. 1<=≤<=*i*,<=*j*<=≤<=*N* 2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
```python n=input() cnt=0 k=0 while k<len(n): for i in n: if i==n[k]: cnt+=1 k+=1 print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game.
```python import sys n=int(input()) z=list(map(int,input().split())) now=0 for i in z: if i-now>15: print(now+15) sys.exit(0) else: now=i print(90) ```
MatrixStudio/Codeforces-Python-Submissions
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*. Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end. Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened. You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.
```python from sys import stdin, stdout s=stdin.readline() s=s[:-1] l=len(s) ans,p,pp=set(),set(),set() d=0 for i in range(l-1,0,-1): if s[:i]==s[-i:]: ans=s[:i] x=len(ans) for j in range(1,l-x): if s[j:j+x] in ans: stdout.write(str(s[j:j+x])) d=1 break if d: break if not d: stdout.write("Just a legend") ```
MatrixStudio/Codeforces-Python-Submissions
An *n*<=×<=*n* table *a* is defined as follows: - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. These conditions define all the values in the table. You are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.
```python def m(n): a=[[0]*n]*n a[0]=[1]*n for i in range(n):a[i][0]=1 for i in range(1, n): for u in range(1, n): a[i][u]=a[i-1][u]+a[i][u-1] print(a[n-1][n-1]) n=int(input()) if n==1: print(1) else: m(n) ```
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 word1=input() word2=input() total=input() arr1=[] arr2=[] tot=[] for x,let in enumerate(word1): arr1.append(let) for x,let in enumerate(word2): arr2.append(let) for x,let in enumerate(total): tot.append(let) arr1.extend(arr2) arr1.sort() tot.sort() if arr1 == tot: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an *n* by *n* square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every *x*,<=*y* such that 1<=≤<=*x*,<=*y*<=≤<=*n* and *a**x*,<=*y*<=≠<=1, there should exist two indices *s* and *t* so that *a**x*,<=*y*<==<=*a**x*,<=*s*<=+<=*a**t*,<=*y*, where *a**i*,<=*j* denotes the integer in *i*-th row and *j*-th column. Help Okabe determine whether a given lab is good!
```python def r(): return list(map(int, input().split())) n = int(input()) matr = [r() for i in range(n)] ans = True columns = list(map(set,zip(*matr))) for row in matr: ans &= all(x == 1 or any(x - a in row for a in col) for x, col in zip(row, columns)) print("Yes" if ans else "No") ```
MatrixStudio/Codeforces-Python-Submissions
We know that lucky digits are digits 4 and 7, however Vasya's got another favorite digit 0 and he assumes it also is lucky! Lucky numbers are such non-negative integers whose decimal record only contains lucky digits. For example, numbers 0,<=47,<=7074 are lucky, but 1,<=7377,<=895,<= -7 are not. Vasya has *t* important positive integers he needs to remember. Vasya is quite superstitious and he wants to remember lucky numbers only, so he is asking you for each important number to represent it as a sum of exactly six lucky numbers (Vasya just can't remember more numbers). Then Vasya can just remember these six numbers and calculate the important number at any moment. For each of *t* important integers represent it as the sum of six lucky numbers or state that this is impossible.
```python print("_RANDOM_GUESS_1691495004.1477993")# 1691495004.1478186 ```
MatrixStudio/Codeforces-Python-Submissions
A *k*-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by *k*. That is, there are no two integers *x* and *y* (*x*<=&lt;<=*y*) from the set, such that *y*<==<=*x*·*k*. You're given a set of *n* distinct positive integers. Your task is to find the size of it's largest *k*-multiple free subset.
```python def main(): n, k = map(int, input().split()) l = list(map(int, input().split())) s = set(l) for p in l: s.discard(p * k) print(len(s)) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on. Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
```python inp=[] out=[[True,True,True],[True,True,True],[True,True,True]] for i in range(3): inp.append(list(map(int,input().split()))) for i in range(3): for j in range(3): if inp[i][j]%2==0: inp[i][j]=0 else: inp[i][j]=1 for i in range(3): for j in range(3): k=out if inp[i][j]==1: out[i][j]=(not out[i][j]) if i-1>=0: out[i-1][j]=(not out[i-1][j]) if i+1<3: out[i+1][j]=(not out[i+1][j]) if j-1>=0: out[i][j-1]=(not out[i][j-1]) if j+1<3: out[i][j+1]=(not out[i][j+1]) for i in range(3): for j in range(3): if out[i][j]==True: out[i][j]=str(1) else: out[i][j]=str(0) print(''.join(out[0])) print(''.join(out[1])) print(''.join(out[2])) ```
MatrixStudio/Codeforces-Python-Submissions
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other. Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
```python groups = 0 last = '00' for i in range(int(input())): new = input() if new != last: groups +=1 last = new print(groups) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
```python from collections import Counter n = int(input()) lst=[] for i in range(n): lst.append(input()) c = Counter(lst) winner = c.most_common(1) print(winner[0][0]) ```
MatrixStudio/Codeforces-Python-Submissions
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square. A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
```python import math n = int(input()) arr = list(map(int,filter(None,input().split(' ')))) arr = sorted(arr,reverse=True) num = -1 for a in arr: sq = math.sqrt(a) if sq-math.floor(sq)==0: continue else: num = a break print(num) ```
MatrixStudio/Codeforces-Python-Submissions
Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he asks you to find two points *A*<==<=(*x*1,<=*y*1) and *C*<==<=(*x*2,<=*y*2), such that the following conditions hold: - the coordinates of points: *x*1, *x*2, *y*1, *y*2 are integers. Besides, the following inequation holds: *x*1<=&lt;<=*x*2; - the triangle formed by point *A*, *B* and *C* is rectangular and isosceles ( is right); - all points of the favorite rectangle are located inside or on the border of triangle *ABC*; - the area of triangle *ABC* is as small as possible. Help the bear, find the required points. It is not so hard to proof that these points are unique.
```python def main(): x, y = list(map(int, input().split())) if x >= 0 and y >= 0: x1, x2, y1, y2 = 0, x+y, x+y, 0 elif x <= 0 and y >= 0: x1, x2, y1, y2 = x-y, 0, 0, -(x-y) elif x <= 0 and y <= 0: x1, x2, y1, y2 = x+y, 0, 0, x+y elif x >= 0 and y <= 0: x1, x2, y1, y2 = 0, x - y, -(x-y), 0 print(x1, y1, x2, y2) if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two given teams very well. Let's say that team *a* solved *p**a* problems with total penalty time *t**a* and team *b* solved *p**b* problems with total penalty time *t**b*. Team *a* gets a higher place than team *b* in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team *a* gets a higher place than team *b* in the final results' table if either *p**a*<=&gt;<=*p**b*, or *p**a*<==<=*p**b* and *t**a*<=&lt;<=*t**b*. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of *x* teams that solved the same number of problems with the same penalty time. Let's also say that *y* teams performed better than the teams from this group. In this case all teams from the group share places *y*<=+<=1, *y*<=+<=2, ..., *y*<=+<=*x*. The teams that performed worse than the teams from this group, get their places in the results table starting from the *y*<=+<=*x*<=+<=1-th place. Your task is to count what number of teams from the given list shared the *k*-th place.
```python nk = list(map(int ,input().split())) n = nk[0] k = nk[1] arr = [] solved = [] pts = [] for i in range(n): x = list(map(int, input().split())) arr.append(x) for i in range(len(arr)): minval = i for j in range(i+1, len(arr)): if arr[minval][0] < arr[j][0]: minval = j elif arr[minval][0] == arr[j][0]: if arr[minval][1] < arr[j][1]: minval = j temp = arr[i] arr[i] = arr[minval] arr[minval] = temp kth = arr[k] print(arr.count(kth)) ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
```python n = int(input()) nums = list(map(int,input().split())) diff = set(nums) res1 = max(nums.count(i) for i in diff) res2 = len(diff) print(res1,res2) ```
MatrixStudio/Codeforces-Python-Submissions
For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer. The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: - A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point). - To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 - In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests). - When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. - Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)". The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?
```python s=input().strip() a=[] if s[0]=='-': p='($' s=s[1:] else: p='$' j=0 t='.' n=len(s) while j<(n): if s[j]=='.': t=t+s[j+1] if j+2<n: t=t+s[j+2] else: t=t+'0' break else: j=j+1 if t=='.': t='.00' u=0 for k in range(j-1,-1,-1): u=u+1 if u==3: a.append(s[k]) if k-1>=0: a.append(',') u=0 else: a.append(s[k]) a=p+''.join(a[::-1])+t if a[0]=='(': a=a+')' print(a) ```
MatrixStudio/Codeforces-Python-Submissions
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
```python def get(f): return f(input().strip()) def gets(f): return [*map(f, input().split())] a, b = gets(int) i = a + b >> 1 if a + b & 1: print(i, 0, 6 - i) else: print(i - 1, 1, 6 - i) ```
MatrixStudio/Codeforces-Python-Submissions
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on. Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
```python s = input().strip() n = len(s) # Generate all possible cyclic shifts shifts = [s[i:] + s[:i] for i in range(n)] # Add shifts to a set to remove duplicates distinct_shifts = set(shifts) # Return the size of the set as the answer print(len(distinct_shifts)) ```
MatrixStudio/Codeforces-Python-Submissions
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?
```python n, k = map(int, input().split()) a = list(map(int, input().split())) count = 0 result = 0 for i in a: if i == 0: count += 1 if count == k: count = 0 result += 1 if count != 0: result += 1 print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places. You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.
```python N=int(input()) # S={"name":[0,0,0,......],} soc=[25,18,15,12,10,8,6,4,2,1] S={} for i in range(N): n=int(input()) for y in range(n): if y<10: s=input() if s in S: S[s][0]+=soc[y] S[s][y+1]+=1 else: S[s]=[soc[y],0,0,0,0,0,0,0,0,0,0] S[s][y+1]+=1 #print(S) ###A mas=[0] m=0 for i in S: #print(type(S[i][0])) if S[i][0]>m: mas=[0] m=S[i][0] mas[0]=i elif S[i][0]==m: mas.append(i) #print(mas,m) if len(mas)>1: zz=1 n=0 M=[0] while n==0: maxx=0 for i in range(len(mas)): t=S[mas[i]][zz] if t>maxx and t!=0: M=[0] maxx=t M[0]=(mas[i]) elif t==maxx and t!=0: M.append(mas[i]) zz=zz+1 if len(M)==1: break print(M[0]) else: print(mas[0]) ####B mas=[0] m=0 for i in S: if S[i][1]>m: mas=[0] m=S[i][1] mas[0]=i elif S[i][0]==m: mas.append(i) if len(mas)>1: mas1=[0] m1=0 for i in range(len(mas)): #print(type(S[i][0])) if S[mas[i]][0]>m: mas1=[0] m1=S[mas[i]][0] mas1[0]=mas[i] elif S[mas[i]][0]==m1: mas1.append(mas[i]) if len(mas1)>1: zz=2 n=0 M=[0] while n==0: maxx=0 for i in range(len(mas)): t=S[mas[i]][zz] if t>maxx and t!=0: M=[0] maxx=t M[0]=(mas[i]) elif t==maxx and t!=0: M.append(mas[i]) zz=zz+1 if len(M)==1: break print(M[0]) else: print(mas1[0]) else: print(mas[0]) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them. Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got. Can you help him?
```python n,k=map(int,input().split()) print(min(n,k),abs(n-k)//2) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed. Your task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times.
```python a,b,n=input().split(" ") no_iterations={ 0:[a] } digits=[str(x) for x in range(10)] found=False for i in range(1,int(n)+1): new_iterations=[] for x in no_iterations[i-1]: for y in digits: if i==int(n): if int(x+y)%int(b)==0 and found==False: print(x+y) found=True else: new_iterations.append(x+y) no_iterations[i]=new_iterations if found==False: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Little X has *n* distinct integers: *p*1,<=*p*2,<=...,<=*p**n*. He wants to divide all of them into two sets *A* and *B*. The following two conditions must be satisfied: - If number *x* belongs to set *A*, then number *a*<=-<=*x* must also belong to set *A*. - If number *x* belongs to set *B*, then number *b*<=-<=*x* must also belong to set *B*. Help Little X divide the numbers into two sets or determine that it's impossible.
```python import sys sys.setrecursionlimit(1000000) set_a = 0 set_b = 10**9 + 1 def find_set(u): if u not in parent: parent[u] = u parent[u] = u if parent[u] == u else find_set(parent[u]) return parent[u] def union(u, v): up = find_set(u) vp = find_set(v) parent[up] = vp """ 4 5 7 2 3 5 4 """ parent = dict() # range 0 to 10**9 + 1 parent[0] = 0 parent[10**9 + 1] = 10**9 + 1 n, a, b = map(int, input().split()) p = list(map(int, input().split())) set_p = set() for i in range(n): set_p.add(p[i]) ans = [-1] * (n) no = False for i in range(n): if a - p[i] in set_p and b - p[i] in set_p: # in both set union(a - p[i], p[i]) union(b - p[i], p[i]) elif a - p[i] in set_p and b - p[i] not in set_p: #only in set a union(a - p[i], set_a) union(p[i], set_a) elif b - p[i] in set_p and a - p[i] not in set_p: #only in set a union(b - p[i], set_b) union(p[i], set_b) else: no = True if no: print("NO") else: print('YES') for idx in p: if find_set(idx) == 0 : print('0', end = ' ') else: print('1', end = ' ') ```
MatrixStudio/Codeforces-Python-Submissions
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has *n* servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. Each ip is of form "a.b.c.d" where *a*, *b*, *c* and *d* are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has *m* commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip. Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.
```python m,n=input().split(' ') IP={} for i in range(int(m)): x,y=input().split(' ') IP[y]=x for i in range(int(n)): s,r=input().split(' ') f=s+' '+r+' #'+IP[r[:-1]] print(f) ```