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* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies. Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm: 1. Give *m* candies to the first child of the line. 1. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. 1. Repeat the first two steps while the line is not empty. Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
```python n, m = list(map(int, input().split(" "))) a = list(map(int, input().split(" "))) posa = [] for i in range(len(a)): posa.append(i+1) while len(a) != 1: a[0] -= m if a[0] <= 0: del(a[0]) del(posa[0]) else: a.append(a[0]) posa.append(posa[0]) del(a[0]) del(posa[0]) print(posa[0]) ```
MatrixStudio/Codeforces-Python-Submissions
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly *n*, based on the alphabet of size *m*. Any its substring with length equal to *k* is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109<=+<=7). Be careful and don't miss a string or two! Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
```python class Dsu: def __init__(self,n): self.sizes=[1]*(n) self.parent=[i for i in range(n)] def findpar(self,node): if self.parent[node]==node: return node self.parent[node]=self.findpar(self.parent[node]) return self.parent[node] def union(self,x,y): px=self.findpar(x) py=self.findpar(y) if px==py: return if self.sizes[px]>self.sizes[py]: self.parent[py]=px self.sizes[px]+=self.sizes[py] else: self.sizes[py]+=self.sizes[px] self.parent[px]=py return n,m,k=map(int,input().split()) d=Dsu(n) for i in range (n): low,high=i,i+k-1 if i+k-1>=n: break while low<high: d.union(low,high) low+=1 high-=1 cc=0 for i in range(n): if i==d.findpar(i): cc+=1 print(cc*m) ```
MatrixStudio/Codeforces-Python-Submissions
A programming coach has *n* students to teach. We know that *n* is divisible by 3. Let's assume that all students are numbered from 1 to *n*, inclusive. Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the *i*-th student wants to be on the same team with the *j*-th one, then the *j*-th student wants to be on the same team with the *i*-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the *i*-th student wants to be on the same team with the *j*-th, then the *i*-th and the *j*-th students must be on the same team. Also, it is obvious that each student must be on exactly one team. Help the coach and divide the teams the way he wants.
```python import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br sys.setrecursionlimit(100000000) int_r = lambda: int(sys.stdin.readline()) str_r = lambda: sys.stdin.readline().strip() intList_r = lambda: list(map(int, sys.stdin.readline().strip().split())) strList_r = lambda: list(sys.stdin.readline().strip()) jn = lambda x, l: x.join(map(str, l)) mul = lambda: map(int, sys.stdin.readline().strip().split()) mulf = lambda: map(float, sys.stdin.readline().strip().split()) ceil = lambda x: int(x) if (x == int(x)) else int(x) + 1 ceildiv = lambda x, d: x // d if (x % d == 0) else x // d + 1 flush = lambda: stdout.flush() outStr = lambda x: stdout.write(str(x)) mod = 1000000007 def main(): n, m = intList_r() sets = [] for i in range(m): a, b = intList_r() flag = 0 for se in sets: if a in se or b in se: se.add(a) se.add(b) flag = 1 if not flag: newset = set() newset.add(a) newset.add(b) sets.append(newset) set4 = [i for i in sets if len(i) > 3] set3 = [i for i in sets if len(i) == 3] set2 = [i for i in sets if len(i) == 2] len4 = sum([len(i) for i in set4]) len3 = sum([len(i) for i in set3]) len2 = sum([len(i) for i in set2]) # set1 = [i for i in sets if len(i) == 1] len1 = n - len2 - len3 - len4 # print(sets) # print(set2) # print(set3) # print(set4) # print(len4) # print(len3) # print(len2) if len4 > 0 | len2 > len1 | (len1 - len2) % 3 != 0: outStr(-1) else: allset = set() for i in set3: allset = allset.union(i) for i in set2: allset = allset.union(i) for i in set4: allset = allset.union(i) set1 = set([i + 1 for i in range(n)]) - allset set1 = list(set1) # print(set1) for i in set3: outStr(" ".join([str(j) for j in i])) i = 0 for it in set2: outStr(" ".join([str(j) for j in it].extend([str(j) for j in set1[i]]))) i += 1 while i < len(set1): outStr(" ".join([str(set1[i]), str(set1[i + 1]), str(set1[i + 2])])) i += 3 if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time. Order is important everywhere, so the painters' work is ordered by the following rules: - Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=&lt;<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
```python m,n = map(int,input().strip().split()) final = [] for _ in range(m): l=list(map(int,input().split())) final.append(l) checkstart=0 checkend=0 for i in range(1,m): final[i][0] += final[i-1][0] for i in range(1,n): final[0][i] += final[0][i-1] for i in range(1,m): for j in range(1,n): final[i][j] += max(final[i][j-1],final[i-1][j]) ans=[] for i in range(m): ans.append(final[i][n-1]) print(*ans) ```
MatrixStudio/Codeforces-Python-Submissions
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere. Lala Land has exactly *n* apple trees. Tree number *i* is located in a position *x**i* and has *a**i* apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in *x*<==<=0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing. What is the maximum number of apples he can collect?
```python print("_RANDOM_GUESS_1689445518.1281602")# 1689445518.1281798 ```
MatrixStudio/Codeforces-Python-Submissions
Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*.
```python a ,b=map(int,input().split()) if a>b and (b*2)!=a: print(min(a,b)*2) elif (b*2) == a: print(a + b) ```
MatrixStudio/Codeforces-Python-Submissions
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro. She has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over. Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator. As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
```python n=int(input()) if (n+1)%2==0: print((n+1)//2) elif (n+1)%2==1: print(n+1) ```
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip. You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
```python a,b,c,d = input().split() a = int(a) b = int(b) c = int(c) d = int(d) counter=0 boxes=input() for i in boxes: if i == "1": counter+=a elif i == "2": counter+=b elif i == "3": counter+=c elif i == "4": counter+=d print (counter) ```
MatrixStudio/Codeforces-Python-Submissions
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs *a* points and Vasya solved the problem that costs *b* points. Besides, Misha submitted the problem *c* minutes after the contest started and Vasya submitted the problem *d* minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs *p* points *t* minutes after the contest started, you get points. Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.
```python L1= [int(x) for x in input().split(" ")] mp=L1[0] vp=L1[1] mt=L1[2] vt=L1[3] Lm=[(3*mp)/10,mp-(mp*mt)/250] Lv=[(3*vp)/10,vp-(vp*vt)/250] m=max(Lm) v=max(Lv) if m>v: print("Misha") elif m==v: print("Tie") else: print("Vasya") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.
```python def ans(n,a,b,c): if l[n]!=-1: return l[n] if n==0: return 0 elif n<0: return -10**9 else: l[n]=max(1+ans(n-a,a,b,c),1+ans(n-b,a,b,c),1+ans(n-c,a,b,c) ) return l[n] n,a,b,c=list(map(int,input().split())) l=[-1]* (n+2) print(ans(n,a,b,c)) ```
MatrixStudio/Codeforces-Python-Submissions
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1. Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used. Help Sherlock complete this trivial task.
```python n=int(input()) flag=False;arr=[] for i in range(2,n+2): if i%2!=0:arr.append(1) elif i%3!=0:arr.append(2) else:arr.append(3) print(len(set(arr))) print(*arr) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*. Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
```python n,h=map(int,input().split()) a=list(map(int,input().split())) count=0 for i in a: if i>h: count+=2 else: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch. Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts *t*1 seconds and the second part lasts *t*2 seconds. The first and the second part are separated by a little break. After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of *v**i* meters per second. After *t*1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by *k* percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of *u**i* meters per second. After a *t*2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary. Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds *a**i* and *b**i*, then there are two strategies: he either uses speed *a**i* before the break and speed *b**i* after it, or vice versa. Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results. The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
```python n, t1, t2, k = map(int, input().split()) table = [] for i in range(1, n+1): a, b = map(int, input().split()) c1 = a*t1*(1-k/100) + b*t2 c2 = b*t1*(1-k/100) + a*t2 if c1 > c2: c = c1 else: c = c2 table.append((i, f"{c:.2f}")) for e in sorted(table, key=lambda x: float(x[1]), reverse=True): print(*e) ```
MatrixStudio/Codeforces-Python-Submissions
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result. Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
```python # Case of the Zeros and Ones n=int(input()) s=input() i=0 while (s.__contains__('10') or s.__contains__('01')) and len(s)>1: if s[i:i+2]=='10' or s[i:i+2]=='01': s=s[:i]+s[i+2:] #print(s) i=i-2 i=i+1 print(len(s)) ```
MatrixStudio/Codeforces-Python-Submissions
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least *i* is found so that name*i* does not yet exist in the database.
```python q={} for _ in range(int(input())):t=input();print(t+str(q[t])if q.setdefault(t,0)else 'OK');q[t]+=1 ```
MatrixStudio/Codeforces-Python-Submissions
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
```python import sys input = sys.stdin.readline print = sys.stdout.write s = input().strip() stack = [] ans = 0 for c in s: if c == '(': stack.append(c) else: # c == ')' if not stack: continue stack.pop() ans += 2 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.
```python from functools import cache import sys from typing import Counter input = lambda:sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MII(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) inf = float("inf") mod = 10**9 + 7 # for _ in range(II()): n = II() a = LII() mx = max(a) cnt = Counter(a) @cache def dfs(i): if i < 0: return 0 return max(dfs(i-2) + i * cnt[i], dfs(i-1)) print(dfs(mx)) ```
MatrixStudio/Codeforces-Python-Submissions
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z. For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well. Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
```python def addEdge(adj, a, b): adj[a].append(b) adj[b].append(a) def dfs(x): visited[x] = True for child in adj[x]: if not visited[child]: dfs(child) if __name__ == '__main__': n, e = map(int, input().split()) adj = [ [] for i in range(n)] visited = [False] * n for i in range(e): x, y = map(int, input().split()) addEdge(adj, x - 1, y - 1) check = True for i in range(n): for child in adj[i]: if len(adj[i]) != len(adj[child]) : check = False break if check: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies. Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm: 1. Give *m* candies to the first child of the line. 1. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. 1. Repeat the first two steps while the line is not empty. Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
```python a,b=map(int,input().split()) x=[int(i)for i in input().split()] for i in range(a-1,-1,-1): if x[i]>b: print(i+1) break else: print(a) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python x,y = map(int,input().split()) if (x*y) %2 ==0: print((x*y)//2) else: print((x*y) //2) ```
MatrixStudio/Codeforces-Python-Submissions
"Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round.
```python ''' 158A - Next Round By: Ayushi Rawat ''' keys = input().split() #print(keys) scores = [] for i in range(8): scores.append(int(input())) # print(scores) n, k = 8, 5 score = [10, 9, 8, 7, 7, 7, 5, 5] count = 0 k = keys[1] for i in range(keys[0]): if score[i] > 0 and score[i] >= score[k]: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python x = [int(a) for a in input().split()] if(1 <= x[0] <= x[1] <= 16): a = x[0]/2 * x[1] if(a == int(a)): print(int(a)) else: print(int(a - 0.5)) ```
MatrixStudio/Codeforces-Python-Submissions
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!). Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
```python a = [i for i in input() if i == 'Q' or i == 'A'] t = 0 for i in range(len(a)): for j in range(i, len(a)): for k in range(j, len(a)): if a[i] == 'Q' and a[j] == 'A' and a[k] == 'Q': t += 1 print(t) ```
MatrixStudio/Codeforces-Python-Submissions
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it? He needs your help to check it. A Minesweeper field is a rectangle $n \times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell: - if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs. - if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $8$ neighboring cells).
```python # Getting Minesweeper dimensions and field from Codeforces. dimensions,field = tuple(map(int,input().split(' '))),[] for i in range(dimensions[0]): field.append(list(input())) # Declaring List Storing Relative Coords of a Cell' Neighbours. relCoords = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1)] # For Storing a single cell's bombCount. bombCount = 0 # Method to compute bomb count in neighbourhood. def computeBombCount(pos,depth): # global. global bombCount # Determining if Cell is valid. if 0>pos[0] or pos[0]>=dimensions[0]: return 0 if 0>pos[1] or pos[1]>=dimensions[1]: return 0 # Determining and returning cell count (Base-Case). if depth == 1: if field[pos[0]][pos[1]] == '*': bombCount = bombCount+1 # Exploring All Neighbours. else: for i in range(len(relCoords)): newCoord = (pos[0]+relCoords[i][0],pos[1]+relCoords[i][1]) computeBombCount(newCoord,1) # Exploring Field and Ascertaining Validity. for i in range(dimensions[0]): for j in range(dimensions[1]): # Combuting bombCount. computeBombCount((i,j),0) # Case Numbered Cell. if field[i][j] in tuple(map(str,range(9))): # Case Bomb-Count Mismatch. if not int(field[i][j]) == bombCount: print("NO");exit() elif field[i][j] == '.' and bombCount>0: print("NO");exit(); bombCount = 0 print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it. What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
```python n,A,B=list(map(int,input().split())) l=list(map(int,input().split())) s=sum(l) cnt=0 #l.sort() for each in range(len(l)): temp=(l[each]*A)/s #print(temp) if temp<B: cnt+=1 else: break s-=l[each] print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Permutation *p* is an ordered set of integers *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*, consisting of *n* distinct positive integers not larger than *n*. We'll denote as *n* the length of permutation *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*. Your task is to find such permutation *p* of length *n*, that the group of numbers |*p*1<=-<=*p*2|,<=|*p*2<=-<=*p*3|,<=...,<=|*p**n*<=-<=1<=-<=*p**n*| has exactly *k* distinct elements.
```python def permutation(n, k): lista = [] for i in range(1,n+1): lista.append(i) #print(lista) permutation = [] i = 0 while i < k-1: permutation.append(lista[i]) permutation.append(lista[n-1-i]) k = k - 1 i = i + 1 resto = lista[i:n-i] for j in resto: permutation.append(j) return permutation ## PRUEBA DEL ALGORITMO n = int(input()) k = int(input()) p = permutation(n,k) for n in p: print(n) ```
MatrixStudio/Codeforces-Python-Submissions
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers. You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time. Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
```python n=int(input()) s=input() m=-1 l=list(map(int,input().split())) for i in range(n-1): if s[i]!=s[i+1]: if s[i+1]!='R': m=max(m,(l[i+1]-l[i])//2) print(m) ```
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 def main(): txt = input() txt_len = int(len(txt)) for pat_len in range(1, int(len(txt)/2) + 1): pattern = txt[:pat_len] suffix = txt[len(txt) - pat_len:] if pattern != suffix: continue middle = txt[pat_len:len(txt) - pat_len] i = middle.find(pattern) if i == -1: print('Just a legend') else: print(middle[i:i + pat_len]) break if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
*n* children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation *a*1,<=*a*2,<=...,<=*a**n* of length *n*. It is an integer sequence such that each integer from 1 to *n* appears exactly once in it. The game consists of *m* steps. On each step the current leader with index *i* counts out *a**i* people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader. You are given numbers *l*1,<=*l*2,<=...,<=*l**m* — indices of leaders in the beginning of each step. Child with number *l*1 is the first leader in the game. Write a program which will restore a possible permutation *a*1,<=*a*2,<=...,<=*a**n*. If there are multiple solutions then print any of them. If there is no solution then print -1.
```python import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,m=map(int,input().split()) l=list(map(int,input().split())) for i in range(len(l)): l[i]-=1 use=[0]*n a=[0]*n bad=0 for i in range(len(l)-1): # transfer l[i] to l[i+1] if a[l[i]] and a[l[i]]%n!=(l[i+1]-l[i])%n: bad=1 break if use[(l[i+1]-l[i])%n]: bad=1 break use[(l[i+1]-l[i])%n]=1 a[l[i]]=(l[i+1]-l[i])%n if a[l[i]]==0: a[l[i]]=n if not bad: # fill in gaps for i in range(n): if a[l[i]]==0: for j in range(1,n+1): if not use[j%n]: a[l[i]]=j break print(" ".join(map(str,a))) else: print("-1") ```
MatrixStudio/Codeforces-Python-Submissions
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city. Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.
```python n,d = map(int,input().split()) A = list(map(int,input().split())) B = set() for i in A: a = i-d;b=i+d f=0;g=0 for j in range(n): if(A[j]==i): continue if(abs(A[j]-a)<d): f=-1 if(abs(A[j]-b)<d): g=-1 if(f==0): B.add(i-d) if(g==0): B.add(i+d) print(len(B)) ```
MatrixStudio/Codeforces-Python-Submissions
Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks: - Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
```python n=int(input()) line=input().split() data=[int(i) for i in line] data.sort(reverse=True) score = 0 if n>=4: for i in range(2,len(data)-1): score=score+(int(data[i])*int((n-i+2))) score=score+int(int(n)*int(data[1])) score=score+int(int(n)*int(data[0])) elif n==3: score = score+(int(data[2])*2) score = score+int(3*int(data[1])) score = score+int(3*int(data[0])) elif n==2: score = score+int(2*int(data[1]))+int(2*int(data[0])) elif n==1: score = int(data[0]) print(score) ```
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 teams = {} for i in range(int(input())): t = input() if t not in teams: teams[t] = 1 else: teams[t] += 1 print(max(teams, key=teams.get)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for *k* burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of *r* burles (1<=≤<=*r*<=≤<=9). What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of *r* burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.
```python k,r=map(int,input().split()) sum=0 while(r%k !=0): r=r+10 sum=sum+1 print(r//k) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python #!/usr/bin/env python # coding: utf-8 # In[2]: s = input() a = s[0] for i in range(1,len(s)): if s[i] != s[i-1] : a += s[i] if "helo" in a.lower() or "hello" in a.lower() : print("YES") else : print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam. You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=*n*). The answer to the query *l**i*,<=*r**i* is the number of such integers *i* (*l**i*<=≤<=*i*<=&lt;<=*r**i*), that *s**i*<==<=*s**i*<=+<=1. Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
```python from functools import lru_cache def update(index, delta): while index < len(tree): tree[index] += delta index += index & (-index) @lru_cache(None) def query(index): res = 0 while index > 0: res += tree[index] index -= index & (-index) return res s = input() tree = [0] * len(s) for i in range(len(s) - 1): update(i + 1, s[i] == s[i + 1]) for _ in range(int(input())): l, r = map(int, input().split()) print(query(r - 1) - query(l - 1)) ```
MatrixStudio/Codeforces-Python-Submissions
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload". The field for the new game is a rectangle table of size *n*<=×<=*m*. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs: - some dwarf in one of the chosen lines is located in the rightmost cell of his row; - some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells. Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.
```python rows, columns = map(int,input().split()) elems = [] res = 0 distance_from_candy = [] for i in range(rows): x = input() elems.append(x) if (x.index("G") > x.index("S")): res = -1 if (x.index("G") != x.index("S")): distance_from_candy.append(x.index("S") - x.index("G")) if (res == -1): print(res) exit() distance_from_candy = list(set(distance_from_candy)) print(len(distance_from_candy)) ```
MatrixStudio/Codeforces-Python-Submissions
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are *n* flights that must depart today, the *i*-th of them is planned to depart at the *i*-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first *k* minutes of the day, so now the new departure schedule must be created. All *n* scheduled flights must now depart at different minutes between (*k*<=+<=1)-th and (*k*<=+<=*n*)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the *i*-th flight costs airport *c**i* burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
```python n, k = map(int, input().split()); Cost = [int(x)for x in input().split()]; O = [[0]for i in range(n)]; Now = [int(x+k+1) for x in range(n)]; Past = [int(x+1)for x in range(n-k)]; o = 0; for i in range(1, k+1): O[-i] = n+1-i; Cost[-i] = -1; Now.remove(n+1-i); while [0] in O: y = Cost.index(max(Cost)); o += (min(Now) - min(Past)) * Cost[y]; Past.remove(min(Past)); O[y] = min(Now); Cost[y] = -1; Now.remove(min(Now)); print(o); for i in O: print(i, end = ' '); ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*): - point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=&gt;<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=&lt;<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=&lt;<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=&gt;<=*y* We'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points. Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
```python ss = 0 n = int(input()) xes = [] yes = [] for i in range(n): x,y = (int(x) for x in input().split()) xes.append(x) yes.append(y) for i in range(n): a,b,c,d = [0]*4 for j in range(0,n): if xes[j] == xes[i] and yes[j] > yes[i]: a+=1 if xes[j] == xes[i] and yes[j] < yes[i]: b+=1 if xes[j] > xes[i] and yes[j] == yes[i]: c+=1 if xes[j] < xes[i] and yes[j] == yes[i]: d+=1 if a*b*c*d != 0 : ss+=1 print(ss) ```
MatrixStudio/Codeforces-Python-Submissions
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw *n* distinct points and *m* segments on the *OX* axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment [*l**i*,<=*r**i*] consider all the red points belong to it (*r**i* points), and all the blue points belong to it (*b**i* points); each segment *i* should satisfy the inequality |*r**i*<=-<=*b**i*|<=≤<=1. Iahub thinks that point *x* belongs to segment [*l*,<=*r*], if inequality *l*<=≤<=*x*<=≤<=*r* holds. Iahub gives to you all coordinates of points and segments. Please, help him to find any good drawing.
```python def flip(l,ind,q): for p in l: if p[0] > ind: break p[1] = 1-p[1] for p in q: p[1][0] = 0 p[1][1] = 0 for ll in l: if p[0][0] <= ll[0] <= p[0][1] and ll[0] <= ind: p[1][ll[1]] += 1 n,m = [int(i) for i in input().split()] points = [[int(i),0] for i in input().split()] segs = [] for i in range(m): segs.append([int(i) for i in input().split()]) segs.sort(reverse = True) q = [] index = 0 for i in range(102): while len(segs) > 0 and segs[-1][0] == i: q.append([segs.pop(),[0,0]]) q = [j for j in q if j[0][1] != i-1] if index < len(points) and points[index][0] == i: fl = False #print() for pair in q: #print(pair) if pair[1][0] - pair[1][1] >= 1: #print("test") if fl: #print(-1) sys.exit(0) fl = True flip(points,i-1,q) pair[1][0] += 1 #print() index += 1 #print(q) #print(points) for i,c in points: print(c,end = ' ') ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$. Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.
```python n=int(input()) l=list(map(int,input().split())) s=list(set(l)) c=0 for i in range(len(s)): t=l.count(s[i]) if t>c: c=t print(c) ```
MatrixStudio/Codeforces-Python-Submissions
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
```python n,p=map(int,input().split()) l=list(map(int,input().split())) d=[] k=[] for i in range(0,n,1): if l[i] not in d: d.append(l[i]) k.append(i+1) if len(d)==p: print("YES") print(*k) else: print("NO") ```
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,c= map(int,input().split()) aaa=str(a) aa=len(aaa) p=True z=True for i in range(c): if z: a=a*10 + 9 a-=a%b ba=str(a) c1=(len(ba)==(i+aa+1)) c2=(ba.startswith(aaa)) if (not c1) or (not c2): print(-1) p=False break if c1 and c2: z=False else: a=a*10 if p : print(a) ```
MatrixStudio/Codeforces-Python-Submissions
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction). Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.
```python n = int(input()) p = list(map(int,input().split())) ll = p.index(max(p)) p.pop(ll) print(ll+1,max(p)) ```
MatrixStudio/Codeforces-Python-Submissions
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first *n*. He writes down the following sequence of numbers: firstly all odd integers from 1 to *n* (in ascending order), then all even integers from 1 to *n* (also in ascending order). Help our hero to find out which number will stand at the position number *k*.
```python n, k = map(int, input().split()) print(([i for i in range(1, n+1, 2)] + [i for i in range(2, n+1, 2)])[k-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money. Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance. Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
```python n=int(input()) if(n>=0): print(n) else: if(n>=-10): print("0") else: a=n//10; b=((n//100)*10)+(n%10); if(a>b): print(a) else: print(b) ```
MatrixStudio/Codeforces-Python-Submissions
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of *n* brains and *m* brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems. In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
```python from typing import List # 좀비의 뇌의 수 n, 뇌를 연결하는 링크의 수 m # 두 노드 간의 최대 거리를 계산(노드 사이 연결은 트리 형태로 가정) # 1번 노드로부터의 거리 계산, 1번 노드는 항상 연결되어 있다고 가정 def solution(brain_links: List[List[int]], visited: List[int]) -> int: def dfs(node: int) -> int: max_distance = 1 for link in brain_links[node]: if not visited[link]: visited[link] = True max_distance = max(max_distance, 1 + dfs(link)) visited[link] = False return max_distance import heapq visited[1] = True distances = [] for next_brain in brain_links[1]: heapq.heappush(distances, dfs(next_brain)) if len(distances) == 1: return heapq.heappop(distances) return heapq.heappop(distances) + heapq.heappop(distances) if __name__ == '__main__': n, m = map(int, input().split()) links = [[] for _ in range(n + 1)] for _ in range(m): a, b = map(int, input().split()) links[a].append(b) links[b].append(a) visited = [False] * (n + 1) print(solution(links, visited)) ```
MatrixStudio/Codeforces-Python-Submissions
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKing — by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group. Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time?
```python if __name__ == '__main__': a, b, c, n = map(int, input().split()) passed = True presult = a+b-c if (a-c < 0 or b-c < 0): passed = False if(passed == False or presult < 1 or presult >= n): print(-1) else: print(n-presult) ```
MatrixStudio/Codeforces-Python-Submissions
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on. When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if *i*-th garland is switched on during *x*-th second, then it is lit only during seconds *x*, *x*<=+<=*k**i*, *x*<=+<=2*k**i*, *x*<=+<=3*k**i* and so on. Mishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers *x*1, *x*2 and *x*3 (not necessarily distinct) so that he will switch on the first garland during *x*1-th second, the second one — during *x*2-th second, and the third one — during *x*3-th second, respectively, and during each second starting from *max*(*x*1,<=*x*2,<=*x*3) at least one garland will be lit. Help Mishka by telling him if it is possible to do this!
```python a = sorted(list(map(int, input().split()))) if a[:1] == [1] or a[:2] == [2,2] or a[:3] == [3,3,3] or a[:3] == [2,4,4]: print ("YES") else: print ("NO") ```
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 n = int(input()) min = input().split() bl = True if int(min[0]) > 15: bl = False print(15) else: for i in range(n-1): if(int(min[i+1])-int(min[i])>15) and bl == True: bl = False print(int(min[i])+15) if bl == True: if int(min[n])<85: print(int(min[n])+15) else: print(90) ```
MatrixStudio/Codeforces-Python-Submissions
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4<=×<=4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2<=×<=2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed. Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2<=×<=2 square, consisting of cells of the same color.
```python matrix=[] answer="NO" for i in range (4): matrix.append(input()) for i in range(3): for j in range(3): if ((matrix[i][j])+(matrix[i][j+1])+(matrix[i+1][j])+(matrix[i+1][j+1])).count("#") !=2: answer="YES" break print(answer) ```
MatrixStudio/Codeforces-Python-Submissions
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (*n*<=-<=1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1,<=2,<=1] after the first step, the sequence [1,<=2,<=1,<=3,<=1,<=2,<=1] after the second step. The task is to find the value of the element with index *k* (the elements are numbered from 1) in the obtained sequence, i. e. after (*n*<=-<=1) steps. Please help Chloe to solve the problem!
```python def solve(n, k): middle = n length = (1 << middle) - 1 while k != (length + 1) // 2: if k > (length + 1) // 2: k = length + 1 - k middle -= 1 length //= 2 return middle n = int(input()) k = int(input()) print(solve(n, k)) ```
MatrixStudio/Codeforces-Python-Submissions
zscoder loves simple strings! A string *t* is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string *s*. He wants to change a minimum number of characters so that the string *s* becomes simple. Help him with this task!
```python s = input() s += '0' for i in range(1, len(s)): if s[i - 1] == s[i]: if s[i] != 'z' and s[i + 1] != 'z': s = s[:i] + 'z' + s[i + 1:] elif s[i] == 'a' or s[i + 1] == 'b': s = s[:i] + 'b' + s[i + 1:] else: s = s[:i] + 'a' + s[i + 1:] print(s[:len(s) - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel is playing a game with numbers now. Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* &gt; *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum of all numbers as small as possible. Please help Ciel to find this minimal sum.
```python # bsdk idhar kya dekhne ko aaya hai, khud kr!!! # import math # from itertools import * # import random # import calendar # import datetime # import webbrowser n = int(input()) arr = list(map(int, input().split())) while max(arr) > min(arr): index = arr.index(max(arr)) arr[index] -= min(arr) print(sum(arr)) ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo has an *n*<=×<=*m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a**ij*. In one move the penguin can add or subtract number *d* from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
```python n, m, d = map(int, input().split()) l = [] for _ in range(n): l += list(map(int, input().split())) l.sort() mid = (n*m)//2 ans = 0 for i in l: if abs(i-l[mid]) % d != 0: print(-1) break ans += abs(i - l[mid]) else: print(ans//d) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve the *i*-th problem. Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first. How many problems can Limak solve if he wants to make it to the party?
```python n,k=map(int,input().split()) actual_time=240-k counter=0 for i in range(1,n): if 5*i<=actual_time: counter+=1 print(counter) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```python s = input() uppercase = 0 for c in s: if c.isupper(): uppercase += 1 if uppercase > int(len(s) / 2): s = s.upper() else: s = s.lower() print(s) ```
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 l1 = [int(x) for x in input().split()] examnumber = l1[0] totalscore = l1[1] print(max(0,examnumber*3-totalscore)) ```
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 = list(map (int , input() . split())) x = max(n) - min(n) print( min(n) , x//2 ) ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has *k**i* people. The *j*-th person standing in the queue to the *i*-th cashier has *m**i*,<=*j* items in the basket. Vasya knows that: - the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
```python n = int(input()) ppl = list(map(int, input().strip().split()))[:n] time = [] for i in range(0, n): temp = 15 * ppl[i] product = list(map(int, input().strip().split()))[:ppl[i]] for j in range(0, ppl[i]): temp += product[j]*5 time.append(temp) time.sort() print(time[0]) ```
MatrixStudio/Codeforces-Python-Submissions
You have a positive integer *m* and a non-negative integer *s*. Your task is to find the smallest and the largest of the numbers that have length *m* and sum of digits *s*. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
```python m,s=map(int,input().split()) if m!=1 and s<=1 or m*9<s: print(-1,-1) else: k=9 l='' for i in range(9): l+=str(k-i)*(s//(k-i)) s-=(s//(k-i))*(k-i) if len(l)<m: p=len(l) l+='0'*(m-p) l1=list(l[::-1]) l1[0]='1' l1[m-p]=str(int(l1[m-p])-1) l2='' for j in range(m): l2+=l1[j] print(l,l2) else: print(l,l[::-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Little Alyona is celebrating Happy Birthday! Her mother has an array of *n* flowers. Each flower has some mood, the mood of *i*-th flower is *a**i*. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in. For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,<=<=-<=2,<=1,<=3,<=<=-<=4. Suppose the mother suggested subarrays (1,<=<=-<=2), (3,<=<=-<=4), (1,<=3), (1,<=<=-<=2,<=1,<=3). Then if the girl chooses the third and the fourth subarrays then: - the first flower adds 1·1<==<=1 to the girl's happiness, because he is in one of chosen subarrays, - the second flower adds (<=-<=2)·1<==<=<=-<=2, because he is in one of chosen subarrays, - the third flower adds 1·2<==<=2, because he is in two of chosen subarrays, - the fourth flower adds 3·2<==<=6, because he is in two of chosen subarrays, - the fifth flower adds (<=-<=4)·0<==<=0, because he is in no chosen subarrays. Thus, in total 1<=+<=(<=-<=2)<=+<=2<=+<=6<=+<=0<==<=7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this! Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
```python n, m = map(int, input().split()) ar = [int(i) for i in input().split()] leftsum = [0 for _ in range(n)] leftsum[0] = ar[0] for i in range(1,n): leftsum[i] = leftsum[i-1] + ar[i] queries = [] totals = [] for _ in range(m): l, r = map(int, input().split()) l-=1 r-=1 queries.append((l,r)) tot = leftsum[r] if l!=0:tot -= leftsum[l-1] totals.append(tot) counter = [ 0 for _ in range(n)] ans = 0 for _ in range(m): idx = totals.index(max(totals)) l,r = queries[idx] temp = 0 for i in range(l,r+1): counter[i]+=1 for i in range(n): temp += counter[i]*ar[i] if temp>ans: ans = temp totals[idx] = -10**9 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```python num=str(int(input())) num3=str(int(input())) if len(num)>len(num3): num3=num3.zfill(len(num)) else: num=num.zfill(len(num3)) ch="" for i in range(len(num)): if num[i]==num3[i]: ch+="0" else: ch+="1" print(ch) ```
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*. Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
```python s = input() x = "" for i in s : if i == '9' : x+=i else : x+=str(min((9 - int(i)), int(i))) print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya likes everything infinite. Now he is studying the properties of a sequence *s*, such that its first element is equal to *a* (*s*1<==<=*a*), and the difference between any two neighbouring elements is equal to *c* (*s**i*<=-<=*s**i*<=-<=1<==<=*c*). In particular, Vasya wonders if his favourite integer *b* appears in this sequence, that is, there exists a positive integer *i*, such that *s**i*<==<=*b*. Of course, you are the person he asks for a help.
```python a,b,c=map(int,input().split()) if(c==0): if(a==b): print("YES") else: print("NO") else: f=(b-a)/c if(f-int(f)>0 or f<0): print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least *k* walks for any two consecutive days in order to feel good. For example, if *k*<==<=5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next *n* days and made a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the number of times Polycarp will walk with the dog on the *i*-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.). Help Polycarp determine the minimum number of walks he needs to do additionaly in the next *n* days so that Cormen will feel good during all the *n* days. You can assume that on the day before the first day and on the day after the *n*-th day Polycarp will go for a walk with Cormen exactly *k* times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers *b*1,<=*b*2,<=...,<=*b**n* (*b**i*<=≥<=*a**i*), where *b**i* means the total number of walks with the dog on the *i*-th day.
```python n,k = map(int, input().split()) a= list(map(int, input().split())) r= 0 for i in range(1,n): if a[i-1] + a[i] < k: r+= k -(a[i-1] +a[i]) a[i] = k -a[i-1] print(r) print(*a) ```
MatrixStudio/Codeforces-Python-Submissions
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum. For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny. Write a program that will print the name of a man who will drink the *n*-th can. Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
```python list_ = ['Sheldon', 'Leonard', 'Penny', 'Rajesh', 'Howard'] quantidades = [0, 5] target = int(input()) x = 0 while quantidades[-1] < target: x += 1 quantidades.append(quantidades[-1] + 5 * 2 ** x) print(list_[(target-1 - quantidades[-2])//2**x]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two lists of non-zero digits. Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
```python n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) flag=0 x=[min(a),min(b)] for i in range(n): if a[i] in b: print(a[i]) flag=1 break if flag==0: print(*sorted(x),sep='') ```
MatrixStudio/Codeforces-Python-Submissions
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users). As a reminder, a prefix of a string *s* is its substring which occurs at the beginning of *s*: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string *a* is alphabetically earlier than a string *b*, if *a* is a prefix of *b*, or *a* and *b* coincide up to some position, and then *a* has a letter that is alphabetically earlier than the corresponding letter in *b*: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
```python f,l = input().split() ans = '' if len(f) > 3 ans = f[:3] + l[0] else: ans = f[:2] + l[0] print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) is coprime, then the pair (*a*,<=*c*) is coprime. You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (*a*,<=*b*,<=*c*), for which the statement is false, and the numbers meet the condition *l*<=≤<=*a*<=&lt;<=*b*<=&lt;<=*c*<=≤<=*r*. More specifically, you need to find three numbers (*a*,<=*b*,<=*c*), such that *l*<=≤<=*a*<=&lt;<=*b*<=&lt;<=*c*<=≤<=*r*, pairs (*a*,<=*b*) and (*b*,<=*c*) are coprime, and pair (*a*,<=*c*) is not coprime.
```python def hypothesis(l, r): if l % 2 != 0: l += 1 elif l + 2 > r: return -1 return l, l + 1, l + 2 L, R = [int(i) for i in input().split()] print(*hypothesis(L, R)) ```
MatrixStudio/Codeforces-Python-Submissions
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him *n* subjects, the *i**th* subject has *c**i* chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously. Let us say that his initial per chapter learning power of a subject is *x* hours. In other words he can learn a chapter of a particular subject in *x* hours. Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour. You can teach him the *n* subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy. Please be careful that answer might not fit in 32 bit data type.
```python n, x = map(int, input().split()) c = sorted(map(int, input().split())) ans = 0 for i in range(n): if x == 0: x += 1 ans += c[i] * x x -= 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed. Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move. Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
```python n,m,k=map(int,input().split()) a=[] for i in range(k): b=list(map(int,input().split())) a.append(b) x=max(n,m) for i in range(x): for j in range(x): if [i,j] in a and [i+1,j] in a and [i+1,j+1] in a and [i,j+1] in a: d=a.index([i+1,j]) e=a.index([i+1,j+1]) f=a.index([i,j+1]) g=a.index([i,j]) print(max(d+1,e+1,f+1,g+1)) break else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string *s* consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in *s*. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
```python counts = [0]*26 for c in input(): counts[ord(c)-97] += 1 # print(*counts) ans = "" i = 26 while i: i -= 1 if counts[i]&1: # Find min thing with odd count and increase that j = 0 while j < 26 and counts[j]&1 < 1: j += 1 if j < 26 and counts[j]&1: counts[i] -= 1 counts[j] += 1 break # print(ans) for i in range(25, -1, -1): add = chr(i+97) * (counts[i]//2) ans = add + ans + add if counts[i]&1: l = len(ans)//2 ans = ans[:l] + chr(i+97) + ans[l:] print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet. Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last *n* days. Thus, he got a sequence of numbers *t*1,<=*t*2,<=...,<=*t**n*, where the *i*-th number is the temperature on the *i*-th day. Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer *k* (1<=≤<=*k*<=≤<=*n*<=-<=1) such that *t*1<=&lt;<=0,<=*t*2<=&lt;<=0,<=...,<=*t**k*<=&lt;<=0 and *t**k*<=+<=1<=&gt;<=0,<=*t**k*<=+<=2<=&gt;<=0,<=...,<=*t**n*<=&gt;<=0. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset. You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.
```python a = open("input.txt", "r") b = open("output.txt", "w") c = int(a.readline()) d = list(map(int, a.readline().split())) ej = 0 for x in d: if x <= 0: e += 1 for i in d[:-1]: e += (i > 0) - (i < 0) c = min(c, e) print(c, file = b) #roomatehelp ```
MatrixStudio/Codeforces-Python-Submissions
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts. Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them. Note that the final necklace should remain as one circular part of the same length as the initial necklace.
```python neckelace = input() p = neckelace.count("o") l = neckelace.count("-") if l%p==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a *d*1 meter long road between his house and the first shop and a *d*2 meter long road between his house and the second shop. Also, there is a road of length *d*3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house. Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.
```python a,b,c=map(int,input().split()) print(min(a+a+c+c,b+b+c+c,a+b+c,a+a+b+b)) ```
MatrixStudio/Codeforces-Python-Submissions
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there. Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: - If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part. - If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part.- If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?
```python s=input() a=round(float(s)) a=str(a) b=a[len(a)-1] if(s[s.index(".")-1]=="9"): print("GOTO Vasilisa.") else: print(int(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle. Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
```python def mapear(f, xs): return list(map(f, xs)) def solve(): n = int(input()) a = mapear(int, input().split(' ')) # Sem perda de generalidade, assumo que i < j < k # Dessa forma, garante-se que nenhuma permutação se repetirá for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if (a[i] + a[j] > a[k]) and (a[i] + a[k] > a[j]) and (a[j] + a[k] > a[i]): print('YES') return print('NO') solve() ```
MatrixStudio/Codeforces-Python-Submissions
In a small restaurant there are *a* tables for one person and *b* tables for two persons. It it known that *n* groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group. If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group. You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.
```python #!/usr/bin/env python3 import math def test_case(casen): n, a, b = map(int, input().split()) t = list(map(int, input().split())) ans = 0 twoone = 0 for i in range(n): if t[i] == 1 and a > 0: a -= 1 continue if t[i] == 1 and twoone > 0: twoone -= 1 continue if t[i] == 1 and b > 0: twoone += 1 b -= 1 continue if t[i] == 1: ans += 1 continue if t[i] == 2 and b > 0: b -= 1 else: ans += 2 return ans def main(): print(test_case(0)) if __name__ == '__main__': main() ```
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 s1=input() a=s1.lower() s2=input() b=s2.lower() os1=0 os2=0 if a==b: print(0) if a<b: print('-1') if a>b: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
```python n=int(input()) m=int(input()) a=int(input()) if n%a==0: b=n/a else: b= n//a +1 if m%a==0: c=m/a else: c=m//a+1 print(max(b,c)) ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
```python # // #include<stdio.h> # // int main() # // { # // int n,x; # // scanf("%d %d" , &n , &x); # // int count = 0; # // char sign; # // int d; # // for(int i = 0 ; i<n ; i++) # // { # // scanf("%c %d" , &sign , &d); # // if(sign == '+') x += d; # // else if(sign == '-' && x-d > 0) x -= d; # // else if(sign == '-' && x-d < 0) count++; # // } # // printf("%d %d" , x , count); # // } n,x = map(int,input().split()) count = 0 for i in range(n): sign,d = map(str,input().split()) packs = int(d) if(sign == '+'): x += packs elif(sign == '-' and x - packs > 0): x -= packs elif(sign == '-' and x - packs < 0): count += 1 print(x,count) ```
MatrixStudio/Codeforces-Python-Submissions
Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her . 1. Let *u**i* be the cost of the *i*-th cheapest stone (the cost that will be on the *i*-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
```python n = int(input()) a = list(map(int, input().split())) k = int(input()) b = [0] sum = 0 for i in range(n): sum += a[i] b.append(sum) a.sort() c = [0] for i in range(n): sum += a[i] c.append(sum) for i in range(k): temp = list(map(int, input().split())) if temp[0] == 1: l = temp[1] r = temp[2] print(b[r] - b[l -1]) else: l = temp[1] r = temp[2] print(c[r] - c[l - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two set of points. The first set is determined by the equation *A*1*x*<=+<=*B*1*y*<=+<=*C*1<==<=0, and the second one is determined by the equation *A*2*x*<=+<=*B*2*y*<=+<=*C*2<==<=0. Write the program which finds the number of points in the intersection of two given sets.
```python vet1 = input().split() vet2 = input().split() a = int(vet1[0]) b = int(vet1[1]) c = int(vet1[2]) p = int(vet2[0]) q = int(vet2[1]) r = int(vet2[2]) detlow = a*q-b*p det1 = q*c-b*r det2 = p*c-a*r if(detlow == 0): print(0) elif((a == 0 and b == 0) and (p == 0 and q == 0) and c != r): print(0) elif((a == 0 and b == 0) and (p == 0 and q == 0) and c != r): print(0) elif(a == 0 and b == 0 and c == 0): print(-1) elif(p == 0 and q == 0 and r == 0): print(-1) elif(detlow == 0 and det1 == 0 and det2==0): print(-1) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are *n* days, at the *i*-th day, Arya finds *a**i* candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later. Your task is to find the minimum number of days Arya needs to give Bran *k* candies before the end of the *n*-th day. Formally, you need to output the minimum day index to the end of which *k* candies will be given out (the days are indexed from 1 to *n*). Print -1 if she can't give him *k* candies during *n* given days.
```python a,b = map(int,input().split()) l = list(map(int,input().split())) s,x =0,0 for i in l: x+=1;s+=i if s<=8:b-=s;s =0 else:b-=8;s-=8 if b<=0:break if b>0:print(-1) else:print(x) ```
MatrixStudio/Codeforces-Python-Submissions
You're given a tree with $n$ vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
```python n = int(input()) d = {i: [] for i in range(1, n + 1)} for i in range(n - 1): a, b = map(int, input().split()) d[a].append(b) d[b].append(a) if n & 1: print(-1) else: val = [1 for i in range(n + 1)] par = [-1 for i in range(n + 1)] par[1] = 1 stack = [1] while stack: u = stack[-1] f = 0 for i in d[u]: if par[i] == -1: par[i] = u stack.append(i) f = 1 if f == 0: stack.pop() val[par[u]] += val[u] ans = 0 for i in range(2, n + 1): if val[i] % 2 == 0: ans += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A permutation is a sequence of integers *p*1,<=*p*2,<=...,<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. Let's denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size of permutation *p*1,<=*p*2,<=...,<=*p**n*. Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation *p* that for any *i* (1<=≤<=*i*<=≤<=*n*) (*n* is the permutation size) the following equations hold *p**p**i*<==<=*i* and *p**i*<=≠<=*i*. Nickolas asks you to print any perfect permutation of size *n* for the given *n*.
```python #[a, b, c, d] = [int(x) for x in input().split()] c=int(input()) if c%2==0: for i in range(0,c): print(c-i," ") else: print("-1") ```
MatrixStudio/Codeforces-Python-Submissions
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with *n* buttons. Determine if it is fastened in a right way.
```python #Berland and fashion n = int(input()) lst = list(map(int,input().split())) count = 0 for item in lst: if item == 0: count += 1 if (len(lst) == 1 and lst[0] == 0) or count > 1: print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Dreamoon wants to climb up a stair of *n* steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer *m*. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
```python #https://codeforces.com/problemset/problem/476/A n,m=map(int,input().split(' ')) ans=-1 s=0 if n%2==0: s=n/2 else: s=(n+1)/2 s=int(s) for i in range(s,n+1): if i%m==0: ans=i; break print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic. Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.
```python n = int(input()) p = input().split(" ") p = [int(p[i]) for i in range (2*n)] c = 0 # slides the value at index ind to i+1, returns number of spots slid def slide(i, ind): temp = p[ind] for j in range (ind-1, i, -1): p[j+1] = p[j] print(p) p[i+1] = temp return ind-i-1 for i in range (0, 2*n, 2): ind = p.index(p[i], i+1) c += slide(i, ind) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·*n* people in the group (including Vadim), and they have exactly *n*<=-<=1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. *i*-th person's weight is *w**i*, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash. Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks. Help the party to determine minimum possible total instability!
```python n = int(input()) l = list(map(int, input().split())) nat = False for i in range(2 * n): for c in range(i + 1, 2 * n): ls = l[:] ls[i] = 0 ls[c] = 0 ls = sorted(ls) now = 0 for loc in range(1, len(ls), 2): now += ls[loc] - ls[loc - 1] if now < nat or str(nat) == 'False': nat = now print(nat) ```
MatrixStudio/Codeforces-Python-Submissions
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first *n*. He writes down the following sequence of numbers: firstly all odd integers from 1 to *n* (in ascending order), then all even integers from 1 to *n* (also in ascending order). Help our hero to find out which number will stand at the position number *k*.
```python n, k = map(int, input().split()) if n == k: print(k - 1) else: result = k if k <= n // 2 else (k - n // 2) * 2 print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times. Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise. Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
```python n=int(input()) m=list(map(int,input().split())) chest=0 biceps=0 back=0 for i in range(n): if i%3==0: chest+=m[i] elif i%3==1: biceps+=m[i] else: back+=m[i] n=max(back,biceps,chest) if n==biceps: print('biceps') elif n==back: print('back') else: print('chest') ```
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 x1=input() x2=input() x=x1+x2 res1 = ''.join(sorted(x)) x3=input() res3 = ''.join(sorted(x3)) if (res1==res3): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence. Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring. Substring is a continuous subsequence of a string.
```python nameofAI = input() nameofPhone = input() print(nameofAI.count(nameofPhone)) ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
```python n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] a = [x for x in a if x <= 0] a.sort() print(sum(a[:min(m, len(a))])*-1) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (*x*,<=*y*) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (*x*0,<=*y*0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (*x*0,<=*y*0). Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers. The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.
```python n, x, y = map(int, input().split()) lines = set() for _ in range(n): x1, y1 = map(int, input().split()) if x1 != x: k = (y1 - y) / (x1-x) b = y - k * x else: k = None b = x1 lines.add((k, b)) print(len(lines)) ```
MatrixStudio/Codeforces-Python-Submissions
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
```python import sys n=int(input()) a=[0]*n b=[0]*n for i in range(n): a[i],b[i]=map(int,input().split()) b[i]=a[i]+b[i] for i in range(n): for j in range(n): if a[i]==b[j] and b[i]==a[j] and i!=j: print("YES") sys.exit() print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
```python def check(x): global a, s, n if s - x*(n-1) <= 0: return True return False def lbp(): global a, s, n low = max(a) high = s while high - low > 1: mid = (high + low) // 2 if check(mid): high = mid else: low = mid if check(low): return low return high def main(): global a, n, s n = int(input()) a = list(map(int, input().split())) s = sum(a) print(lbp()) a = [] s = 0 n = 0 main() ```
MatrixStudio/Codeforces-Python-Submissions
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place. But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams. Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania. It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
```python from math import gcd a, b = map(int, input().split()) a, b = min(a, b), max(a, b) g = gcd(a, b) print(f"{a // g}/{b // g}") ```
MatrixStudio/Codeforces-Python-Submissions
You are given an *n*<=×<=*m* rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table   we obtain the table:   A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
```python n, m = map(int, input().split()) t = [input() for i in range(n)] lt = [False] * (n - 1) def tc(j): global lt lt2 = list(lt) for i in range(n - 1): if not lt2[i]: if t[i][j] < t[i + 1][j]: lt2[i] = True elif t[i][j] > t[i + 1][j]: return True lt = lt2 return False print(sum(1 for j in range(m) if tc(j))) ```