source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
```python n, m, a = map(int, input().split(" ")) ma = m//a if m % a > 0: ma += 1 na = n//a if n % a > 0: na += 1 print(na*ma) ```
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven. Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
```python n, t, k, d = map(int, input().split()) time_1_oven = n * (t / k) time_2_oven = 0 n_cakes_1 = 0 n_cakes_2 = 0 mins = 0 mins_2_oven = 0 oven_2_on = False while n_cakes_1 < n: mins += 1 if mins % t == 0 and mins != 0: n_cakes_1 += k mins_1_oven = mins mins = 0 while n_cakes_2 < n: # First oven mins += 1 if mins % t == 0 and mins != 0: n_cakes_2 += k # Second oven if d <= mins: oven_2_on = True if oven_2_on: if mins_2_oven % t == 0 and mins_2_oven != 0: n_cakes_2 += k mins_2_oven += 1 mins_2_oven = mins if mins_1_oven <= mins_2_oven: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
```python from sys import stdin input = lambda: stdin.readline().strip() d = dict() n = int(input()) for _ in range(n): s = input() if s not in d: d[s] = 1 else: d[s] += 1 print(max(d.values())) ```
MatrixStudio/Codeforces-Python-Submissions
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of *n* missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos *i* and *j* is patrolled by *c**i*,<=*j* war droids. The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any *k*-element set of silos *S* there is exactly one silo that is directly connected by a passage with each silo from *S* (we'll call this silo adjacent with *S*). Having considered that, the insurgents decided to act as follows: 1. they choose a *k*-element set of silos *S*; 1. a group of scouts lands from the air into each silo from *S*; 1. each group moves along the corresponding passage to the silo, adjacent with *S* (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); 1. in the silo, adjacent with *S*, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set *S*. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set *S*. Solve this problem to help the insurgents protect the ideals of the Republic!
```python f = [1 for i in range(2001)]; for i in range(1, 2001): f[i] = f[i-1] * i; n, m = map(int, raw_input().split()); a = [[-1 for i in range(n)] for j in range(n)]; cal = [0 for i in range(n)]; for i in range(0, n-1): buf = map(int, raw_input().split()); for j in range(i+1, n): a[i][j] = a[j][i] = buf[j-i-1]; total = 0; for i in range(n): d = sum = 0; for j in range(n): if a[i][j] != -1: d = d + 1; sum = sum + a[i][j]; if d >= m: if cal[d] == 0: cal[d] = f[d-1] / f[d-m]; total = total + sum * cal[d]; print total * m * f[n-m] / f[n]; ```
MatrixStudio/Codeforces-Python-Submissions
All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in). Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city. For each city calculate two values ​​*min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city
```python cities = int(input()) coordinate_of_city = list(map(int, input().split(' '))) for i in range(cities): coordinate_of_city_copy = coordinate_of_city[::] coordinate_of_city_copy.remove(coordinate_of_city_copy[i]) distances = [] for coordinate in coordinate_of_city_copy: distances.append(abs(coordinate_of_city[i] - coordinate)) print(min(distances), max(distances)) ```
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 x,y,z=map(int, input().split()) if x%z==0: a=x//z else: a=x//z + 1 if y%z==0: b=y//z else: b=y//z + 1 print(a*b) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist. Divisor of *n* is any such natural number, that *n* can be divided by it without remainder.
```python import math entrada = input() n = int(entrada.split()[0]) k = int(entrada.split()[1]) arr_v = [] i = 1 while (i * i <= n): if (n % i != 0): i += 1 continue arr_v.append(i) if (i * i != n): arr_v.append(n // i) i += 1 if (k > len(arr_v)): print(-1) else: arr_v.sort() print(arr_v[k - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253": Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
```python left = 0 right = 1 up = 2 down = 3 buttons = [] #0 buttons.append({left:False, right:False, up:True, down:False }) #1 buttons.append({left:False, right:True, up:False, down:True }) #2 buttons.append({left:True, right:True, up:False, down:True }) #3 buttons.append({left:True, right:False, up:False, down:True }) #4 buttons.append({left:False, right:True, up:True, down:True }) #5 buttons.append({left:True, right:True, up:True, down:True }) #6 buttons.append({left:True, right:False, up:True, down:True }) #7 buttons.append({left:False, right:True, up:True, down:False }) #8 buttons.append({left:True, right:True, up:True, down:True }) #9 buttons.append({left:True, right:False, up:True, down:False }) n = eval( input( ) ) stroke = input( ) can = [True,True,True,True] for button in stroke: button = int(button) if buttons[button][left] == False: can[left] = False if buttons[button][right] == False: can[right] = False if buttons[button][up] == False: can[up] = False if buttons[button][down] == False: can[down] = False canMove = False for i in range(4): if can[i] == True: canMove = True if canMove == True: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different. There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number. You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
```python from itertools import combinations n = int(input()) home_colors = [] guest_colors = [] for _ in range(n): hi, ai = map(int, input().split()) home_colors.append(hi) guest_colors.append(ai) count = 0 for host, guest in combinations(range(n), 2): if home_colors[host] == guest_colors[guest]: count += 1 if home_colors[guest] == guest_colors[host]: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result. Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
```python a=int(input()) b=input() c=b.count("0") d=b.count("1") print(a-min(c,d)*2) ```
MatrixStudio/Codeforces-Python-Submissions
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions." Could you pass the interview in the machine vision company in IT City?
```python k = int(input()) r = pow(5, k, 100) print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.
```python from collections import * from functools import * n = int(input()) arr = [int(x) for x in input().split()] c = Counter(arr) mx = max(arr) @lru_cache(None) def helper(ind): if ind > mx: return 0 ans = helper(ind+2) + ind*c[ind] ans = max(ans, helper(ind+1)) return ans print(helper(1)) ```
MatrixStudio/Codeforces-Python-Submissions
Little Elephant loves magic squares very much. A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15. The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 105. Help the Little Elephant, restore the original magic square, given the Elephant's notes.
```python mat=[] for i in range(3): mat.append([int(i) for i in input().split()]) a=mat[0][1]+mat[0][2] b=mat[1][0]+mat[1][2] c=mat[2][0]+mat[2][1] mat[0][0]=10**5-a mat[1][1]=10**5-b mat[2][2]=10**5-c for i in range(3): print(*mat[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Anton likes to play chess, and so does his friend Danik. Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
```python n=int(input()) ch=input() r=0 for i in ch: if i=='A': r=r+1 else: r=r-1 if r>0: print('Anton') elif r==0: print('Friendship') else: print('Danik') ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
```python n,m = map(int, input().split()) t = 0 while n>0: t = t + 1 if t%m==0: n = n + 1 n = n - 1 print(t) ```
MatrixStudio/Codeforces-Python-Submissions
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door. The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters. Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
```python s1 = input() s2 = input() s3 = input() s = s1+s2 s1 = ''.join(sorted(s)) s2 = ''.join(sorted(s3)) if s1 == s2: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes. Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
```python n = int(input()) wordList = [] for ctr in range(n): word = input() wordList.append(word) for w in wordList: if len(w) <= 10: print(w) else: print(w[0]+str(len(w)-2)+w[-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex *u* is called a child of vertex *v* and vertex *v* is called a parent of vertex *u* if there exists a directed edge from *v* to *u*. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz).
```python import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return (int(input())) def inlt(): return (list(map(int, input().split()))) def insr(): s = input() return (list(s[:len(s) - 1])) def invr(): return (map(int, input().split())) def explore(adj,i): count=[] q=[i] while(q!=[]): i=min(q) q.remove(i) if visited[i]!=1: visited[i]=1 count+=[i+1] q+=adj[i] return count x=0 n=inp() adj=[[] for i in range(n)] for i in range(n-1): u=inp() if u !=-1 and u-1!= i+1: adj[u-1].append(i+1) for i in range(n): if adj[i]==[]: continue else: a=0 for j in adj[i]: if adj[j]==[]: a+=1 if a!=3: x=1 break if x==1: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
You are given a following process. There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.
```python leng, m = map(int, input().split()) blocks = list(map(int, input().split())) diction = dict.fromkeys(range(1, (leng + 1)), 0) for temp in blocks: t = diction[temp] t += 1 diction[temp] = t answer = min(diction.values()) print(answer) ```
MatrixStudio/Codeforces-Python-Submissions
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left. Your problem is to print the minimum possible length of the sequence of moves after the replacements.
```python n=int(input()) s=input() a=[] for i in range(n): a.append(s[i]) for i in range(n-1): if a[i]=="U" and a[i+1]=="R": a[i]="D" a[i+1]="D" if a[i]=="R" and a[i+1]=="U": a[i]="D" a[i+1]="D" print(n-(a.count("D"))//2) ```
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()) sum1=sum2=sum3=0 for i in range(n) : arr=[int(j) for j in input().split()] sum1=sum1+arr[0] sum2=sum2+arr[1] sum3=sum3+arr[2] if sum1==sum2==sum3==0 : print("YES") else : print("NO") ```
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 m,n,a = map(int, input().split()) total = m*n area = a*a if total%area==0: print(int(total/area)+1) else: print((total//area)+1+1) ```
MatrixStudio/Codeforces-Python-Submissions
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, the chessboard is a square-checkered board with the squares arranged in a 8<=×<=8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke. Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements. It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
```python a=[] c=0 s=0 for i in range(8): b=input() a=a+[b] c=c+a.count('BBBBBBBB') if c!=8: for i in range(8): for j in range(8): if a[i][j]=='B': for m in range(8): if a[m][j]=='B': s=s+1 if s==8: c=c+1 s=0 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw *n* people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
```python # -*- coding: utf-8 -*- """ Created on Wed Mar 18 21:37:04 2020 @author: DELL """ str=["ABSINTH", "BEER", "BRANDY","CHAMPAGNE","GIN","RUM","SAKE","TEQUILA","VODKA","WHISKEY","WINE"] n=int(input()) l=[] for i in range(n): h=input() l+=[h] c=0 for i in l: if i.isalpha(): if not i in str: c+=1 elif i.isdigit(): i=int(i) if i<18: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers. Let's remember how Fibonacci numbers can be calculated. *F*0<==<=0, *F*1<==<=1, and all the next numbers are *F**i*<==<=*F**i*<=-<=2<=+<=*F**i*<=-<=1. So, Fibonacci numbers make a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, ... If you haven't run away from the PC in fear, you have to help the virus. Your task is to divide given Fibonacci number *n* by three not necessary different Fibonacci numbers or say that it is impossible.
```python n = int(input()) print(str(0) + ' ' + str(0) + ' ' + str(n)) ```
MatrixStudio/Codeforces-Python-Submissions
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function *f*(*x*,<=*l*,<=*r*) as a bitwise OR of integers *x**l*,<=*x**l*<=+<=1,<=...,<=*x**r*, where *x**i* is the *i*-th element of the array *x*. You are given two arrays *a* and *b* of length *n*. You need to determine the maximum value of sum *f*(*a*,<=*l*,<=*r*)<=+<=*f*(*b*,<=*l*,<=*r*) among all possible 1<=≤<=*l*<=≤<=*r*<=≤<=*n*.
```python import math n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) x,y=max(a),max(b) f,q= math.log(x,2),math.log(y,2) f=int(f) ans1 = (2**f)+((2**f)-1) q=int(q) ans2 = (2**q)+((2**q)-1) print(ans1+ans2) ```
MatrixStudio/Codeforces-Python-Submissions
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*: - *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE Each child happens to be good at exactly one of these three subjects. The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team. What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
```python n=int(input()) a=list(map(int,input().split())) a1=[] a2=[] a3=[] l1,l2,l3 = 0,0,0 for x in range(1,n+1): if a[x-1]==1: a1.append(x) l1+=1 elif a[x-1]==2: a2.append(x) l2+=1 else: a3.append(x) l3+=1 k=min(l1,l2,l3) print(k) for x in range(k): print(a1[x],a2[x],a3[x]) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya likes points a lot. Recently his mom has presented him *n* points lying on the line *OX*. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed *d*. Note that the order of the points inside the group of three chosen points doesn't matter.
```python num, choose = map(int, input().split()) lista = list(map(int, input().split())) ans = 0 j = 0 for i in range(0,num): while(lista[i] - lista[j] > choose): j+=1 ans += ((i - j) * (i - j - 1))/2 print(int(ans)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
```python m, n = [int(i) for i in input().split()] count = m m//=n s = m count +=m while True: m//=n if m==0: break if m%n==0: count+=1 count+=m print(count) ```
MatrixStudio/Codeforces-Python-Submissions
The input contains a single integer *a* (1<=≤<=*a*<=≤<=40). Output a single string.
```python president = int(input()) if president == 1: print("Washington") elif president == 2: print("Adams") elif president == 3: print("Jefferson") elif president == 4: print("Madison") elif president == 5: print("Monroe") elif president == 6: print("Adams") elif president == 7: print("Jackson") elif president == 8: print("Van Buren") elif president == 9: print("Harrison") elif president == 10: print("Tyler") elif president == 11: print("Polk") elif president == 12: print("Taylor") elif president == 13: print("Fillmore") elif president == 14: print("Pierce") elif president == 15: print("Buchanan") elif president == 16: print("Lincoln") elif president == 17: print("Johnson") elif president == 18: print("Grant") elif president == 19: print("Hayes") elif president == 20: print("Garfield") elif president == 21: print("Arthur") elif president == 22: print("Cleveland") elif president == 23: print("Harrison") elif president == 24: print("Cleveland") elif president == 25: print("McKinley") elif president == 26: print("Roosevelt") elif president == 27: print("Taft") elif president == 28: print("Wilson") elif president == 29: print("Harding") elif president == 30: print("Coolidge") elif president == 31: print("Hover") elif president == 32: print("Roosevelt") ```
MatrixStudio/Codeforces-Python-Submissions
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
```python def main(): [na, nb] = [int(_) for _ in input().split()] [k, m] = [int(_) for _ in input().split()] a = [int(_) for _ in input().split()] b = [int(_) for _ in input().split()] max_a = a[k - 1] min_b = b[nb - m] print('YES' if max_a < min_b else 'NO') if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
George decided to prepare a Codesecrof round, so he has prepared *m* problems for the round. Let's number the problems with integers 1 through *m*. George estimates the *i*-th problem's complexity by integer *b**i*. To make the round good, he needs to put at least *n* problems there. Besides, he needs to have at least one problem with complexity exactly *a*1, at least one with complexity exactly *a*2, ..., and at least one with complexity exactly *a**n*. Of course, the round can also have problems with other complexities. George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity *c* to any positive integer complexity *d* (*c*<=≥<=*d*), by changing limits on the input data. However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the *m* he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
```python #Find distinct numbers in array 1 #Find distinct numbers in array 2 #Find miss and count n = list(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) a_t = [i for i in set(a)] b_t = [i for i in set(b)] count = 0 for a_i in a_t: if a_i not in b_t: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array *a*1,<=*a*2,<=...,<=*a**n* consisting of *n* integers, and an integer *k*. You have to split the array into exactly *k* non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the *k* obtained minimums. What is the maximum possible integer you can get? Definitions of subsegment and array splitting are given in notes.
```python n, k = [int(i) for i in input().split()] nums = [int(i) for i in input().split()] if k >= 3: result = max(nums) elif k == 1: result = min(nums) else: mins = [0 for i in range(n)] a = 0 b = n - 1 minA = max(nums) minB = max(nums) for i in range((n // 2) + 1): # arr1 = nums[0:i] # arr2 = nums[i:] # min1 = min(arr1) # min2 = min(arr2) if nums[a] < minA: minA = nums[a] if nums[b] < minB: minB = nums[b] if a == b: mins[a] = max(nums[a], nums[b]) else: mins[a] = minA mins[b] = minB # bigger = max(min1, min2) # large = max(large, bigger) # print(mins) result = max(mins) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium. The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
```python def putWeight(string,weight): leftPlate = "" rightPlate = "" plate = "L" for i in string: if str(i) == "|": plate = "R" continue if plate == "L": leftPlate+=str(i) continue if plate == "R": rightPlate+=str(i) continue while len(weight) != 0: if len(leftPlate) > len(rightPlate): rightPlate+=weight.pop(0) continue if len(rightPlate) > len(leftPlate): leftPlate+=weight.pop(0) continue if len(rightPlate) == len(leftPlate): leftPlate+=weight.pop(0) continue if len(leftPlate) == len(rightPlate): return str(leftPlate)+"|"+str(rightPlate) else: return "Impossible" string = str(input()) weight = list(input()) #nums = input().split() #items = input().split() print(putWeight(str(string),list(weight))) ```
MatrixStudio/Codeforces-Python-Submissions
The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: - At least one participant should get a diploma. - None of those with score equal to zero should get awarded. - When someone is awarded, all participants with score not less than his score should also be awarded. Determine the number of ways to choose a subset of participants that will receive the diplomas.
```python def isPalyndrome(word): for i in range(len(word) // 2): if word[i] != word[len(word) - 1 - i]: return False return True word = input() while(len(word) > 0): if not isPalyndrome(word): print(len(word)) break else: word = word[:-1] if len(word) == 0: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres). Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.
```python class Solution(object): def __init__(self): n, v = map(int, input().split()) l1 = [] l2 = [] for i in range(n): x, y = map(int, input().split()) if x == 1: l1.append((y, i + 1)) else: l2.append((y, i + 1)) l1.sort(reverse=True) l2.sort(reverse=True) # print(f'l1: {l1} l2: {l2}') s1 = [0] s2 = [0] for i in range(min(v, len(l1))): s1.append(s1[-1] + l1[i][0]) # print(s1) for i in range(min(v // 2, len(l2))): s2.append(s2[-1] + l2[i][0]) # print(s2) ans = idx1 = idx2 = 0 for i in range(len(s1)): j = min(len(s2) - 1, (v - i) // 2) x = s1[i] + s2[j] if ans < x: ans = x idx1 = i idx2 = j # print(f'ans: {ans} idx1: {idx1} idx2: {idx2}') print(f'{ans}') a = [l1[i][1] for i in range(idx1)] + [l2[i][1] for i in range(idx2)] for x in a: print(f'{x}', end=' ') pass def main(): Solution() pass if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
A median in an array with the length of *n* is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2,<=6,<=1,<=2,<=3) is the number 2, and a median of array (0,<=96,<=17,<=23) — the number 17. We define an expression as the integer part of dividing number *a* by number *b*. One day Vasya showed Petya an array consisting of *n* integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals *x*. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to *x*. Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
```python #import math number_of_testcases = 1 #int(input()) for _ in range(number_of_testcases): initial_array_len, required_median_val = map(int,input().split()) given_array = list(map(int,input().split())) given_array.sort() min_nums_needed = 0 while given_array[((initial_array_len + 1)//2) - 1] != required_median_val: given_array.append(required_median_val) given_array.sort() min_nums_needed += 1 initial_array_len += 1 print(min_nums_needed) ```
MatrixStudio/Codeforces-Python-Submissions
Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help. Filya is given an array of non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. First, he pick an integer *x* and then he adds *x* to some elements of the array (no more than once), subtract *x* from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal. Now he wonders if it's possible to pick such integer *x* and change some elements of the array using this *x* in order to make all elements equal.
```python input() a = list(map(int, input().split())) a = sorted(set(a)) if len(a) >= 4: print("NO") elif len(a) <= 2: print("YES") else: if a[1] - a[0] == a[2] - a[1]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions. It is guaranteed that the result will be positive integer number.
```python inpt=input() s=inpt.split() n=int(s[0]) k=int(s[1]) for i in range(k): if n%10==0:\ n/=10 else: n-=1 print(int(n)) ```
MatrixStudio/Codeforces-Python-Submissions
Each New Year Timofey and his friends cut down a tree of *n* vertices and bring it home. After that they paint all the *n* its vertices, so that the *i*-th vertex gets color *c**i*. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
```python n = int(input()) u = [] v = [] for i in range(n-1): a, b = map(int, input().split()) u.append(a) v.append(b) c = [0] + [int(x) for x in input().split()] e = 0 dic = {} for i in range(1, n+1): dic[i] = 0 def plus(dic, n): if n in dic: dic[n] += 1 else: dic[n] = 1 for i in range(n-1): if c[u[i]] != c[v[i]]: e += 1 dic[u[i]] += 1 dic[v[i]] += 1 for i in range(1, n+1): if dic[i] == e: print ('YES', i,sep='\n') exit(0) print ("NO") ```
MatrixStudio/Codeforces-Python-Submissions
An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure. Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
```python n=input() n=int(n) mylist=[] ans=0 if n<3: mylist.append(1) elif n==3: mylist.append(1) mylist.append(3) elif n==4: mylist.append(3) mylist.append(1) mylist.append(4) mylist.append(2) else: for i in range(1,n+1,2): mylist.append(i) for i in range(2,n+1,2): mylist.append(i) ans=len(mylist) print(ans) for p in mylist: print(p," ", end="") ```
MatrixStudio/Codeforces-Python-Submissions
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains *n* sweet candies from the good ol' bakery, each labeled from 1 to *n* corresponding to its tastiness. No two candies have the same tastiness. The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest ones — but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum! A xor-sum of a sequence of integers *a*1,<=*a*2,<=...,<=*a**m* is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found [here.](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than *k* candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.
```python n,k=map(int,input().split()) print(n if k==1 else (1<<len(bin(n))-2)-1) ```
MatrixStudio/Codeforces-Python-Submissions
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough. Right now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.
```python a,b = map(int,input().split()) x,y,z = map(int,input().split()) k = 2*x+y-a k1= y+3*z-b if k<0 : k=0 if k1<0 : k1=0 print(k+k1) ```
MatrixStudio/Codeforces-Python-Submissions
*n* children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation *a*1,<=*a*2,<=...,<=*a**n* of length *n*. It is an integer sequence such that each integer from 1 to *n* appears exactly once in it. The game consists of *m* steps. On each step the current leader with index *i* counts out *a**i* people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader. You are given numbers *l*1,<=*l*2,<=...,<=*l**m* — indices of leaders in the beginning of each step. Child with number *l*1 is the first leader in the game. Write a program which will restore a possible permutation *a*1,<=*a*2,<=...,<=*a**n*. If there are multiple solutions then print any of them. If there is no solution then print -1.
```python n, m = map(int, input().split()) s = list(map(int, input().split())) s.append(s[0]) l = list(range(1, n + 1)) def difference(n1, n2, length): if n1 == length and n2 != length: return -1 if n1<n2: return n2-n1 elif n1==n2: return n1 else: return n2+length-n1 d = {} for idx in range(len(s)-2): diff = difference(s[idx], s[idx+1], n) d[s[idx]] = diff if diff == -1: print(-1) else: try: l.remove(diff) except ValueError: print(-1) break if l: for item in range(1, n+1): try: d[item] except KeyError: d[item] = l.pop() print(" ".join([str(d[item])for item in sorted(d.keys())])) ```
MatrixStudio/Codeforces-Python-Submissions
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
```python l=list(map(int,input().split())) m=set(l) print(len(l)-len(m)) ```
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python n,a,b=map(int,input().split()) print(b+1 if a+1>b else n-a) ```
MatrixStudio/Codeforces-Python-Submissions
Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
```python n=int(input()) ll=list(map(int,input().split())) five=ll.count(5) zero=ll.count(0) if zero==0: print(-1) elif five<9: print(0) else: print("5"*((five//9)*9)+"0"*zero) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars. Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
```python # brownfox2k6 from math import gcd n = int(input()) a = [*map(int, input().split())] while True: g = gcd(*a) if g == 1: break for i in range(n): a[i] //= g for i in range(n): if a[i] > 3: exit(print("No")) print("Yes") ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
```python s1 = input() s2 = input() if s1.lower() > s2.lower(): print(1) elif s1.lower() < s2.lower(): print(-1) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
As you must know, the maximum clique problem in an arbitrary graph is *NP*-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively. Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques. Let's define a divisibility graph for a set of positive integers *A*<==<={*a*1,<=*a*2,<=...,<=*a**n*} as follows. The vertices of the given graph are numbers from set *A*, and two numbers *a**i* and *a**j* (*i*<=≠<=*j*) are connected by an edge if and only if either *a**i* is divisible by *a**j*, or *a**j* is divisible by *a**i*. You are given a set of non-negative integers *A*. Determine the size of a maximum clique in a divisibility graph for set *A*.
```python l = [int(n) for n in [*open(0)][1].split()] n = len(l) print(l) dp = [([1000_000]*2) for i in range(n)] for i in range(n): recMax = 0 e = l[i] for e2 in dp: if(e % e2[0]==0): if(e2[1]>recMax): recMax=e2[1] dp[i][0] = e dp[i][1] = recMax+1 def max2(o): return o[1] print(max(dp, key = max2)[1]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist. Divisor of *n* is any such natural number, that *n* can be divided by it without remainder.
```python import math inp=list(map(int,input().split())) n=inp[0] k=inp[1] i=1 l=[] while(i<=math.sqrt(n)): if(n%i==0): l.append(i) l.append(int(n//i)) i=i+1 if(len(l)<k): print(-1) else: l.sort() print(l[k-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of *n* last visited by the user pages and the inputted part *s* are known. Your task is to complete *s* to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix *s*.
```python s = input() res = float('inf') flag = 0 for j in range(int(input())): k = input() if((k.find(s)!=-1) and (k.find(s)==0)): l = len(k) if(l<=res): res = l s1 = k flag = 1 if((k==s) or (k.find(s)==-1 and flag == 0) ): s1=s print(s1) ```
MatrixStudio/Codeforces-Python-Submissions
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive.
```python def f(x): fl=1 if x==2 or x==3: fl=1 elif x%2==0 or x==1: fl=0 else: n=3 while 1: if x%n==0: fl=0 break elif n>int(x**.5): fl=1 break else: n+=2 return fl x=int(input()) j=0 for n in range(6,x+1): l=0 for k in range(1,n+1): if f(k)==1 and n%k==0: l+=1 if l==2: j+=1 l=0 print(j) ```
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 colors = ['R','O','Y','G','B','I','V'] n= int(input()) for i in range(n-4): # if i == n-1 and i%7 == 0: # print(colors[i%7+1],end='') # break print(colors[i%4],end='') print('BIV',end='') print(colors[i%4]) ```
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 q = input() W = ["Z","Y","X","W","V","U","T","S","R","Q","P","O","N","M","L","K","J","I","H","G","F","E","D","C","B","A"] w = ["z","y","x","w","v","u","t","s","r","q","p","o","n","m","l","k","j","i","h","g","f","e","d","c","b","a"] e = 0 for i in range(len(q) - 1): if W.count(q[i + 1]) > 0: e += 1 if e == len(q) - 1: if w.count(q[0]) > 0: print(W[w.index(q[0])], end="") else: print(w[W.index(q[0])], end="") for i in range(len(q) - 1): print(w[W.index(q[i + 1])], end="") else: print(q) ```
MatrixStudio/Codeforces-Python-Submissions
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test. You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
```python def main(): n = int(input()) d = {i: None for i in map(int, input().split())} for i in range(1, 3001): if i not in d: print(i) return if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes. The parking lot before the office consists of one line of (2*n*<=-<=2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever. Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly *n* successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.
```python n = int(input()) answer = (n - 1) * 4 * 3 * pow(4, n - 3) print(answer) ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom! Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*. Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
```python a,b=map(int, input().split()) def gcd(a, b): while b > 0: a %= b a, b = b, a return a def fact(n): for i in range(1, n): n*=i return n print(gcd(fact(a),fact(b))) # Thu Jul 06 2023 11:43:19 GMT+0300 (Moscow Standard Time) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to *n* as the pattern. The digits will form a rhombus. The largest digit *n* should be located in the centre. The digits should decrease as they approach the edges. For example, for *n*<==<=5 the handkerchief pattern should look like that: Your task is to determine the way the handkerchief will look like by the given *n*.
```python n=int(input()) l=[] l2=[] s=str(0) l.append(s) s=str(0)+str(1)+str(0) l.append(s) for i in range (2,n+1): s=s[:i]+str(i)+str(i-1)+s[i:] l.append(s) for i in range(len(l)): l2.append((l[i].replace("", " ")[1: -1])) m=n*2 for i in range (len(l2)): print((m)*" " + l2[i]) m-=2 m+=4 for i in reversed(range(len(l2)-1)): print((m)*" " + l2[i]) m+=2 ```
MatrixStudio/Codeforces-Python-Submissions
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an *n*<=×<=*m* grid, there's exactly one bear in each cell. We denote the bear standing in column number *j* of row number *i* by (*i*,<=*j*). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for *q* rounds. In each round, Mike chooses a bear (*i*,<=*j*) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears. Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row. Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
```python n , m , q = list(map(int,input().split())) mat=[None]*n sums=[None]*n for i in range(n): mat[i]=list(map(int,input().split())) cnt=0 cntmx=0 for j in range(1,m): if mat[i][j] ==1: if cnt==0: cnt=1 if mat[i][j] ==1 and mat[i][j-1] ==1: cnt+=1 elif cnt>cntmx: cntmx=cnt sums[i]=cntmx for qq in range(q): i,j =list(map(int,input().split())) mat[i-1][j-1] =1 if mat[i-1][j-1]==0 else 0 cnt=0 cntmx=0 for jj in range(1,m): if mat[i-1][jj] ==1: if cnt==0: cnt=1 if mat[i-1][jj] == 1 and mat[i-1][jj-1] ==1: cnt+=1 if cnt>cntmx: cntmx=cnt sums[i-1]=cntmx print(max(sums)) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
```python n, k , m = map(int, input().split()) a = list(map(int, input().split())) s = [] h = 0 z = 0 for i in range(n): s.append(a[i]%m) for i in range(n): if s.count(s[i]) >= k: h =s[i] break if h > 0: print('Yes') for i in range(n): if z == k: break if s[i] == h: z+=1 print(a[i], end = ' ') else: print('No') ```
MatrixStudio/Codeforces-Python-Submissions
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1. The potato pie is located in the *n*-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F. Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door. Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*. Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
```python import string n = int(input()) s = input().lower() key = [0]*26 count = 0 i=0 while i<len(s): key[string.ascii_lowercase.index(s[i])] +=1 if key[string.ascii_lowercase.index(s[i+1])]>0: key[string.ascii_lowercase.index(s[i+1])] -=1 else: count +=1 i+=2 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python num = [int(x) for x in input().split()] multi = num[0] * num[1] print(int(multi / 2)) ```
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 a,b=map(int,input().split()) if (a==b): print(a, 0) elif (a>b): print(b,(a-b)//2) else : print(a, (b-a)//2) ```
MatrixStudio/Codeforces-Python-Submissions
One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
```python n, k = map(int, input().split()) s = input() count = [0] * 26 for i in s: count[ord(i) - 97] += 1 # for i in range(26): # if count[i] > 0: # print(chr(i + 97), count[i]) print('NO' if max(count) > k else 'YES') ```
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 a = int(input()) print(int((a-1)/2)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously). Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
```python n = int(input()) s = list(map(int, input().split())) ans = 0 h = 0 l = 0 for i in range(len(s)): if i == 0: l = s[i] h = s[i] pass else: if s[i] > h: h = s[i] ans += 1 if s[i] < l: l = s[i] ans += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each other one candy more than they received in the previous turn. This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy.
```python a , b = list(map(int,input().split())) v1 = (int)(a**0.5) v2 = (-1 + (int)((1 + 4*b)**0.5))//2 if v1 > v2: print('Valera') else: print('Vladik') ```
MatrixStudio/Codeforces-Python-Submissions
You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist. Divisor of *n* is any such natural number, that *n* can be divided by it without remainder.
```python n,k = map(int,input().split()); dels = [] for i in range(1,n): if n % i == 0: dels.append(i) dels = sorted(dels) if len(dels)>=k: print(dels[k-1]) else: print(-1) ```
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() capitalCount = 0 smallCount = 0 for letter in word: if letter.isupper(): capitalCount += 1 else: smallCount += 1 if smallCount >= capitalCount: print(word.lower()) else: print(word.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom! Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*. Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
```python def gcd(x, y): if x > y: small = y else: small = x for i in range(1, small + 1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd def factorial(n): fact = 1 for i in range(1,n+1): fact = fact * i return fact a,b=map(int,input().split()) fa = factorial(a) fb = factorial(b) print(gcd(fa,fb)) ```
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 from math import floor n = int(input()) seq = 'ROYGBIV' seq2 = 'GBIV' n -= 7 if n == 0: print(seq) else: seq += floor(n/4)*seq2+seq2[:(n % 4 if n > 4 else n)] print(seq) ```
MatrixStudio/Codeforces-Python-Submissions
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left. Your problem is to print the minimum possible length of the sequence of moves after the replacements.
```python l=int(input()) n=input() s=l i=0 while i<l-1: if n[i]!=n[i+1]: s-=1 i+=2 else: i+=1 print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya lives in a strange world. The year has *n* months and the *i*-th month has *a**i* days. Vasya got a New Year present — the clock that shows not only the time, but also the date. The clock's face can display any number from 1 to *d*. It is guaranteed that *a**i*<=≤<=*d* for all *i* from 1 to *n*. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number *d*<=+<=1, so after day number *d* it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day *d* is also followed by day 1. Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month. A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the *n*-th month inclusive, considering that on the first day of the first month the clock display showed day 1.
```python D = int(input()) N = int(input()) A = list(map(int, input().split())) s = 0 for i in range(N-1): s += D-A[i] print(s) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment. Vitaly sees a building of *n* floors and 2·*m* windows on each floor. On each floor there are *m* flats numbered from 1 to *m*, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·*m* from left to right, then the *j*-th flat of the *i*-th floor has windows 2·*j*<=-<=1 and 2·*j* in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on. Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.
```python n,m = map(int,input().split()) l = [] for i in range(n): l.append(list(map(int,input().split()))) ll = [] for j in range(n*m): ll.append(0) for i in range(len(l)): for j in range(len(l[i])): if l[i][j]: ll[i*n+j//2]=1 print(ll.count(1)) ```
MatrixStudio/Codeforces-Python-Submissions
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of *n* rows and *m* columns. Cell (*x*,<=*y*) is the cell in the *x*-th row in the *y*-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1,<=1), that is top left corner of the matrix. Then she goes down all the way to cell (*n*,<=1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. *n* and *m* given are such that she always end up in cell (1,<=2). Lara has already moved to a neighbouring cell *k* times. Can you determine her current position?
```python print("_RANDOM_GUESS_1689259586.8015401")# 1689259586.801548 ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as *n* measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result *x*, and the largest result *y*, then the inequality *y*<=≤<=2·*x* must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes. Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.
```python from collections import Counter as cc import sys sys.stdin=open("input.txt") sys.stdout=open("output.txt", 'w') n = int(input()) l = list(map(int, input().split())) d = dict(cc(l)) g = sorted(list(d.items()), key = lambda x:x[0]) # print(g) a=0 r=0 for i in range(1,len(g)): if g[i][0]>2*g[0][0]: r=i break for i in range(r,len(g)): a+=g[i][1] b=0 r=0 for i in range(len(g)-2,-1,-1): if g[i][0]*2<=g[-1][0]: r=i break for i in range(r,-1,-1): b+=g[i][1] print(min(a,b)) ```
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 jxtymdfJyjtxbckj= int(input()) w = list(map(int,input().split())) b = [1] for i in range(1,len(w)): if w[i] > w[i - 1]: b.append(b[i-1] + 1) else: b.append(1) print( max(b) ) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python m=int(input()) n=int(input()) c=m*n for i in range(260): if 2*i<=m*n and 2*(i+1)>m*n: print(i) ```
MatrixStudio/Codeforces-Python-Submissions
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is "maximal". Note that the first and last seats are not adjacent (if $n \ne 2$).
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) s = list(input().rstrip()) if n == 1: ans = "Yes" if s[0] & 1 else "No" elif n == 2: ans = "Yes" if (s[0] ^ s[1]) & 1 else "No" else: ans = "Yes" for i in range(n): if s[i] & 1: for j in [i - 1, i + 1]: if not 0 <= j < n: continue if s[j] & 1: ans = "No" else: f = 0 for j in [i - 1, i + 1]: if not 0 <= j < n: continue if s[j] & 1: f = 1 if not f: ans = "No" print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on. Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
```python def change(b): a=[[True for i in range(3)] for j in range(3)] for i in range(0,3): for j in range(0,3): while (b[i][j]): a[i][j]=not a[i][j] a[(i+1)%3][j]=not a[(i+1)%3][j] a[(i+2)%3][j]=not a[(i+2)%3][j] a[i][(j+1)%3]=not a[i][(j+1)%3] a[i][(j+2)%3]=not a[i][(j+2)%3] b[i][j]=b[i][j]-1 for i in range(0,3): for j in range(0,3): if (a[i][j]==True): a[i][j]='1' else: a[i][j]='0' return a b=[] for i in range(0,3): c=[(int(j)%2) for j in input().split()] b.append(c) a=change(b) for i in range(0,3): print(''.join(a[i])) ```
MatrixStudio/Codeforces-Python-Submissions
As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are *n* jars of honey lined up in front of Winnie-the-Pooh, jar number *i* contains *a**i* kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that *k* kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly *k* kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.
```python n, k = map(int, input().split()) jars = list(map(int, input().split())) piggies_share = 0 for i in range(n): if jars[i] >= k: num_eaten = min(3, jars[i] // k) jars[i] -= num_eaten * k piggies_share += jars[i] print(piggies_share) ```
MatrixStudio/Codeforces-Python-Submissions
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2. Diameter of multiset consisting of one point is 0. You are given *n* points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed *d*?
```python n,d=map(int,input().split()) arr=list(map(int,input().split())) arr.sort() ans=float("inf") for i,el in enumerate(arr): res=0 for j,p in enumerate(arr): if i!=j: if arr[j]>arr[i]+d or arr[j]<arr[i]: res+=1 ans=min(ans,res) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with *n* vertices and a positive number *k*. Find the number of distinct pairs of the vertices which have a distance of exactly *k* between them. Note that pairs (*v*, *u*) and (*u*, *v*) are considered to be the same pair.
```python import sys sys.setrecursionlimit(10_000_000) input = sys.stdin.readline nodes_cnt, K = map(int, input().split()) neighbors_of = [[] for _ in range(nodes_cnt)] for _ in range(nodes_cnt - 1): a, b = map(int, input().split()) a -= 1 b -= 1 neighbors_of[a].append(b) neighbors_of[b].append(a) pairs_cnt = 0 def visit(node: int, parent: int or None) -> dict: if neighbors_of[node] == [parent]: return {0: 1} children_results = [visit(child, parent=node) for child in neighbors_of[node] if child != parent] nodes_cnt_at_depth = {0: 1} for i in range(1, K + 1): nodes_cnt_at_depth[i] = sum(child.get(i - 1, 0) for child in children_results) res = nodes_cnt_at_depth[K] for d1 in range(1, K // 2 + 1): d2 = K - d1 cur = 0 for child in children_results: cur += child.get(d1 - 1, 0) * (nodes_cnt_at_depth[d2] - child.get(d2 - 1, 0)) if d1 == d2: res += cur // 2 else: res += cur global pairs_cnt pairs_cnt += res return nodes_cnt_at_depth visit(0, None) print(pairs_cnt) ```
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 m=input() n=input() result="" for i in range(len(m)): p=int(m[i]) q=int(n[i]) result+=str(p^q) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
You have *n* devices that you want to use simultaneously. The *i*-th device uses *a**i* units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·*a**i* units of power. The *i*-th device currently has *b**i* units of power stored. All devices can store an arbitrary amount of power. You have a single charger that can plug to any single device. The charger will add *p* units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·*p* units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible. You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power. If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
```python def check(a,charge,k): cost=0 for need,bank in a: l=need*(k) if l>bank: cost+=(l-bank)/charge if cost>k: return False return True def f(a,charge): # print(check(a,charge,0.5)) lo=0 hi=len(str(charge))*(10) ans=None while lo<=hi: mid=(lo+hi)/2 # print(mid,check(a,charge,mid)) if check(a,charge,mid): lo=mid+1 ans=mid else: hi=mid-1 if hi==len(str(charge))*(10): return -1 return ans n,charge=map(int,input().strip().split()) blanck=[] for i in range(n): l,r=map(int,input().strip().split()) blanck.append((l,r)) print(f(blanck,charge)) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
```python s= input() t= input() if s[::-1]==t: print("YES") else: print("NO") ```
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 p = input() count = 0 for i in range(len(p)-1): if p[i] == p[i+1]: count += 1 if count == 7: break if count == 7: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
```python n_leaves= int(input()) s=set() c=0 for i in range(n_leaves): d=input() s.add(d) for j in range(len(s)): c=c+1 print(c) ```
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 x = int(input()) ac = 0 bc = 0 cc = 0 for i in range(x): a, b, c = map(int, input().split()) ac = ac + a bc = bc + b cc = cc + c if ac == 0 and bc == 0 and cc == 0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each digit. One day when Malek wanted to go from floor 88 to floor 0 using the elevator he noticed that the counter shows number 89 instead of 88. Then when the elevator started moving the number on the counter changed to 87. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem. Suppose the digital counter is showing number *n*. Malek calls an integer *x* (0<=≤<=*x*<=≤<=99) good if it's possible that the digital counter was supposed to show *x* but because of some(possibly none) broken sticks it's showing *n* instead. Malek wants to know number of good integers for a specific *n*. So you must write a program that calculates this number. Please note that the counter always shows two digits.
```python a = [2, 7, 2, 3, 3, 4, 2, 5, 1, 2] #print(len(a)) n = input() ans = a[(ord(n[0]) - ord('0'))] * a[(ord(n[1]) - ord('0'))] print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously). Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
```python n=int(input()) l=input().split() lo=int(l[0]) hi=int(l[0]) b = 0 for i in range(1,len(l)): if int(l[i])>hi: hi=int(l[i]) b+=1 elif int(l[i])<lo: lo=int(l[i]) b+=1 print(b) ```
MatrixStudio/Codeforces-Python-Submissions
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of *n* different natural numbers from 1 to *n* to obtain total control over her energy. But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.
```python Sum = 0 Num = int(input()) for i in range(len(str(Num))): if Num % 10 > 0: Sum = Sum + 2 ** i Num //= 10 print(Sum) ```
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
```python impot math j=int(input()) elesteps=math.ceil(j/5) ```
MatrixStudio/Codeforces-Python-Submissions
The Berland Armed Forces System consists of *n* ranks that are numbered using natural numbers from 1 to *n*, where 1 is the lowest rank and *n* is the highest rank. One needs exactly *d**i* years to rise from rank *i* to rank *i*<=+<=1. Reaching a certain rank *i* having not reached all the previous *i*<=-<=1 ranks is impossible. Vasya has just reached a new rank of *a*, but he dreams of holding the rank of *b*. Find for how many more years Vasya should serve in the army until he can finally realize his dream.
```python def find_years_to_rise(n, d, a, b): cumulative_years = [0] * (n + 1) # Calculate the cumulative number of years to reach each rank. for i in range(1, n + 1): cumulative_years[i] = cumulative_years[i - 1] + d[i - 1] # Return the difference between the cumulative number of years to reach rank b and the cumulative number of years to reach rank a. return cumulative_years[b] - cumulative_years[a] n = 3 d = [5, 6] a = 1 b = 2 years_to_rise = find_years_to_rise(n, d, a, b) print(years_to_rise) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a *n* by *m* table. Denote *c*-th cell of *r*-th row as (*r*,<=*c*). The tail of the snake is located at (1,<=1), then it's body extends to (1,<=*m*), then goes down 2 rows to (3,<=*m*), then goes left to (3,<=1) and so on. Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#'). Consider sample tests in order to understand the snake pattern.
```python if __name__ == "__main__": n, k = map(int, input().split()) s="#"*k k-=1 s1="."*k s2="."*k s1+="#" s2="#"+s2 for i in range(n): if i%2==0: print(s) elif i%4==1: print(s1) elif i%4==3: print(s2) ```
MatrixStudio/Codeforces-Python-Submissions
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes. A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?
```python k,n,s,p = map(int,input().split()) sheets = (n + s - 1) // s ans = k * sheets print((ans + p - 1 ) // p) ```
MatrixStudio/Codeforces-Python-Submissions
Mike is trying rock climbing but he is awful at it. There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=&lt;<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height. Today Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions. Help Mike determine the minimum difficulty of the track after removing one hold.
```python n=int(input()) l=list(map(int,input().split())) m=[] for i in range(1,n-1): x=l[i] l.pop(i) res = [abs(j - i) for i, j in zip(l[: -1], l[1 :])] m.append(max(res)) l.insert(i,x) print(min(m)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python s=input() s1=105 s2=104 s3=103 s4=102 s5=101 for i in range(len(s)): if (s[i]=='h')and(i<s1): s1=i for i in range(s1,len(s)): if (s[i]=='e')and(i<s2): s2=i for i in range(s2,len(s)): if (s[i]=='l')and(i<s3): s3=i for i in range(s3,len(s)): if (s[i]=='l')and(i<s4)and(i>s3): s4=i for i in range(s4,len(s)): if (s[i]=='o')and(i<s5): s5=i if (s1<s2)and(s2<s3)and(s3<s4)and(s4<s5): print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Today, Wet Shark is given *n* bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right. Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
```python n=int(input()) elephants=[[]] count=0 for i in range(n): cord=[int(i) for i in input().split()] elephants.append([cord[0],cord[1]]) for i in range(n): for j in range(i+1,n): x1=elephants[i][0] y1=elephants[i][1] x2=elephants[j][0] y2=elephants[j][1] if(abs(x1-x2)==abs(y1-y2)): count+=1 print(count) ```