source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Your friend recently gave you some slimes for your birthday. You have *n* slimes all initially with value 1. You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other *n*<=-<=1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value *v*, you combine them together to create a slime with value *v*<=+<=1. You would like to see what the final state of the row is after you've added all *n* slimes. Please print the values of the slimes in the row from left to right.
```python def main(): n, res, mask, x = int(input()), [], 1, 1 while n >= mask: if n & mask: res.append(x) mask *= 2 x += 1 print(*[x for x in reversed(res) if x]) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has an array, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array *a**i*, *a**j* (*i*<=≠<=*j*); - he simultaneously increases number *a**i* by 1 and decreases number *a**j* by 1, that is, executes *a**i*<==<=*a**i*<=+<=1 and *a**j*<==<=*a**j*<=-<=1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
```python n=int(input()) L=input().split() sum=0 for i in L: sum+=int(i) i=n while(sum%i!=0): i-=1 print(i) ```
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() line=line.split() s=0 for i in range(n): line[i]=int(line[i]) line.sort() for i in range(n): s=s+(i+2)*line[i] s=s-line[n-1] print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Anton has the integer *x*. He is interested what positive integer, which doesn't exceed *x*, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.
```python def sod(n): sm = 0 while n != 0: n1 = n%10 sm += n1 n = n//10 return sm n = int(input()) size = len(str(n)) new = str(n) new = int(new[0])-1 new = str(new) #print(new) num = new for i in range(size-1): num += '9' num = int(num) res1 = sod(n) res2 = sod(num) if res1 >= res2: print(n) else: print(num) ```
MatrixStudio/Codeforces-Python-Submissions
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)). Max starts to type all the values from *a* to *b*. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator. For example if *a*<==<=1 and *b*<==<=3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.
```python from math import * d = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6] l, r = map(int, input().split()) ans = 0 def calc(a): res = 0 while (a > 0): res += d[a % 10] a //= 10; return res for a in range(l, r + 1): ans += calc(a) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights. Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible. Write the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
```python from collections import * import math from heapq import * def checker(): n, k = map(int, input().split()) arr = list(map(int, input().split())) max_sum = sum(arr[:k]) max_idx = 0 curr_sum = max_sum start = 0 end = k - 1 while(end + 1 < n): curr_sum -= arr[start] start += 1 end += 1 curr_sum += arr[end] if curr_sum < max_sum: max_sum = curr_sum max_idx = start + 1 if curr_sum < max_sum: max_sum = curr_sum max_idx = start + 1 print(max_idx) return checker() # testcases = int(input()) # for _ in range(testcases): # checker() ```
MatrixStudio/Codeforces-Python-Submissions
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of *n* men (*n* is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore. The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends. You are asked to calculate the maximum total number of soldiers that may be killed during the game.
```python import math def main(): n = int(input()) print(math.floor(1.5 * n)) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly *n*1 balls and second player's box contains exactly *n*2 balls. In one move first player can take from 1 to *k*1 balls from his box and throw them away. Similarly, the second player can take from 1 to *k*2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
```python n1, n2, k1, k2 = map(int, input().split()) if n1>k2: print("First") elif n2>k1: print("Second") ```
MatrixStudio/Codeforces-Python-Submissions
Vika has *n* jars with paints of distinct colors. All the jars are numbered from 1 to *n* and the *i*-th jar contains *a**i* liters of paint of color *i*. Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1<=×<=1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color *x*, then the next square will be painted in color *x*<=+<=1. In case of *x*<==<=*n*, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops. Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
```python def stickProb(): stickSize=int(input()) count=0 duplicates=1 if(stickSize>=12): duplicates=2 if(stickSize%2!=0 or int(stickSize/2-2)<=0): print(0) else: if(stickSize/2-2)%2==0: print(int((stickSize/2-2)/2)) else: print(int((stickSize/2-2)/2)+1) def paintProb(): jarNumber=int(input()) colors=input().split() for element in colors: element=int(element) #dups where=[] for keyColor in range(len(colors)): if(colors[keyColor]==min(colors)): where.append(keyColor) if(len(where)==1): for keyColor in range(len(colors)): if(colors[keyColor]==min(colors)): print(jarNumber*(int(colors[keyColor])+jarNumber-1)) else: distance=0 print('len(where)',len(where)) for element in range(len(where)-1): print(where[element+1]-where[element]) distance=max([where[element+1]-where[element],distance]) distance=max([distance,jarNumber-where[len(where)-1]-1+where[0]]) print("answer:",jarNumber*(int(colors[where[0]]))+distance) paintProb() ```
MatrixStudio/Codeforces-Python-Submissions
Consider a linear function *f*(*x*)<==<=*Ax*<=+<=*B*. Let's define *g*(0)(*x*)<==<=*x* and *g*(*n*)(*x*)<==<=*f*(*g*(*n*<=-<=1)(*x*)) for *n*<=&gt;<=0. For the given integer values *A*, *B*, *n* and *x* find the value of *g*(*n*)(*x*) modulo 109<=+<=7.
```python #include<iostream> #include<string> using namespace std; int main() { int n,k,inp,cur=0,i,ans=-1; cin>>n>>k; for(i=1;i<=n;i++) { cin>>inp; cur+=inp; if(cur<=8) { k-=cur; cur=0; } else { cur-=8; k-=8; } if(k<=0&&ans==-1) ans=i; } cout<<ans; return 0; } ```
MatrixStudio/Codeforces-Python-Submissions
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture. In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals *n*, then the player wins, otherwise the player loses. The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals *n*.
```python from sys import stdin as sin def aint():return int(sin.readline()) def amap():return map(int,sin.readline().split()) def alist():return list(map(int,sin.readline().split())) def astr():return str(sin.readline().split()) from collections import defaultdict as dd n = int(input()) if n-10<=11 and n-10>=1: if n==20: print(15) elif n-10==11: print(4) elif n-10==1: print(5) else: print(4) else: print(0) ```
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())) c=0 maxi=0 for i in list(set(l)): c=l.count(i) maxi=max(maxi,c) print(maxi) ```
MatrixStudio/Codeforces-Python-Submissions
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have *n* layers. The first layer is hate, second one is love, third one is hate and so on... For example if *n*<==<=1, then his feeling is "I hate it" or if *n*<==<=2 it's "I hate that I love it", and if *n*<==<=3 it's "I hate that I love that I hate it" and so on. Please help Dr. Banner.
```python n=int(input()) k='' for i in range(1,n+1): if(i%2!=0): k=k+'I hate it' elif(i%2==0): k=k+'I love it' if(i+1<=n): k=k+' then ' print(k) ```
MatrixStudio/Codeforces-Python-Submissions
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches. You are given a length equal to *n* centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches. Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
```python n=int(input()) n+=1 f = n//36 i = (n%36)//3 print(f,i) ```
MatrixStudio/Codeforces-Python-Submissions
Jzzhu has invented a kind of sequences, they meet the following property: You are given *x* and *y*, please calculate *f**n* modulo 1000000007 (109<=+<=7).
```python x,y=map(int,input().split()) a=[x,y,y-x,-x,-y,x-y] n=int(input()) print(a[(n-1)%6]%1000000007) ```
MatrixStudio/Codeforces-Python-Submissions
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not. You're given a number. Determine if it is a magic number or not.
```python n = int(input()) s = str(n) num = [2,3,5,6,7,8,9] duo4 = ['444','4444','44444','444444','4444444','44444444','444444444','44444444444'] for i in num: if str(i) in s: print('NO') break for x in duo4: if x in s: print('NO') break else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: - either it only contains uppercase letters; - or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed. Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
```python t = input() for i in range(1, len(t)): if ord(t[i]) > 97: m = 1 break else: m = 0 if m == 0: print(t.title()) else: print(t) ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
```python i = int(input()) if i%2=0 :print('YES') else:print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
```python n= int(input()) c= [] o=True for i in range(n): c.append(list(map(int,input().split()))) for i in range(n): d=[] for j in range(n): d.append(c[j][i]) if sum(d) != 0: print("NO") o =False break if o: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird! The cake is a *n*<=×<=*n* square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be? Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
```python n= int(input()) matrix = [ [ 'c' for i in range(n) ] for j in range(n)] for i in range(n): matrix[i]=list(input()) #print(matrix) ans=0 for i in range(n): count=0 for j in range(n): if matrix[i][j]=='C': count=count+1 ans=ans+(count*(count-1))/2 for i in range(n): count=0 for j in range(n): if matrix[j][i]=='C': count=count+1 ans=ans+(count*(count-1))/2 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are *n* schools numerated from 1 to *n*. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools *i* and *j* costs and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
```python n = int(input()) if n == 1: print(0) else: if n%2 == 0: print(n//2 - 1) else: print((n+1)//2 - 1) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
```python s=input() c=0 p=[0] d=False for player in s[:1]: if player==p: c+=1 if c>=7: d=True break else: c=1 p=player if d: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You are given a chessboard of size 1<=×<=*n*. It is guaranteed that *n* is even. The chessboard is painted like this: "BWBW...BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to . In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied. Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
```python n=int(input()) r1,r2=0,0 p=list(map(int,input().split())) for i in range(n//2): r1+=abs(2*i+1-p[i]) r2+=abs(2*i+2-p[i]) print(min(r1,r2)) ```
MatrixStudio/Codeforces-Python-Submissions
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations: - Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains. A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains. You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).
```python x=0 n=int(input()) s=input() for i in range(n): if s=="++X" x+=1 elif s=="--X": x-=1 else: continue print(x) ```
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 sz = int(input()) lo = list(map(int,input().split()));lt = sorted(lo) q = int(input()) for i in range(q): t,s,e = map(int,input().split()) if t == 1: print(sum(lo[(s-1):e])) else: print(sum(lt[(s-1):e])) ```
MatrixStudio/Codeforces-Python-Submissions
According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.
```python n,m=map(int,input().split()) s=input() if len(set(list(s)))!=1: print('NO') exit() a=[s[0]] for i in range(n-1): s=input() if len(set(list(s)))==1 and s[0]!=a[-1]: pass else: print('NO') exit() print('YES') ```
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 x=list(input()) y=list(input()) z=list() for i in range(len(x)): z=z.append(int(x[i]!=y[i])) print(*z,sep='') ```
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() a = list(map(int,input().split())) ans = [a[i+1] - a[i] for i in range(n-1) if s[i] == "R" and s[i+1]== "L"] if ans: print(min(ans)//2) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
```python input() s=m=j=0 for i in map(int,input().split()): if j<i:m+=1 else: s=max(s,m) m=1 j=i print(max(s,m)) ```
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 word = input().strip() upper = 0 alphabet = ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"] for x in word: if x in alphabet: upper = upper + 1 if upper > len(word)//2: print (word.upper()) else: print(word.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome. In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment. However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.
```python s=input() h=int(s[:2]) m=int(s[3:]) mm=int(s[1]+s[0]) if m<mm: print(s[0]+s[1]+':'+str(mm)) else: h=(h+1)%24; if(h<10): h='0'+str(h) print(h+':'+h[1]+h[0]) else: t=str(h) print(t+':'+t[1]+t[0]) ```
MatrixStudio/Codeforces-Python-Submissions
Three sons inherited from their father a rectangular corn fiend divided into *n*<=×<=*m* squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, which is why he bequeathed to divide his field into three parts containing *A*, *B* and *C* tons of corn. The field should be divided by two parallel lines. The lines should be parallel to one side of the field and to each other. The lines should go strictly between the squares of the field. Each resulting part of the field should consist of at least one square. Your task is to find the number of ways to divide the field as is described above, that is, to mark two lines, dividing the field in three parts so that on one of the resulting parts grew *A* tons of corn, *B* on another one and *C* on the remaining one.
```python # 3 3 # 1 1 1 # 1 1 1 # 1 1 1 # 3 3 3 # 2 5 # 1 1 1 1 1 # 2 2 2 2 2 # 3 6 6 n, m = input().split() n = int(n) m = int(m) A = [] for i in range(n): A.append([]) tmp = input().split() for obj in tmp: A[i].append(int(obj)) req = input().split() for i in range(len(req)): req[i] = int(req[i]) col = [] row = [] for i in range(m): # get column sum colsum = 0 for j in range(n): colsum += A[j][i] col.append(colsum) for i in range(n): # get row sum rowsum = 0 for j in range(m): rowsum += A[i][j] row.append(rowsum) # print(col) # print(row) ans = 0 # combine column if len(col) >= len(req): combine = [] for i in range(1, m+1): for j in range(i+1, m+1): tmp = [i, j-i, m-j] if 0 not in tmp: combine.append(tmp) for obj in combine: counter = 0 new = [] for i in range(len(obj)): # [1, 1, 3] tmp = 0 for j in range(counter, counter + obj[i]): tmp += col[j] new.append(tmp) counter += obj[i] # print(sorted(new)) if sorted(new) == req: ans += 1 if len(row) >= len(req): rowbine = [] for i in range(1, n+1): for j in range(i+1, n+1): tmp = [i, j-i, m-j] if 0 not in tmp: rowbine.append(tmp) for obj in rowbine: counter = 0 new = [] for i in range(len(obj)): # [1, 1, 3] tmp = 0 for j in range(counter, counter + obj[i]): tmp += col[j] new.append(tmp) counter += obj[i] # print(sorted(new)) if sorted(new) == req: ans += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters. Your task is to add spaces to the text by the following rules: - if there is no punctuation mark between two words, then they should be separated by exactly one space - there should be no spaces before each punctuation mark - there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.
```python s = input().replace(',', ' , ').split() for i in range(len(s) - 1): if s[i] == ',': print(s[i], end=' ') elif s[i] != ',' and s[i + 1] == ',': print(s[i], end='') else: print(s[i], end=' ') print(s[-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of *k*<=&gt;<=1 Pokemon with strengths {*s*1,<=*s*2,<=*s*3,<=...,<=*s**k*} tend to fight among each other if *gcd*(*s*1,<=*s*2,<=*s*3,<=...,<=*s**k*)<==<=1 (see notes for *gcd* definition). Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
```python import math def gprimes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes N = int(input()) nums = input().split(" ") nums = [int(x) for x in nums] sq = math.sqrt(max(nums)) primes = gprimes(int(sq)+1) for i in nums: if(i >= sq): primes.append(i) maxx = 0 count = 0 for prime in primes: count = 0 for num in nums: if(num % prime == 0): count+=1 maxx = max(count,maxx) print(primes) print(maxx) ```
MatrixStudio/Codeforces-Python-Submissions
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names. This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
```python a=input() n=0 for _ in a: t=a.count(_) n+=1 if t>1: n=n-(t-1) n=n-(t-1)/2 if n%2==0: print('CHAT WITH HER!') else: print('IGNORE HIM!') ```
MatrixStudio/Codeforces-Python-Submissions
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
```python n,m=map(int,input().split()) for i in range(n): for j in range(n): if i==j: print(m) else: print("0") ```
MatrixStudio/Codeforces-Python-Submissions
You are given a sequence of integers of length $n$ and integer number $k$. You should print any integer number $x$ in the range of $[1; 10^9]$ (i.e. $1 \le x \le 10^9$) such that exactly $k$ elements of given sequence are less than or equal to $x$. Note that the sequence can contain equal elements. If there is no such $x$, print "-1" (without quotes).
```python v1, v2 = map(int, input().split()) v = [1] + sorted(list(map(int, input().split()))) if v.count(v[v2]) == v1: print(v[v2]) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* numbers *a*1,<=*a*2,<=...,<=*a**n*. You can perform at most *k* operations. For each operation you can multiply one of the numbers by *x*. We want to make as large as possible, where denotes the bitwise OR. Find the maximum possible value of after performing at most *k* operations optimally.
```python n, k, x = map(int, input().split()) numbers = list(map(int, input().split())) res = numbers[0] num = max(numbers) checked_max = False if num == res: res = res * x ** k checked_max = True for i in numbers: if i == num and not checked_max: i = i * x ** k checked_max = True res = res | i print(res) ```
MatrixStudio/Codeforces-Python-Submissions
There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year? It's guaranteed that the optimal answer is always integer.
```python n=input() alist=[int(x) for x in n.split()] alist.sort() print(alist[1]-alist[0]+(alist[2]-alist[1])) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
```python st=input() st=st[1:-1] m=set(st.split(', ')) print(len(m)) ```
MatrixStudio/Codeforces-Python-Submissions
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem. You are given an integer *n* no less than 12, express it as a sum of two composite numbers.
```python def isprime(n): for i in range(2,int(n/2)+1): if n%i==0: return 0 return 1 n=int(input()) l=[] x=int(n/2) for i in range(3): if isprime(x): x=x+1 else: l.append(x) l.append(n-x) break print(' '.join(l)) ```
MatrixStudio/Codeforces-Python-Submissions
Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number *x* is really big if the difference between *x* and the sum of its digits (in decimal representation) is not less than *s*. To prove that these numbers may have different special properties, he wants to know how rare (or not rare) they are — in fact, he needs to calculate the quantity of really big numbers that are not greater than *n*. Ivan tried to do the calculations himself, but soon realized that it's too difficult for him. So he asked you to help him in calculations.
```python n, s = map(int, input().split()) def R(n): ans = 0 while True: ans += n % 10 n = n // 10 if n == 0: return ans current = n - R(n) if current < s: print("0") else: extra = n % 10 + 1 lo,hi = 0, n while lo < hi - 1: mid = lo + (hi - lo)//2 if mid - R(mid) < s: lo = mid else: hi = mid print(n - hi + 1) ```
MatrixStudio/Codeforces-Python-Submissions
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath. With that begins the watch of Jon Snow. He is assigned the task to support the stewards. This time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him. Can you find how many stewards will Jon support?
```python n = int(input()) stewards = list(map(int, input().split())) count = 0 for i in range(n): bigger = False smaller = False for x in range(n): if stewards[x] < stewards[i]: smaller = True if stewards[x] > stewards[i]: bigger = True if bigger and smaller: count += 1 print(count) ```
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 n = input() k = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' m = 'abcdefghijklmnopqrstuvwxyz' u,l = 0,0 for i in n: if i in k: u += 1 if i in m: l += 1 if u > l: print(n.upper()) else: print(n.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas. Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into *n* consecutive segments, each segment needs to be painted in one of the colours. Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.
```python #codeforces_957A_live n = int(input()) si = input() flag = True if "MM" in si or "CC" in si or "YY" in si or not("?" in si): print("No") elif "???" in si or "??" in si: print("Yes") elif si.startswith("?") or si.endswith("?"): print("Yes") else: for k in range(n): if si[k] == "?" and si[k-1] != si[k+1]: print("Yes") flag = False break; if flag : print("No") ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section. Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1<=×<=5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture: As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.
```python #!/usr/bin/python3 # n, t = input().split(" ") # a = input() # n = int(n) # t = int(t) # s = list(a) # while(t != 0): # for i in range(n-1): # if s[i] == 'B' and s[i+1] == 'G': # s[i] = 'G' # s[i + 1] = 'B' # t -= 1 # break # print("".join(s)) # t = int(input()[2:]) # s = input() # while t: # s = s.replace('BG', 'GB') # t -= 1 # print(s) # print(s) # n = input # c = p = 0 # for i in' '*int(n()): # s = n() # c += s != p # p = s # print(c) # s = input() # d = {".": "0", "-.": "1", "--": "2"} # s = s.replace("--", "2") # s = s.replace("-.", "1") # s = s.replace(".", "0") # print(s) # y = int(input()) # while(len(set(str(y))) < 4): # y += 1 # print(y) # for i in range(2): # o = "" # r = input().replace(" ", "") # for j in r: # if int(j) % 2 == 0: # o += "1" # else: # o += "0" # print(o) # s = [[1]*5 for _ in range(5)] # for i in 1, 2, 3: # for j, v in zip((1, 2, 3), map(int, input().split())): # for k, d in (-1, 0), (1, 0), (0, -1), (0, 1), (0, 0): # s[i+k][j+d] += v # for i in 1, 2, 3: # for j in 1, 2, 3: # print(s[i][j] % 2, end='') # print() # s = input() # u = l = 0 # for i in s: # if i.lower() == i: # l += 1s # else: # u += 1 # if u == l or l > u: # s = s.lower() # elif u > l: # s = s.upper() # print(s) # n=int(input()) # a=[*map(int,input().split())] # print(a) # b=a.index(max(a))+a[::-1].index(min(a)) # print(b) # print(b-(b>=n)) # def I(): return map(int, input().split()) # n = int(input()) # for _ in range(n): # i = int(input()) # if i % 4 == 0: # print("YES") # else: # print("NO") # n = [] # with open("sort.in", 'r') as f: # l = f.read().strip('\n').split(" ") # nums = [] # for i in l: # if "\n" in i: # _, k = i.split("\n") # nums.append(int(k)) # else: # nums.append(int(i)) # n = sorted(nums) # print(n) # with open('sorted.txt', 'w') as d: # d.write("\n".join(str(i) for i in n)) # a, b = map(int, input().split()) # c = 0 # while a <= b: # a *= 3 # b *= 2 # c += 1 # print(c) # i = input # case = int(i()) # for _ in range(case): # n, k = map(int, input().split()) # a = {} # q = "" # for _ in range(n): # l = i() # q += l # for w in l.split(): # if w not in a: # a[w] = 1 # else: # a[w] += 1 # for _ in range(k): # query = i() # if query in a: # print(q.count(query)) # else: # print(0) # i = input # n = int(i()) # c = 0 # for _ in range(n): # if i().split().count('1') >= 2: # c += 1 # print(c) # i = input() # v = input() # if i.lower() == v.lower(): # print("0") # else: # print(['1', '-1'][sorted(i, key=str.lower) > sorted(v, key=str.lower)] n = int(input()) a = list(map(int, input().split())) r = 0 for i in range(n): j = i while j+1 < n and a[j] <= a[j+1]: j += 1 while j+1 < n and a[j] >= a[j+1]: j += 1 r = max(r, j-i+1) print(r) ```
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() up=0 low=0 for i in s: if i.isupper(): up+=1 else: low+=1 if(up>low): print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number *k* is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by *k*2, and the loser's score is multiplied by *k*. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all *n* games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
```python #include <stdio.h> #include <stdlib.h> int compar (const void *a, const void *b) { return *((int *) a) - *((int *) b); } int main () { int n, k; int i, j; int begin[26], end[26]; for (i = 0; i < 26; i++) begin[i] = end[i] = 0; (void) scanf ("%d %d", &n, &k); (void) getchar (); for (i = 1; i <= n; i++) { int c = getchar (); if (!begin[c - 'A']) begin[c - 'A'] = i; end[c - 'A'] = i; } qsort (begin, 26, sizeof (int), compar); qsort (end, 26, sizeof (int), compar); for (i = 0; !begin[i]; i++); for (j = 0; !end[j]; j++); while (i < 26 && j < 26 && k >= 0) { if (begin[i] > end[j]) { k++, j++; continue; } if (begin[i] <= end[j]) { k--, i++; continue; } } if (k >= 0) printf ("NO\n"); else printf ("YES\n"); return 0; } ```
MatrixStudio/Codeforces-Python-Submissions
Not long ago Billy came across such a problem, where there were given three natural numbers *A*, *B* and *C* from the range [1,<=*N*], and it was asked to check whether the equation *AB*<==<=*C* is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root *d*(*x*) of the number *x* is the sum *s*(*x*) of all the digits of this number, if *s*(*x*)<=≤<=9, otherwise it is *d*(*s*(*x*)). For example, a digital root of the number 6543 is calculated as follows: *d*(6543)<==<=*d*(6<=+<=5<=+<=4<=+<=3)<==<=*d*(18)<==<=9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. *d*(*xy*)<==<=*d*(*d*(*x*)*d*(*y*)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.
```python n , ans , a = int(input()) , 0 , [0] * 10 for i in range(1,n+1): ans -= (int)(n/i) a[i % 9] += 1 for i in range(9): for j in range(9): ans += a[i] * a[j] * a[(i * j) % 9] print (ans) ```
MatrixStudio/Codeforces-Python-Submissions
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals *n*. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position *a*1 to position *b*1, the second — from *a*2 to *b*2 What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
```python n, x = map(int, input().split()) minx = None maxx = None for i in range(n): a, b = map(int, input().split()) small = a if a < b else b big = b if b > a else a if minx: minx = small if small > minx else minx maxx = big if big < maxx else maxx else: minx = small maxx = big if minx and minx > maxx: print(-1) else: print(min(abs(x - minx), abs(x - maxx))) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky.
```python #In the name of GOD n = input() if ('4' in n and '7' in n) or ('4' not in n and '7' not in n): print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the *i*-th letter of her name should be 'O' (uppercase) if *i* is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to *n*. Fibonacci sequence is the sequence *f* where - *f*1<==<=1, - *f*2<==<=1, - *f**n*<==<=*f**n*<=-<=2<=+<=*f**n*<=-<=1 (*n*<=&gt;<=2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.
```python num = int(input()) lis = [] string = "" def fib(n): if n < 2: return n else: return fib(n-1) + fib(n-2) for x in range(num): lis.append(fib(x)) for i in range(1,num+1): print(i) if i in lis: string = string + "O" else: string = string + "o" print (string) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 25 20:03:39 2021 @author: haining """ a,b= [int(x) for x in input().split()] listb =[1,b+1] for i in range(a): c = [int(x) for x in input().split()] for i in range(c[0]): if c[1,-1] in listb: listb.remove(c[1,-1]) if listb == []: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
```python q = input() a = 'abcdefghijklmnopqrstuvwxyz' print(len(set([i for i in q if i in a]))) ```
MatrixStudio/Codeforces-Python-Submissions
When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the condition... actually, it doesn't matter. Igor K. quickly found the formula and got the so passionately desired Accepted. However, the professor wasn't very much impressed. He decided that the problem represented on Timmy's Online Judge was very dull and simple: it only had three possible colors of flag stripes and only two limitations. He suggested a complicated task to Igor K. and the fellow failed to solve it. Of course, we won't tell anybody that the professor couldn't solve it as well. And how about you? Can you solve the problem? The flags consist of one or several parallel stripes of similar width. The stripes can be one of the following colors: white, black, red or yellow. You should find the number of different flags with the number of stripes from *L* to *R*, if: - a flag cannot have adjacent stripes of one color; - a flag cannot have adjacent white and yellow stripes; - a flag cannot have adjacent red and black stripes; - a flag cannot have the combination of black, white and red stripes following one after another in this or reverse order; - symmetrical flags (as, for example, a WB and a BW flag, where W and B stand for the white and black colors) are considered the same.
```python print("_RANDOM_GUESS_1689419957.1878912")# 1689419957.1879108 ```
MatrixStudio/Codeforces-Python-Submissions
You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands. Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand. Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.
```python from functools import reduce line = input() line=[int(x) for x in line.split()] if line[2]==0 and( line[1]==0 or line[0]==0) : print(0) else: print( (reduce(lambda x,y:x+y,line)//2)*2) ```
MatrixStudio/Codeforces-Python-Submissions
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized. On that night, Sengoku constructed a permutation *p*1,<=*p*2,<=...,<=*p**n* of integers from 1 to *n* inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with *n* meteorids, colours of which being integer sequences *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n* respectively. Meteoroids' colours were also between 1 and *n* inclusive, and the two sequences were not identical, that is, at least one *i* (1<=≤<=*i*<=≤<=*n*) exists, such that *a**i*<=≠<=*b**i* holds. Well, she almost had it all — each of the sequences *a* and *b* matched exactly *n*<=-<=1 elements in Sengoku's permutation. In other words, there is exactly one *i* (1<=≤<=*i*<=≤<=*n*) such that *a**i*<=≠<=*p**i*, and exactly one *j* (1<=≤<=*j*<=≤<=*n*) such that *b**j*<=≠<=*p**j*. For now, Sengoku is able to recover the actual colour sequences *a* and *b* through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.
```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) answer = [0] * n for i in range(n): if a[i] == b[i]: answer[i] = i + 1 ind1 = -1 ind2 = -1 for i in range(n): if a[i] != b[i]: if ind1 == -1: ind1 = i else: ind2 = i if ind1 and ind2 == -1: for i in range(1, n + 1): if i not in answer: answer[ind1] = i print(*answer) exit() else: answer = a[:] answer[ind1] = b[ind1] if len(set(answer)) == n: print(*answer) exit() answer[ind2] = b[ind2] print(*answer) exit() ```
MatrixStudio/Codeforces-Python-Submissions
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner. Output the probability that SmallR will win the match.
```python def main(): #Soma de PG infinita a, b, c, d = [int(x) for x in input().split()] pSmallR = a/b pZanoes = c/d return pSmallR / (1 - ((1-pSmallR)*(1-pZanoes))) print(main()) ```
MatrixStudio/Codeforces-Python-Submissions
Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*'). In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin. Help Amr to achieve his goal in minimum number of steps.
```python import math r,x,y,x1,y1=map(int,input().split()) d=math.sqrt((x1-x)**2+(y1-y)**2) c=math.ceil(d/(2*r)) if(c==1): print(int(1)) else: print(int(c)) ```
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 i = [int(x) for x in input().split(' ')] f = min(i) r = int((max(i)-f)/2) print(f,r) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of *a* in any order. What is the maximum possible number of indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), such that *a**i*<=+<=1<=&gt;<=*a**i*.
```python import sys input = sys.stdin.readline from collections import Counter as C def miis(): return map(int, input().split()) for _ in range(1): n = int(input()) a = list(miis()) c = C(a) ans = n-1 for i in c: ans = min(n-c[i], ans) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters. Help her to find the maximum number of "nineteen"s that she can get in her string.
```python input_val = input() c = input_val.count print(max(0, min((c('n')-1)//2, c('e')//3, c('t'), c('i')))) ```
MatrixStudio/Codeforces-Python-Submissions
A positive integer is called a 2-3-integer, if it is equal to 2*x*·3*y* for some non-negative integers *x* and *y*. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not. Print the number of 2-3-integers on the given segment [*l*,<=*r*], i. e. the number of sich 2-3-integers *t* that *l*<=≤<=*t*<=≤<=*r*.
```python # Aniket Hend ans=0 l,r=map(int,input().split()) for i in range(100): for j in range(100): num=2**i*3**j if l<=num<=r: ans+=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together. More detailed, there are *n* pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: 1. Value *x* and some direction are announced, and all boys move *x* positions in the corresponding direction. 1. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that *n* is even. Your task is to determine the final position of each boy.
```python import sys sys.stderr = sys.stdout def dance(n, q, C): e = 0 o = 0 for c in C: if c[0] == 1: x = c[1] if x % 2: e, o = (o - x) % n, (e - x) % n else: e = (e - x) % n o = (o - x) % n elif c[0] == 2: e, o = (o + 1) % n, (e - 1) % n for i in range(0, n, 2): yield (i + e) % n + 1 yield (i + 1 + o) % n + 1 def main(): n, q = readinti() C = readinttl(q) print(' '.join(map(str, dance(n, q, C)))) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main() ```
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()) num = sorted([int(x) for x in input().split()]) min_diff = 10 ** 6 for i in range(2 * n - 1): for j in range(i + 1, 2 * n): kaya_num = [] for k in range(2 * n): if i != k and j != k: kaya_num.append(num[k]) current_diff = 0 for l in range(0,2*n-3,2): current_diff += kaya_num[l + 1] - kaya_num[l] min_diff = min(current_diff, min_diff) print(min_diff) ```
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 w = list(input()) x = 0 n = 0 m = 0 a = 0 y = 0 z = 0 h = "" v = list("") v.clear() for l in w: x = x + 1 if l != " ": h = h + l else: v.append(h) h = "" if x == len(w): v.append(h) x = 0 for o in v: x = x + 1 if x == 1: n = o if x == 2: m = o if x == 3: a = o if int(n)%int(a) == 0: y = int(n)/int(a) else: y = (int(n)-(int(n)%int(a)))/int(a) + 1 if int(m)%int(a) == 0: z = int(m)/int(a) else: z = (int(m)-(int(m)%int(a)))/int(a) + 1 print(int(y*z)) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
```python n = int(input()) cards = list(map(int,input().split(' '))) Spoints = Dpoints = 0 i = 0 while i < n: willBeAdded = max(cards[0],cards[-1]) if i%2 == 0: Spoints = Spoints + willBeAdded else : Dpoints = Dpoints + willBeAdded cards.remove(max(cards[0],cards[-1])) i +=1 print(Spoints,Dpoints) ```
MatrixStudio/Codeforces-Python-Submissions
Some company is going to hold a fair in Byteland. There are $n$ towns in Byteland and $m$ two-way roads between towns. Of course, you can reach any town from any other town using roads. There are $k$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $s$ different types of goods. It costs $d(u,v)$ coins to bring goods from town $u$ to town $v$ where $d(u,v)$ is the length of the shortest path from $u$ to $v$. Length of a path is the number of roads in this path. The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of $n$ towns.
```python from sys import stdin,stdout,setrecursionlimit from collections import defaultdict,deque setrecursionlimit(200001) def bfs(v): se=set() cg=[] se.add(l[v-1]) d=deque() global graph, vis,dis,s,res dis[v]=0 vis[v]=1 d.append(v) while(len(d)>0): x=d.popleft() vis[x]=1 for i in graph[x]: if vis[i]==0 : vis[i]=1 dis[i]=1+dis[x] d.append(i) temp=len(se) se.add(l[i-1]) if len(se)==temp+1: cg.append(dis[i]) cg.sort() for i in range(s-1): res+=cg[i] return cg n,m,k,s=map(int,stdin.readline().split()) l=list(map(int,stdin.readline().split())) graph=defaultdict(list) vis=[0]*(100001) dis=[0]*(100001) res=0 for j in range(m): a,b=map(int,stdin.readline().split()) graph[a].append(b) graph[b].append(a) ans=[] for i in range(1,n+1): vis=[0]*(100001) dis=[0]*(100001) res=0 bfs(i) ans.append(res) print(*ans) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of *w* milliliters and 2*n* tea cups, each cup is for one of Pasha's friends. The *i*-th cup can hold at most *a**i* milliliters of water. It turned out that among Pasha's friends there are exactly *n* boys and exactly *n* girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: - Pasha can boil the teapot exactly once by pouring there at most *w* milliliters of water; - Pasha pours the same amount of water to each girl; - Pasha pours the same amount of water to each boy; - if each girl gets *x* milliliters of water, then each boy gets 2*x* milliliters of water. In the other words, each boy should get two times more water than each girl does. Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.
```python n,w = map(int,input().split()) a = list(map(int,input().split())) maxx = 0 a.sort(reverse = True) if a[0] / 2 > a[2*n-1]: maxx = (a[2*n-1]*3)*n else: maxx = (a[0]*1.5)*n print(min(maxx,w)) ```
MatrixStudio/Codeforces-Python-Submissions
The Easter Rabbit laid *n* eggs in a circle and is about to paint them. Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied: - Each of the seven colors should be used to paint at least one egg. - Any four eggs lying sequentially should be painted different colors. Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.
```python n=int(input()) colorlist=["R","O","Y","G"] y=0 x=n%7 while y<n-3: z=y%4 print(colorlist[z],end="") y+=1 print("BIV") ```
MatrixStudio/Codeforces-Python-Submissions
In Berland each high school student is characterized by academic performance — integer value between 1 and 5. In high school 0xFF there are two groups of pupils: the group *A* and the group *B*. Each group consists of exactly *n* students. An academic performance of each student is known — integer value between 1 and 5. The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal. To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class *A* and one student of class *B*. After that, they both change their groups. Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.
```python n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) s=0 c=0 for i in range(1,6): x=a.count(i) y=b.count(i) if abs(x-y)%2!=0 : c=1 else : s=s+abs(x-y)//2 if c==1 : print(-1) else : print(s) ```
MatrixStudio/Codeforces-Python-Submissions
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income *A* of his kingdom during 0-th year is known, as well as the total income *B* during *n*-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient *X* — the coefficient of income growth during one year. This coefficient should satisfy the equation: Surely, the king is not going to do this job by himself, and demands you to find such number *X*. It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient *X* must be integers. The number *X* may be zero or negative.
```python n,m,k = map(int,input().split()) for i in range(-1100,1100): if n*(i**k)==m: print(i) exit() print("No solution") ```
MatrixStudio/Codeforces-Python-Submissions
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top. Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it. Write a program that models the behavior of Ankh-Morpork residents.
```python num_of_snacks = int(input()) snacks_size = [map(int, input().split(" "))] # num_of_snacks = 5 # snacks_size = [4, 5, 1, 2, 3] last_snack = num_of_snacks sorted_list_leng = 0 for i_day in range(num_of_snacks): if snacks_size[i_day] != last_snack: print() else: base_snacks = list( range(snacks_size[sorted_list_leng], snacks_size[i_day]+1)) sorted_list = sorted(base_snacks, reverse=True) sorted_list_leng = len(sorted_list) last_snack = sorted_list[-1] - 1 print(*sorted_list) ```
MatrixStudio/Codeforces-Python-Submissions
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
```python int_inp = lambda: int(input()) #integer input strng = lambda: input().strip() #string input strl = lambda: list(input().strip())#list of strings as input mul = lambda: map(int,input().strip().split())#multiple integers as inpnut mulf = lambda: map(float,input().strip().split())#multiple floats as ipnut seq = lambda: list(map(int,input().strip().split()))#list of integers import math from collections import Counter,defaultdict a= 0 b= 0 for _ in range(int_inp()): k,l =mul() a = a+k%2 b = b+l%2 if a&1 and b&1: print(1) elif a%2==0 and b%2==0: print(0) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
You're given a list of *n* strings *a*1,<=*a*2,<=...,<=*a**n*. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation.
```python n=int(input()) arr=[] for i in range(n): arr.append(input()) for i in range(0,n): for j in range(i+1,n): if(arr[i]+arr[j]>arr[j]+arr[i]): s=arr[i] arr[i]=arr[j] arr[j]=s sol= "" for i in range( n): sol=sol+ arr[i] print(sol) ```
MatrixStudio/Codeforces-Python-Submissions
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*. As Petya is older, he wants to take the chores with complexity larger than some value *x* (*h**i*<=&gt;<=*x*) to leave to Vasya the chores with complexity less than or equal to *x* (*h**i*<=≤<=*x*). The brothers have already decided that Petya will do exactly *a* chores and Vasya will do exactly *b* chores (*a*<=+<=*b*<==<=*n*). In how many ways can they choose an integer *x* so that Petya got exactly *a* chores and Vasya got exactly *b* chores?
```python n,a,b = map(int,input().split()) x = list(map(int,input().split())) aa = sorted(x) print(aa[b] - aa[b-1]) ```
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 c = d = 0 flag = 0 for n in range(int(input())): a, b = map(int, input().split()) if a + b == c and c+d == a: flag = 1 c , d = a, b if flag == 1: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo adores strings. But most of all he adores strings of length *n*. One day he wanted to find a string that meets the following conditions: 1. The string consists of *n* lowercase English letters (that is, the string's length equals *n*), exactly *k* of these letters are distinct. 1. No two neighbouring letters of a string coincide; that is, if we represent a string as *s*<==<=*s*1*s*2... *s**n*, then the following inequality holds, *s**i*<=≠<=*s**i*<=+<=1(1<=≤<=*i*<=&lt;<=*n*). 1. Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist. String *x*<==<=*x*1*x*2... *x**p* is lexicographically less than string *y*<==<=*y*1*y*2... *y**q*, if either *p*<=&lt;<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or there is such number *r* (*r*<=&lt;<=*p*,<=*r*<=&lt;<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=&lt;<=*y**r*<=+<=1. The characters of the strings are compared by their ASCII codes.
```python n,k=map(int,input().split()) from sys import exit if k==1:print('a'*n);exit() if k>n:print(-1);exit() alfa='cdefghijklmnopqrstuvwxyz' res='ab'*((n-k+2)//2) if (n-k+2)%2==1:res+='a' res+=alfa[:k-2] print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down. Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0. As there is no internet in the countryside, Vitya has been watching the moon for *n* consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
```python n = int(input()) a=list(map(int, input().split())) if a[n-1] == 0 : print("UP") elif a[n-1] == 15 : print("DOWN") elif n == 1 : print("-1") elif a[n-2] > a[n-1] : print("DOWN") else : print("UP") ```
MatrixStudio/Codeforces-Python-Submissions
The last stage of Football World Cup is played using the play-off system. There are *n* teams left in this stage, they are enumerated from 1 to *n*. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over. Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids *a* and *b* can meet.
```python from math import * n,a,b=(int(i) for i in input().split()) z=log(abs(b-a), 2)+1 print("Final" if 2**z==n else z) ```
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 n,m=map(int, input().split()) if(n%2==0 and (n/2)%m==0): print(int(n/2)) else: if((int(n/2)+1)%m==0): print(int(n/2)+1) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has an array *a* consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position). Inserting an element in the same position he was erased from is also considered moving. Can Vasya divide the array after choosing the right element to move and its new position?
```python n=int(input()) a=list(map(int,input().split())) s=sum(a) if s%2==0: s=s//2 a.sort() dp=[[0]*(s+1) for _ in range(len(a))] dp[0][a[0]]=1 tg=False for i in range(1,len(a)): for j in range(1,s): if dp[i-1][j]==1: dp[i][j]=1 if j+a[i]<=s: dp[i][j+a[i]]=1 if dp[i][s]==1: tg=True break if tg: break if tg: print('YES') else: print('NO') 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 d1, d2, d3 = map(int, input().split()) print(min(d1 + d2 + d3, 2*d1 + 2*d2)) ```
MatrixStudio/Codeforces-Python-Submissions
Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Noldbach problem states that at least *k* prime numbers from 2 to *n* inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1. Two prime numbers are called neighboring if there are no other prime numbers between them. You are to help Nick, and find out if he is right or wrong.
```python import math def isPrime(n): if n == 1: return False if n == 2: return True if n%2 == 0: return False for i in range(3, math.ceil(math.sqrt(n))+1, 2): if n%i == 0: return False return True n, k = map(int, input().split()) total = 0 primes = [2, 3, 5] for i in range(7, n+1, 2): if isPrime(i): if i+primes[-1] <= n: total += 1 else: break primes.append(i) if total >= k: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day Ms Swan bought an orange in a shop. The orange consisted of *n*·*k* segments, numbered with integers from 1 to *n*·*k*. There were *k* children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the *i*-th (1<=≤<=*i*<=≤<=*k*) child wrote the number *a**i* (1<=≤<=*a**i*<=≤<=*n*·*k*). All numbers *a**i* accidentally turned out to be different. Now the children wonder, how to divide the orange so as to meet these conditions: - each child gets exactly *n* orange segments; - the *i*-th child gets the segment with number *a**i* for sure; - no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.
```python k , n = map(int , input().split()) t = k*n disaier = list(map(int , input().split())) if n == 1 : print(*range(1 , t + 1)) else: segment = [False] * (k*n) for i in disaier : segment[i-1] = True print(segment) for i in range(k) : counter = 0 number = 0 while counter < n-1 : if segment[number] == False : print(number + 1 ,end=' ') segment[number] = True counter +=1 number += 1 print(disaier[i] ,end=' ') print() ```
MatrixStudio/Codeforces-Python-Submissions
Igor found out discounts in a shop and decided to buy *n* items. Discounts at the store will last for a week and Igor knows about each item that its price now is *a**i*, and after a week of discounts its price will be *b**i*. Not all of sellers are honest, so now some products could be more expensive than after a week of discounts. Igor decided that buy at least *k* of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all *n* items.
```python a = [int(k) for k in input().split()] b = [int(k) for k in input().split()] c = [int(k) for k in input().split()] d = [b[k] - c[k] for k in range(a[0])] d.sort() e = 0 while d[e] < 0 and e < a[0]: e += 1 if e > a[1]: print(sum(d[0:e])+sum(c)) else: print(sum(d[0:a[1]])+sum(c)) ```
MatrixStudio/Codeforces-Python-Submissions
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
```python import math if __name__ == '__main__': a, b, c = [int(i) for i in input().split()] print(int(4 * (math.sqrt(a * b / c) + math.sqrt(a * c / b) + math.sqrt(b * c / a)))) ```
MatrixStudio/Codeforces-Python-Submissions
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies. All elements are enumerated with integers. The ChemForces company has discovered $n$ distinct chemical elements with indices $a_1, a_2, \ldots, a_n$, and will get an income of $x_i$ Berland rubles if the $i$-th element from this list is in the set of this company. The TopChemist company discovered $m$ distinct chemical elements with indices $b_1, b_2, \ldots, b_m$, and it will get an income of $y_j$ Berland rubles for including the $j$-th element from this list to its set. In other words, the first company can present any subset of elements from $\{a_1, a_2, \ldots, a_n\}$ (possibly empty subset), the second company can present any subset of elements from $\{b_1, b_2, \ldots, b_m\}$ (possibly empty subset). There shouldn't be equal elements in the subsets. Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.
```python n = int(input()) a = [] x = [] goods = [] for i in range(n): s = input().split() goods.append(int(s[0])) a.append(int(s[0])) x.append(int(s[1])) m = int(input()) b = [] y = [] for i in range(m): s = input().split() if int(s[0]) not in goods: goods.append(int(s[0])) b.append(int(s[0])) y.append(int(s[1])) max_sum = 0 len_g = len(goods) for i in range(len_g): if goods[i] in a and goods[i] not in b: max_sum += x[a.index(goods[i])] elif goods[i] in b and goods[i] not in a: max_sum += y[b.index(goods[i])] else: max_sum += max(y[b.index(goods[i])], x[a.index(goods[i])]) print(max_sum) ```
MatrixStudio/Codeforces-Python-Submissions
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored *A*·*B*·*C* hay blocks and stored them in a barn as a rectangular parallelepiped *A* layers high. Each layer had *B* rows and each row had *C* blocks. At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (*A*<=-<=1)<=×<=(*B*<=-<=2)<=×<=(*C*<=-<=2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1<=×<=1<=×<=1 blocks and scattered them around the barn. After the theft Sam counted *n* hay blocks in the barn but he forgot numbers *A*, *B* и *C*. Given number *n*, find the minimally possible and maximally possible number of stolen hay blocks.
```python print("_RANDOM_GUESS_1689595076.160925")# 1689595076.1609445 ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
```python n=int(input()) coor=[] for i in range(n): #a,b=map(int,input().split()) a,b=10**9,10**9 coor.append([a,b]) def newlist(a): d={} s=len(a) for i in range(s): for j in range(s): if i<j: if (a[i][0]+a[j][0],a[i][1]+a[j][1]) in d: d[a[i][0]+a[j][0],a[i][1]+a[j][1]]+=1 else: d[a[i][0]+a[j][0],a[i][1]+a[j][1]]=0 return d d=newlist(coor) sum2=0 for l in d: sum2+=d[l]*(d[l]-1)/2 print(int(sum2)) ```
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 n, a, b = map(int, input().split()) t = list(map(int, input().split())) oit, res = 0, 0 for i in range(n): if t[i] == 1: if a > 0: a -= 1 continue if oit > 0: oit -= 1 b -= 1 continue if b > 0: oit += 1 continue res += 1 else: if b - oit == 0: res += 2 else: b -= 1 print(res) ```
MatrixStudio/Codeforces-Python-Submissions
According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.
```python n,m=list(map(int,input().split())) l=[] count=0 for i in range(n): a=input() l.append(a) for i in range(1,len(l)): for j in range(1,len(l[i])): if l[i][j]!=l[i][j-1]: count=count+1 if l[i]==l[i-1]: count=count+1 if count>0: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, *n* coins of arbitrary values *a*1,<=*a*2,<=...,<=*a**n*. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally. As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.
```python #王奕欢 2300012285 a=int(input()) l=[int(x) for x in input().split()] d=sorted(l) d.reverse() b=0 c=0 for i in range(a): c+=d[i] e = c-b for i in range(a): if b<=e: b+=d[i] e = c - b if b<=e: continue else: f = i + 1 print(f) break ```
MatrixStudio/Codeforces-Python-Submissions
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club. For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX". Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
```python s=input() i=0 while(i<len(s)): st=s[i:i+3] if st=="WUB": s=s.replace("WUB"," ") i+=3 else: i+=1 print(s.strip()) ```
MatrixStudio/Codeforces-Python-Submissions
— This is not playing but duty as allies of justice, Nii-chan! — Not allies but justice itself, Onii-chan! With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands! There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of *a*, *b* and *c* distinct islands respectively. Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster. The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998<=244<=353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.
```python ##a = list(map(int, input().split())) ##print(' '.join(map(str, res))) [a, b, c] = list(map(int, input().split())) N = 5005; MOD = 998244353 bin = [[0 for j in range(N)] for i in range(N)] fac = [0 for i in range(N)] fac[0] = 1 for i in range(1, N): fac[i] = (fac[i-1]*i)%MOD for i in range(0, N): bin[i][0] = 1 for i in range(1, N): for j in range(1, N): bin[i][j] = (bin[i-1][j]+bin[i-1][j-1])%MOD def calc(p, q): res = 0 for i in range(min(p, q)+1): res += ((bin[p][i]*bin[q][i])%MOD*fac[i])%MOD res %= MOD return res res = ((calc(a, b)*calc(a, c))%MOD*calc(b, c))%MOD print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment. For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place. Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
```python n = int(input()) l = [int(i) for i in input().split()] c = 0 for i in range(1,6): s = sum(l)+i if s%(n+1)==0: c+=1 elif s%(n+1)==1: pass elif s%(n+1)==2: c+=1 elif s%(n+1)==3: c+=1 elif s%(n+1)==4: c+=1 elif s%(n+1)==5: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the *i*-th star on the pedal axle has *a**i* (0<=&lt;<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*) teeth, and the *j*-th star on the rear wheel axle has *b**j* (0<=&lt;<=*b*1<=&lt;<=*b*2<=&lt;<=...<=&lt;<=*b**m*) teeth. Any pair (*i*,<=*j*) (1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (*i*,<=*j*) has a gear ratio, equal to the value . Since Vasya likes integers, he wants to find such gears (*i*,<=*j*), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (*i*,<=*j*) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears. In the problem, fraction denotes division in real numbers, that is, no rounding is performed.
```python an = int(input()) a = list(map(int, input().split())) bn = int(input()) b = list(map(int, input().split())) ratios = [] mx = 0 for i in a: for j in b: if j % i == 0: k = j//i ratios.append(k) if k > mx: mx= k ct = 0 for i in ratios: if mx == i: ct+=1 print(ct) ```
MatrixStudio/Codeforces-Python-Submissions
Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together. More detailed, there are *n* pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: 1. Value *x* and some direction are announced, and all boys move *x* positions in the corresponding direction. 1. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that *n* is even. Your task is to determine the final position of each boy.
```python n,q = map(int, input().split(" ")) setup=[i + 1 for i in range(n)] for i in range(q): move = list(map(int, input().split(" "))) if move[0] == 2: setup = [item for sublist in zip(setup[1::2], setup[::2]) for item in sublist] elif move[0] == 1: if move[1] < 0: setup = setup[move[1]:] + setup[:move[1]] else: setup = setup[-move[1]:] + setup[:-move[1]] print(setup) ```
MatrixStudio/Codeforces-Python-Submissions
High school student Vasya got a string of length *n* as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than *k* characters of the original string. What is the maximum beauty of the string he can achieve?
```python n,k=map(int,input().split()) s=input() j=0 i=0 dp=[0,0] ans=0 dp[ord(s[i])-ord('a')]+=1 for i in range(n): while j<n-1: if min(dp)<=k: j+=1 dp[ord(s[j])-ord('a')]+=1 else: break if j!=n-1 or k<min(dp): dp[ord(s[j])-ord('a')]-=1 j-=1 ans=max(ans,dp[0]+dp[1]) dp[ord(s[i])-ord('a')]-=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created. We assume that Bajtek can only heap up snow drifts at integer coordinates.
```python from sys import stdin, stdout fin = stdin.readline fout = stdout.write def solve(): n = int(fin()) c = [] for i in range(n): c.append(fin().split()) c[-1][0] = int(c[-1][0]) c[-1][1] = int(c[-1][1]) r = 0 last = None cur = None while c: change = False if cur == last: cur = c.pop() last = cur.copy() for i in range(len(c)): if cur[0] == c[i][0] or cur[1] == c[i][1]: cur = c[i] del c[i] change = True break if not change: r += 1 r -= 1 if r == -1: r = 0 fout(str(r)+'\n') solve() ```