source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n* strings *t**i*. Each string has cost *c**i*.
Let's define the function of string , where *p**s*,<=*i* is the number of occurrences of *s* in *t**i*, |*s*| is the length of the string *s*. Find the maximal value of function *f*(*s*) over all strings.
Note that the string *s* is not necessarily some string from *t*.
|
```python
print("_RANDOM_GUESS_1693146323.519945")# 1693146323.5199614
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n = int(input())
l = list(map(int,input().split()))
e = 0
ei = 0
oi = 0
o = 0
for i in range(n):
if l[i] & 1:
o += 1
oi = i+1
else:
e += 1
ei = i+1
if o > e:
print(oi)
else:
print(ei)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Do you know a story about the three musketeers? Anyway, you will learn about its origins now.
Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.
There are *n* warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.
Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
|
```python
from collections import Counter as cntr
from math import inf
def cin():
return map(int, input().split(' '))
n, m = cin()
p = []
s = [set() for i in range(n+1)]
h = [0 for i in range(n+1)]
for i in range(m):
a, b = cin()
p += [(a,b,c) for c in s[a].inersection(s[b])]
s[a].add(b)
s[b].add(a)
h[a]+= 1
h[b]+= 1
print(min(h[a]+h[b]+h[c] for a,b,c in p) - 6 if p else -1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
|
```python
input();*r,=map(int,input().split())
print(['Still Rozdil',r.index(min(r))+1][r.count(min(r))==1])
```
|
|
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
color=set(input().split())
count = 4- len(color)
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor *d* between two integers *a* and *b* that is in a given range from *low* to *high* (inclusive), i.e. *low*<=≤<=*d*<=≤<=*high*. It is possible that there is no common divisor in the given range.
You will be given the two integers *a* and *b*, then *n* queries. Each query is a range from *low* to *high* and you have to answer each query.
|
```python
a, b = list(map(int,input().split()))
n = int(input())
itog = []
for _ in range(n):
l, r = list(map(int,input().split()))
a,b = min(a,b), max(a, b)
maxi = -1
x = 1
while x * x <= a:
if a % x == 0:
if b % x == 0:
if x >= l and x <= r and x >= maxi:
maxi = x
y = a // x
if b % y == 0:
if y >= l and y <= r and y >= maxi:
maxi = y
x += 1
itog.append(maxi)
for i in itog:
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string *s*, consisting of lowercase English letters and a positive integer *k*. Your task is to reorder the letters in the string *s* in such a way that the resulting string is a *k*-string.
|
```python
a=int(input())
s=input()
l=[]
for i in s:
l.append(i)
b=set(l)
c=0
for i in b:
if(l.count(i)!=a):
c=1
print("-1")
break
d=""
if(c==0):
for i in b:
d=d+i
print(d*a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size *k*.
Now Marmot wonders in how many ways he can eat between *a* and *b* flowers. As the number of ways could be very large, print it modulo 1000000007 (109<=+<=7).
|
```python
MOD = 1000000007
t, k = map(int, input().split())
dp = [0] * 100001
dp[0] = 1
for i in range(1, 100001):
dp[i] = dp[i - 1]
if i >= k:
dp[i] = (dp[i] + dp[i - k]) % MOD
for i in range(1, 100001):
dp[i] = (dp[i] + dp[i - 1]) % MOD
for _ in range(t):
a, b = map(int, input().split())
print((dp[b] - dp[a - 1]) % MOD)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Berland Football Cup starts really soon! Commentators from all over the world come to the event.
Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.
If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment.
Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.
What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?
|
```python
#autogenerated (:'D)
read_numbers = lambda: map(int, input().split())
INF = 1 << 64
#main
n, m, a, b = read_numbers()
r = n % m
print( min(r*b, (m-r)*a) )
```
|
|
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()
ls=list(s)
ls1=['h','e','l','l','o']
co=0;st=0;re=0
for i in ls1:
if(i in ls[st:]):
re=ls[st:].index(i)
co+=1
st=st+re+1;
else:
print("NO")
if(co==5):
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Imp is watching a documentary about cave painting.
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number *n* by all integers *i* from 1 to *k*. Unfortunately, there are too many integers to analyze for Imp.
Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all , 1<=≤<=*i*<=≤<=*k*, are distinct, i. e. there is no such pair (*i*,<=*j*) that:
- 1<=≤<=*i*<=<<=*j*<=≤<=*k*, - , where is the remainder of division *x* by *y*.
|
```python
from bisect import *
from collections import *
import sys
import io, os
import math
import random
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
maxint=10**21
def ceil(a, b):
if(b==0):
return maxint
a = -a
k = a // b
k = -k
return k
# arr=list(map(int, input().split()))
# n,m=map(int,input().split())
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def strinp(testcases):
k = 5
if (testcases == -1 or testcases == 1):
k = 1
f = str(input())
f = f[2:len(f) - k]
return f
def lcm(n):
ans=1
for i in range(2,n):
ans=(ans*i)//(gcd(ans,i))
return(ans)
def main():
n,k=map(int,input().split())
if(k>45):
print("NO")
dic={}
trig=True
for i in range(1,k+1):
if(n%i in dic):
trig=False
break
dic[n%i]=1
if(trig):
print("YES")
else:
print("NO")
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has *n* friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings *s*1,<=*s*2,<=...,<=*s**n*. All these strings consist only of digits and have the same length.
Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string *c* which is a prefix (the beginning) of each *s**i* for all *i* (1<=≤<=*i*<=≤<=*n*). Help Polycarpus determine the length of the city phone code.
|
```python
def get_city_phone_code(numbers: list):
prefix = ''
for f_letter_list in zip(*numbers):
if len(set(f_letter_list)) == 1:
prefix += f_letter_list[0]
else:
break
return len(prefix)
no_test = int(input())
for _ in range(no_test):
num_of_inp = int(input())
phone_codes = [input() for _ in range(num_of_inp)]
len_of_code = get_city_phone_code(phone_codes)
print(len_of_code)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n = int(input())
p = input().split()
p = [int(i) for i in p]
target = -6
for i in p:
if(p[i]%2 !=0):
target = i+1
break
print(target)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A flower shop has got *n* bouquets, and the *i*-th bouquet consists of *a**i* flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets.
Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.
Determine the maximum possible number of large bouquets Vasya can make.
|
```python
n = input()
odd = 0
even = 0
for a in map(int, input().split()):
if a % 2 == 1:
odd += 1
else:
even += 1
print(min(odd, even))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.
If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows:
1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game.
|
```python
n,v1,v2,t1,t2=input().split()
n=int(n)
v1=int(v1)
v2=int(v2)
t1=int(t1)
t2=int(t2)
t1=t1*2
t2=t2*2
v1=v1*n+t1
v2=v2*n+t2
if v1<v2:
print("First")
elif v1>v2:
print("Second")
else:
print("Friendship")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Bolek has found a picture with *n* mountain peaks painted on it. The *n* painted peaks are represented by a non-closed polyline, consisting of 2*n* segments. The segments go through 2*n*<=+<=1 points with coordinates (1,<=*y*1), (2,<=*y*2), ..., (2*n*<=+<=1,<=*y*2*n*<=+<=1), with the *i*-th segment connecting the point (*i*,<=*y**i*) and the point (*i*<=+<=1,<=*y**i*<=+<=1). For any even *i* (2<=≤<=*i*<=≤<=2*n*) the following condition holds: *y**i*<=-<=1<=<<=*y**i* and *y**i*<=><=*y**i*<=+<=1.
We shall call a vertex of a polyline with an even *x* coordinate a mountain peak.
Bolek fancied a little mischief. He chose exactly *k* mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the *y* coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1,<=*r*1), (2,<=*r*2), ..., (2*n*<=+<=1,<=*r*2*n*<=+<=1).
Given Bolek's final picture, restore the initial one.
|
```python
x=input()
x=x.split(" ")
z=input()
z=z.split(" ")
b=1
for i in range(int(x[1])):
z[b]=chr(ord(z[b])-1)
b+=2
for k in z:
print(k,end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be *p* bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect.
Polycarpus agrees to lower the price by no more than *d* bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.
Note, Polycarpus counts only the trailing nines in a price.
|
```python
a, b = map(int, input().split())
maxx = str(a)
c = 0
for i in range(a - b, a, -1):
count = 0
for j in str(i)[::-1]:
if j != "9":
break
count += 1
if count > c:
maxx = str(i)
c = count
print(maxx)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.
With that begins the watch of Jon Snow. He is assigned the task to support the stewards.
This time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.
Can you find how many stewards will Jon support?
|
```python
n=int(input())
l=[int(i) for i in input().split()]
s=0
m=max(l)
mi=min(l)
for i in range(n):
if l[i] < m and l[i] > mi :
s+=1
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence *a*0,<=*a*1,<=...,<=*a**h*, where *h* is the height of the tree, and *a**i* equals to the number of vertices that are at distance of *i* edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence *a**i*, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
|
```python
h = int(input())
A = list(map(int,input().split()))
f = False
for i,a in enumerate(A):
if f and a != 1:
f = None
break
else:
f = a != 1
if f is not None:
print('perfect')
else:
T = []
for j,a in enumerate(A):
if j == i:
x = len(T)
T += [len(T)]*a
print('ambiguous')
print(' '.join(map(str,T)))
T[x+1] = x-1
print(' '.join(map(str,T)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel has a board with *n* rows and *n* columns. So, the board consists of *n*<=×<=*n* cells. Each cell contains either a symbol '.', or a symbol '#'.
A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.
Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.
Please, tell Ciel if she can draw the crosses in the described way.
|
```python
def check(i, j):
global matrix, n
if j==0 or j==n-1 or i>n-3:
return False
matrix[i][j] = '.'
matrix[i+1][j] = '.'
matrix[i+2][j] = '.'
matrix[i+1][j-1] = '.'
matrix[i+1][j+1] = '.'
return True
n = int(input())
matrix = []
for i in range(n):
l = list(input())
matrix.append(l)
ans = True
for i in range(n):
for j in range(n):
if matrix[i][j] == '#':
ans = check(i, j)
if not ans:
break
if ans:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
- the queen's weight is 9, - the rook's weight is 5, - the bishop's weight is 3, - the knight's weight is 3, - the pawn's weight is 1, - the king's weight isn't considered in evaluating position.
The player's weight equals to the sum of weights of all his pieces on the board.
As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
|
```python
w=0
bl=0
for xx in range(8):
b=list(input())
if 'Q' in b:
w+=9*b.count('Q')
if 'R' in b:
w+=5*b.count('R')
if 'B' in b:
w+=3*b.count('B')
if 'N' in b:
w+=3*b.count('N')
if 'P' in b:
w+=1*b.count('P')
if 'q' in b:
bl+=9*b.count('q')
if 'r' in b:
bl+=5*b.count('r')
if 'b' in b:
bl+=3*b.count('b')
if 'n' in b:
bl+=3*b.count('n')
if 'p' in b:
bl+=1*b.count('p')
if w>bl:
print('White')
elif w==bl:
print('Draw')
else:
print('Black')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=<<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=<<=5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
|
```python
i=1
global result
while i<6 :
line = input()
type(line)
if line.__contains__('1'):
col = line.index('1')+1
result= abs(col-3)+abs(i-3)
i+=1
print(result,'\n')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Duff is in love with lovely numbers! A positive integer *x* is called lovely if and only if there is no such positive integer *a*<=><=1 such that *a*2 is a divisor of *x*.
Malek has a number store! In his store, he has only divisors of positive integer *n* (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.
Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.
|
```python
def check(x):
i=2
while i*i<=x:
if x%i==0:
return 0
i=i+1
return 1
a=int(input())
ans=1
while a!=1 and check(a)==0:
now=2
while a%now!=0:
now=now+1
ans=ans*now
while a%now==0:
a=a//now
ans=ans*a
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had *c* pages.
At first day Mister B read *v*0 pages, but after that he started to speed up. Every day, starting from the second, he read *a* pages more than on the previous day (at first day he read *v*0 pages, at second — *v*0<=+<=*a* pages, at third — *v*0<=+<=2*a* pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than *v*1 pages per day.
Also, to refresh his memory, every day, starting from the second, Mister B had to reread last *l* pages he read on the previous day. Mister B finished the book when he read the last page for the first time.
Help Mister B to calculate how many days he needed to finish the book.
|
```python
import math
c,v0,v1,a,l=map(int,input().split())
page=v0
page1=a
count=1
if a==0 and l==0:
print(math.ceil(c/v0))
exit(0)
if a==0 and l!=0:
k=math.ceil(c/v0)
print(math.ceil((c+k*l)/v0))
exit(0)
while page < c:
page+=page1
page-=l
if (page1+a) < v1:
page1+=a
count+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.
B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.
You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
|
```python
def main():
s=input()
s1 = ''.join(sorted(s))
print(s1,s)
if s1!=s:
print("NO")
return
countA = s.count('a')
countB = s.count('b')
countC = s.count('c')
if (countC == countA or countC == countB) and countA>0 and countB>0:
print("YES")
else:
print("NO")
return
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string *s*.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" "110"); 1. replace "11" with "1" (for example, "110" "10").
Let *val*(*s*) be such a number that *s* is its binary representation.
Correct string *a* is less than some other correct string *b* iff *val*(*a*)<=<<=*val*(*b*).
Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).
|
```python
input()
s = input()
if s.count('1') == 0:
print(0)
else:
print(bin(2 ** (s.count('0')))[2:])
```
|
|
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
a = int(input())
c = []
m = ''
for i in range(a):
b = input()
if len(b) < 11:
c.append(b)
elif len(b) > 10:
m += b[0]
m += str(len(b))
m += b[-1]
c.append(m)
m = ''
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your friend Mishka and you attend a calculus lecture. Lecture lasts *n* minutes. Lecturer tells *a**i* theorems during the *i*-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array *t* of Mishka's behavior. If Mishka is asleep during the *i*-th minute of the lecture then *t**i* will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — *a**i* during the *i*-th minute. Otherwise he writes nothing.
You know some secret technique to keep Mishka awake for *k* minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and *n*<=-<=*k*<=+<=1. If you use it on some minute *i* then Mishka will be awake during minutes *j* such that and will write down all the theorems lecturer tells.
You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
|
```python
import sys
input = sys.stdin.readline
def theorems(a,k,i):
ans = 0
for j in range(i,k+i):
ans += a[j]
return ans
def max_notes(a, t, n, k):
# a = list of number of theorems during each minute
# t = behaviour list
# n = total minutes
# k = number of minutes which can be kept awake
# ans = max([theorems(a,t,k,i) for i in range(n-k)])
ans = 0
index = 0
for i in range(n-k):
temp = theorems(a, k, i)
if temp > ans:
ans = temp
index = i
for i in range(index):
ans += (a[i]*t[i])
for i in range(index+k,n):
ans += (a[i]*t[i])
return ans
n,k = map(int, input().split())
a = [int(x) for x in input().split()]
t = [int(x) for x in input().split()]
print(max_notes(a,t,n,k))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
|
```python
number = int(input())
def find_correct_num(target):
low = 1
high = target
mid = (high + low) // 2
while high > low:
if sum_digit_and_itself(mid) == target:
return mid
elif sum_digit_and_itself(mid) > target:
high = mid
else:
low = mid + 1
mid = (high + low) // 2
return 0
def sum_digit_and_itself(number):
val = number
result = 0
while val > 0:
result += val % 10
val = val // 10
return result + number
print(find_correct_num(number))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
|
```python
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 22:56:38 2023
@author: HXY
"""
n=int(input())
list0=list(map(int,input().split()))
list0.sort()
m=int(input())
for _ in range(m):
x=int(input())
re=0
for y in list0:
if y<=x:
re+=1
else:
break
print(re)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka has got *n* empty boxes. For every *i* (1<=≤<=*i*<=≤<=*n*), *i*-th box is a cube with side length *a**i*.
Mishka can put a box *i* into another box *j* if the following conditions are met:
- *i*-th box is not put into another box; - *j*-th box doesn't contain any other boxes; - box *i* is smaller than box *j* (*a**i*<=<<=*a**j*).
Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.
Help Mishka to determine the minimum possible number of visible boxes!
|
```python
t = int(input())
arr = list(map(int,input().split()))
dict = {}
res = 0
for i in arr:
if i not in dict:
dict[i] = 1
res = max(res,dict[i])
else:
dict[i] += 1
res = max(res,dict[i])
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have *r* red, *g* green and *b* blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number *t* of tables can be decorated if we know number of balloons of each color?
Your task is to write a program that for given values *r*, *g* and *b* will find the maximum number *t* of tables, that can be decorated in the required manner.
|
```python
a =list(map(int,input.split())
stol=min(a)
summa=sum(a)
while summa-3*stol>=3:
stol+=1
summa-=3
print(stol)
```
|
|
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
n=int(input())
s=input()
s=s+' '
t=0
y=[]
for i in range(len(s)):
if s[i]!=' ':
t=t*10+int(s[i])
else:
y.append(t)
t=0
def gb(a,b):
c=a;d=b
while b>0:
if a<b:
a,b=b,a
a,b=b,a%b
e=c*d//a
return e
for i in range(len(y)-1):
c=gb(y[i],y[i+1])
if (c//y[i]%2==0 or c//y[i]%3==0 or c==y[i]) and (c//y[i+1]%2==0 or c//y[i+1]%3==0 or c==y[i+1]):
y[i+1]=c
else:
print('No');break
else:
print('Yes')
```
|
|
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
n=input()
i=0
c=1
while(i<len(n)):
if(i+1<len(n) and n[i]==n[i+1]):
c+=1
else:
c=1
if(c>=7):
print("YES")
break
print(c)
i+=1
if(c<7):
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has *n* apartments that are numbered from 1 to *n* and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.
Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly *k* already inhabited apartments, but he doesn't know their indices yet.
Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.
|
```python
n,k=map(int,input().split())
if n==k :
print(0,0)
else:
if n<3*k+1:
print(1,n-k)
else:
print(1,k*2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly *hh*:<=*mm*. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every *x* minutes until *hh*:<=*mm* is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.
A time is considered lucky if it contains a digit '7'. For example, 13:<=07 and 17:<=27 are lucky, while 00:<=48 and 21:<=34 are not lucky.
Note that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at *hh*:<=*mm*.
Formally, find the smallest possible non-negative integer *y* such that the time representation of the time *x*·*y* minutes before *hh*:<=*mm* contains the digit '7'.
Jamie uses 24-hours clock, so after 23:<=59 comes 00:<=00.
|
```python
def main():
X = int(input())
HH, MM = map(int, input().split())
m = MM
h = HH
snooze = 0
while 1:
if m % 10 == 7 or h % 10 == 7:
break
m -= X
if m < 0:
m += 60
h -= 1
if h < 0:
h += 24
snooze += 1
print(snooze)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
|
```python
n = int(input ())
L=[]
L=list(map(int,input().split()))
L.sort()
k=1
x=n
a=0
i=0
while(i<n-1) :
j=1
k1=1
a+=1
while ( L[i+j]==L[i]):
k1+=1
j+=1
if (i+j>=n-1):
break;
if (k1>k) :
k=k1
i=i+j
print (k,a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.
|
```python
a = [input() for _ in range(3)]
for i in range(3):
if a[i] == 'scissors':
a[i] = 's'
if a[i] == 'rock':
a[i] = 'r'
if a[i] == 'paper':
a[i] = 'p'
flag = False
if a[0] == 's':
if a[1] == 'p' and a[2] == 'p':
flag = True
print('F')
elif a[0] == 'p':
if a[1] == 'r' and a[2] == 'r':
flag = True
print('F')
elif a[0] == 'r':
if a[1] == 's' and a[2] == 's':
flag = True
print('F')
if not flag:
if a[1] == 's':
if a[0] == 'p' and a[2] == 'p':
flag = True
print('M')
elif a[1] == 'p':
if a[0] == 'r' and a[2] == 'r':
flag = True
print('M')
elif a[1] == 'r':
if a[0] == 's' and a[2] == 's':
flag = True
print('M')
if not flag:
if a[2] == 's':
if a[0] == 'p' and a[1] == 'p':
flag = True
print('S')
elif a[2] == 'p':
if a[0] == 'r' and a[1] == 'r':
flag = True
print('S')
elif a[2] == 'r':
if a[0] == 's' and a[1] == 's':
flag = True
print('S')
if not flag:
print('?')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
|
```python
n,m=map(int,input().split())
ans=set()
for i in range(n):
inp=list(map(int,input().split()))
for j in range(1,inp[0]):
if inp[j] in ans:
continue
else:
ans.add(inp[j])
if len(ans)==n:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.
Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.
Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
|
```python
n=int(input())
if n>=0:
print(n)
else:
a=str(n)
b=a[0:len(a)-1]
c=a[0:len(a)-2]+a[len(a)-1]
x=int(b)
y=int(c)
if x>y:
print(x)
else:
print(y)
```
|
|
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
def ceildiv(a, b):
return -(a // -b)
n, m, a = map(int(), input().strip().split())
print(ceildiv(n, a)+ceildiv(m,a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2<=×<=2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
|
```python
r1,r2=map(int,input().split(" "))
c1,c2=map(int,input().split(" "))
d1,d2=map(int,input().split(" "))
a=b=c=d=fl=0
for i in range(1,10):
a=i
b=r1-i
c=c1-a
d=c2-b
#print(a,b,c,d)
if r2<c or r2<d or r2<c+d:
continue
if a+d!=d1 or b+c!=d2:
continue
#print("Not diagnal")
elif a!=b and b!=c and c!=d and d!=a:
fl=1
break
if fl==1:
print(a,b)
print(c,d)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
|
```python
a, b = input().split()
a = int(a)
b = int(b)
strin=""
countA=0
countB=0
while a + b !=2:
if a < b:
countA = countA*(-1)
countB = countB + 1
b= b-a
elif a>b:
countB = countB*(-1)
countA = countA + 1
a= a-b
elif a==b and a!=1:
strin = "Impossible"
break
if (a==b and a!=1 and strin=="Impossible"):
break
if countB<0:
strin=strin+str(-countB)+'B'
# print(-countB,"B")
countB=0
elif countA <0:
strin=strin+str(-countA)+'A'
# print(-countA,"A")
countA=0
if (a==b and a==1):
countA = countA*(-1)
countB = countB*(-1)
if countB<0:
strin=strin+str(-countB)+'B'
# print(-countB,"B")
countB=0
elif countA <0:
strin=strin+str(-countA)+'B'
# print(-countA,"A")
countA=0
strin.replace(' ', '')
print(strin)
```
|
|
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 boredlife(a,b):
x,y=1,1
if(a<=b):
for i in range(1,a+1):
x *= i
return x
elif(a>b):
for i in range(1,b+1):
y *= i
return y
a,b = map(int,input().split())
print(boredlife(a,b))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
|
```python
s = input()
n1 = s.find("0000000")
n2 = s.find("1111111")
if(n1 != -1 or n2 != -1):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
|
```python
n=int(input())
j=0
lis=[]
def sm(x):
s=str(x)
k=0
for i in range (len(s)):
k=k+int(s[i])
return k
for x in range (n):
if n==x+sm(x):
lis.append(x)
print(len(lis))
for x in lis:
print(x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2.
По заданной последовательности целых положительных чисел *a*1,<=*a*2,<=...,<=*a**n* требуется найти *r* — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел *a**i*, которые делятся на *r*.
|
```python
a = []
n = int(input())
a += (int(i) for i in input().split())
r, m = 1, 1
while m != 0:
m2 = m
m = 0
for i in range(n):
if a[i] % r == 0:
m += 1
if m != 0:
r = r * 2
else:
break
print(m2, r // 2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given matrix with *n* rows and *n* columns filled with zeroes. You should put *k* ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.
One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.
If there exists no such matrix then output -1.
|
```python
def create_symmetrical_matrix(n, k):
# Check if it is possible to create a symmetrical matrix
if k > (n * n + 1) // 2:
return -1
# Create an empty matrix filled with zeros
matrix = [[0] * n for _ in range(n)]
# Fill the matrix with ones symmetrically
row, col = 0, 0
for i in range(k):
matrix[row][col] = 1
matrix[col][row] = 1
col += 1
if col == n:
row += 1
col = row
return matrix
# Read input from user
n, k = map(int, input().split())
# Create and print the resulting matrix
result = create_symmetrical_matrix(n, k)
if result == -1:
print(-1)
else:
for row in result:
print(' '.join(map(str, row)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer *n*?"
Petya knows only 5 integer types:
1) byte occupies 1 byte and allows you to store numbers from <=-<=128 to 127
2) short occupies 2 bytes and allows you to store numbers from <=-<=32768 to 32767
3) int occupies 4 bytes and allows you to store numbers from <=-<=2147483648 to 2147483647
4) long occupies 8 bytes and allows you to store numbers from <=-<=9223372036854775808 to 9223372036854775807
5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer *n*. Since BigInteger works much slower, Peter regards it last. Help him.
|
```python
# LUOGU_RID: 99907972
#include<iostream>
using namespace std;
int main()
{
long double n;
cin>>n;
if(n<=127)
{
cout<<"byte"<<endl;
}
else if(n<=32767)
{
cout<<"short"<<endl;
}
else if(n<=2147483647)
{
cout<<"int"<<endl;
}
else if(n<=9223372036854775807)
{
cout<<"long"<<endl;
}
else
{
cout<<"BigInteger"<<endl;
}
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=<<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=<<=5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
|
```python
a = list(map(int, input())
b,c = 0,0
for i in range(5):
for j in range(5):
if [i][j] == 1:
b = i - 2
b * -1 if b < 0
c = j - 2
c * -1 if b < 0
print(b+c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.
He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1.
Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.
Help Sherlock complete this trivial task.
|
```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 09:00:42 2020
@author: chaitanya
"""
size = int(input())+2
teacher_list = [0]*(size)
def isPrime(n) :
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def gcd(x, y):
while(y):
x, y = y, x % y
return x
for i in range(2,size):
if isPrime(i) == True:
teacher_list[i] = 1
teacher_number = 2
for i in range(2,size):
if teacher_list[i] == 0:
n1 = i
teacher_list[i] = teacher_number
for j in range (i+1,size):
n2 = j
if teacher_list[j] == 0:
if gcd(n1,n2) != n1:
teacher_list[j] = teacher_number
teacher_number += 1
print(teacher_number-1)
result = ''
for i in range(2,size):
result = result + str(teacher_list[i])+' '
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.
|
```python
def fu(a,b):
if a=="scissors" and b=="paper":
return True
elif a=="rock" and b=="scissors":
return True
elif a=="paper" and b=="rock":
return True
return False
f=input()
m=input()
s=input()
if fu(f,m) and fu(f,s):
print("F")
elif fu(m,f) and fu(m,s):
print("M")
elif fu(s,f) and fu(s,m):
print("S")
else:
print("?")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
|
```python
s=input()
d={'a':0,'e':0,'i':0,'o':0,'u':0}
c=0
for i in s:
if(i in d):
c+=1
elif('0'<i<'9' and int(i)%2!=0):
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) is coprime, then the pair (*a*,<=*c*) is coprime.
You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (*a*,<=*b*,<=*c*), for which the statement is false, and the numbers meet the condition *l*<=≤<=*a*<=<<=*b*<=<<=*c*<=≤<=*r*.
More specifically, you need to find three numbers (*a*,<=*b*,<=*c*), such that *l*<=≤<=*a*<=<<=*b*<=<<=*c*<=≤<=*r*, pairs (*a*,<=*b*) and (*b*,<=*c*) are coprime, and pair (*a*,<=*c*) is not coprime.
|
```python
a,b=map(int,input().split())
if((b-a)==1):
print(-1)
else:
if(a%3==0):
print(a,a+1,a+3)
elif(a%2==0):
print(a,a+1,a+2)
else:
if((b-a)<3):
if(a%2==0):
print(a,a+1,a+2)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.
A sequence of *l* integers *b*1,<=*b*2,<=...,<=*b**l* (1<=≤<=*b*1<=≤<=*b*2<=≤<=...<=≤<=*b**l*<=≤<=*n*) is called good if each number divides (without a remainder) by the next number in the sequence. More formally for all *i* (1<=≤<=*i*<=≤<=*l*<=-<=1).
Given *n* and *k* find the number of good sequences of length *k*. As the answer can be rather large print it modulo 1000000007 (109<=+<=7).
|
```python
import math
def factor(n):
ans=[]
i=1
while(i<=int(math.sqrt(n))):
if(n//i==i and n%i==0):
ans.append(i)
else:
if(n%i==0):
ans.append(i)
ans.append(n//i)
i=i+1
return ans;
from collections import defaultdict
al=defaultdict(int)
we=[]
n,k=map(int,input().split())
we.append([0])
for i in range(1,n+1):
x=factor(i)
we.append(x)
for i in range(n):
al[i+1]=1
for i in range(k-1):
ze=al.copy()
for j in range(1,n+1):
al[j]=sum(ze[t] for t in we[j])
print(sum(al[i] for i in range(1,n+1))%(10**9+7))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
|
```python
n=int(input())
count=0
if(n>=100):
count=count+(n//100)
n=n%100
if(n>=20):
count=count+(n//20)
n=n%20
if(n>=10):
count=count+(n//10)
n=n%10
if(n>=5):
count=count+(n//5)
n=n%5
if(n>=1):
count=count+(n//1)
n=n%1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)$. You need to find for each query the sum of elements of the array with indexes from $l_i$ to $r_i$, inclusive.
The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
|
```python
n, q = map(int, input().split())
a = list(map(int, input().split()))
height_map = [0] * n
for _ in range(q):
l, r = map(int, input().split())
for i in range(l - 1, r):
height_map[i] += 1
height_map_sorted = sorted(height_map)
a_sorted = sorted(a)
out = 0
for i in range(n):
i_ = height_map_sorted.index(height_map[i])
out += a_sorted[i_] * height_map_sorted[i_]
del a_sorted[i_]
del height_map_sorted[i_]
print(out)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.
For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.
Write a program that will print the name of a man who will drink the *n*-th can.
Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
|
```python
n=input()
n=int(n)
a=['Sheldon','Leonard','Penny','Rajesh','Howard']
if(n>4):
for i in range(n-5):
p=a[0]
a.append(p)
a.append(p)
a.remove(p)
print(a[n-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly *x* chunks. Now he wonders whether he can buy exactly this amount of chicken.
Formally, Ivan wants to know if he can choose two non-negative integers *a* and *b* in such a way that *a* small portions and *b* large ones contain exactly *x* chunks.
Help Ivan to answer this question for several values of *x*!
|
```python
def canChange(coinList,totalCoin):
result = [[0 for i in range(totalCoin + 1)] for j in range(len(coinList) + 1)]
for j in range(totalCoin+1):
result[0][j] = float("inf")
for i in range(1,len(coinList)+1):
for j in range(1,totalCoin + 1):
if j >= coinList[i-1]:
result[i][j] = min(result[i - 1][j], result[i][j - coinList[i - 1]]+1)
else:
result[i][j] = result[i-1][j]
return result[i][j]
if __name__ == "__main__":
n = int(input())
coinList = [3, 7]
for i in range(n):
totalCoin = int(input())
if canChange(coinList,totalCoin) != float("inf"):
print("Yes")
else:
print("No")
```
|
|
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())
i=1
cnt=0
while(i*i<n):
if (n%i==0):
cnt+=2
i+=1
if (i*i==n) :
cnt+=1
if (cnt < k):
print(-1)
else :
i=1
c=0
while(i*i <= n ) :
if (n%i ==0):
c+=1
# else :
i+=1
if (k==c):
print(i)
break
if (k==cnt-c):
print(n//i)
break
i+=1
# if (c==k) :
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0,<=0) and Varda's home is located in point (*a*,<=*b*). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (*x*,<=*y*) he can go to positions (*x*<=+<=1,<=*y*), (*x*<=-<=1,<=*y*), (*x*,<=*y*<=+<=1) or (*x*,<=*y*<=-<=1).
Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (*a*,<=*b*) and continue travelling.
Luckily, Drazil arrived to the position (*a*,<=*b*) successfully. Drazil said to Varda: "It took me exactly *s* steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0,<=0) to (*a*,<=*b*) in exactly *s* steps. Can you find out if it is possible for Varda?
|
```python
a,b,s = map(int, input().split())
min_steps = max(a,b)
if s<min_steps:
print("NO")
else:
if (s - min_steps)%2==0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let *a* is a permutation of an integers from 1 to *n*, inclusive, and *a**i* denotes the *i*-th element of the permutation. The Little Elephant's recursive function *f*(*x*), that sorts the first *x* permutation's elements, works as follows:
- If *x*<==<=1, exit the function. - Otherwise, call *f*(*x*<=-<=1), and then make *swap*(*a**x*<=-<=1,<=*a**x*) (swap the *x*-th and (*x*<=-<=1)-th elements of *a*).
The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to *n*, such that after performing the Little Elephant's function (that is call *f*(*n*)), the permutation will be sorted in ascending order.
|
```python
n = int(input())
permutation = [str(n)]
for i in range(1, n):
permutation.append(str(i))
print(" ".join(permutation))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
|
```python
lines=input()
line=[]
for i in lines:
line.append(i)
i=1
total=len(line)
while i<len(line):
if line[-i]==')':
break
else:
total-=1
i+=1
io=0
do=0
while io<len(line):
if line[io]=='(':
break
else:
do+=1
io+=1
end=0
for i in range(do,total):
if line[i]==")":
end+=1
start=total-end
if start<end:
print(int(start+start))
else:
print(int(end+end))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the *expose* procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)
Given integers *l*, *r* and *k*, you need to print all powers of number *k* within range from *l* to *r* inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
|
```python
l,r,k = [int(i) for i in input().split()]
cur = 1
while cur < l :
cur *= k
ret = []
while l <= cur and cur <= r :
ret.append(cur)
cur *= k
if len(ret) == 0 :
ret.append(-1)
for ans in ret :
print(ans,end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
|
```python
inp = [int(i) for i in input().split()]
num_buttons, num_bulbs = inp[0], inp[1]
lit = set()
for i in range(num_buttons):
line = [int(i) for i in input().split()][1:]
lit.update(line)
if len(lit) == num_bulbs:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a string *A*. Find a string *B*, where *B* is a palindrome and *A* is a subsequence of *B*.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".
A palindrome is a string that reads the same forward or backward.
The length of string *B* should be at most 104. It is guaranteed that there always exists such string.
You do not need to find the shortest answer, the only restriction is that the length of string *B* should not exceed 104.
|
```python
a=input()
b=''
n=len(a)
i=-1
while i>=-n:
b+=a[i]
i=i-1
if a==b:
print(a)
else:
for i in a:
print(i,end='')
i=0
while i<len(b):
if i==0:
pass
else:
print(b[i],end='')
i=i+1
print()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have array *a*1,<=*a*2,<=...,<=*a**n*. Segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) is good if *a**i*<==<=*a**i*<=-<=1<=+<=*a**i*<=-<=2, for all *i* (*l*<=+<=2<=≤<=*i*<=≤<=*r*).
Let's define *len*([*l*,<=*r*])<==<=*r*<=-<=*l*<=+<=1, *len*([*l*,<=*r*]) is the length of the segment [*l*,<=*r*]. Segment [*l*1,<=*r*1], is longer than segment [*l*2,<=*r*2], if *len*([*l*1,<=*r*1])<=><=*len*([*l*2,<=*r*2]).
Your task is to find a good segment of the maximum length in array *a*. Note that a segment of length 1 or 2 is always good.
|
```python
n=int(input())
m=[int(i) for i in input().split()]
m=m[::-1]
if n>2:
maxLength=length=2
for i in range(n-2):
if m[i]==m[i+1]+m[i+2]:
length+=1
maxLength=max(length,maxLength)
else:
length=2
if maxLength==2:
for i in range(n-1):
if m[i]==m[i+1]:
b=False
break
else:
b=True
if b :
maxLength=1
print(maxLength)
else :
if n==1:
print(1)
else:
if m[0]==m[1]:
print(2)
else:
print(1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.
|
```python
n = int(input())
s = input().strip()
letter_set = set()
for char in s:
if 'a' <= char <= 'z' or 'A' <= char <= 'Z':
letter_set.add(char.lower())
if len(letter_set) == 26:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks.
There are *n* banks, numbered from 1 to *n*. There are also *n*<=-<=1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank *i* has initial strength *a**i*.
Let us define some keywords before we proceed. Bank *i* and bank *j* are neighboring if and only if there exists a wire directly connecting them. Bank *i* and bank *j* are semi-neighboring if and only if there exists an online bank *k* such that bank *i* and bank *k* are neighboring and bank *k* and bank *j* are neighboring.
When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.
To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank *x* if and only if all these conditions are met:
1. Bank *x* is online. That is, bank *x* is not hacked yet. 1. Bank *x* is neighboring to some offline bank. 1. The strength of bank *x* is less than or equal to the strength of Inzane's computer.
Determine the minimum strength of the computer Inzane needs to hack all the banks.
|
```python
# 答案好像就只有3种情况
import sys
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, sys.stdin.readline().split())
g[u - 1].append(v - 1)
g[v - 1].append(u - 1)
def check(x):
root = None
for i,v in enumerate(a):
if v < x - 1:
continue
s = {i} if v == x else set(g[i] + [i])
if not root:
root = s
else:
root &= s
if not root:
return False
return True
mx = max(a)
for x in range(mx,mx + 2):
if check(x):
print(x)
break
else:
print(mx + 2)
```
|
|
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, k = [int(s) for s in input().split()]
if (n % k != 0):
n = n + (k - n % z)
if (m % z != 0):
m = m + (k - m % z)
print(n * m // (k * k))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The last stage of Football World Cup is played using the play-off system.
There are *n* teams left in this stage, they are enumerated from 1 to *n*. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.
Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids *a* and *b* can meet.
|
```python
from math import log2, floor, ceil
n, a, b = map(int, input().split())
a -= 1
b -= 1
counter = 1
while abs(a - b) != 1:
a = a // 2
b = b // 2
n = n // 2
counter += 1
if n == 2:
print("Final!")
else:
print(counter)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly *k* time units for the lunch break.
The Rabbits have a list of *n* restaurants to lunch in: the *i*-th restaurant is characterized by two integers *f**i* and *t**i*. Value *t**i* shows the time the Rabbits need to lunch in the *i*-th restaurant. If time *t**i* exceeds the time *k* that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal *f**i*<=-<=(*t**i*<=-<=*k*). Otherwise, the Rabbits get exactly *f**i* units of joy.
Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
|
```python
n,k = map(int,input().split())
joy =0
for i in range(n):
f,t = map(int,input().split())
if t <= k:
if joy < f:
joy = f
else:
if joy < f:
joy = f-(t-k)
print(joy)
```
|
|
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 = input()
s = input()
c = []
for i in range(len(s)):
c.append(s[i])
cnt_anton = 0
cnt_danik = 0
for i in c:
if i == 'A':
cnt_anton += 1
elif i == 'D':
cnt_danik += 1
if cnt_anton == cnt_danik:
print('Friendship')
elif cnt_anton > cnt_danik:
print('Anton')
else:
print('Danik')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:
- on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him.
|
```python
N = int(input())
Line1= input()
X =Line1[0]
O=Line1[1]
Rslt ='YES'
if N>2 and X==O:
Rslt = 'NO
if X==Line1[N-1]:
Space=Line1[1:-1:]
Space=Space.repalce(O,'')
if len(Space)! =0:
Rslt ='NO'
else: Rslt ='NO'
for n in range(1,N) :
if Rslt =='NO' : break
Line1 =input()
if X==Line1[n] and X==Line1[N-n-1]:
Line1[n] =''
Line1[N-n-1]=''
Space=Line1
Space=Space.repalce(O,'')
if len(Space)! =0:
Rslt ='NO'
else: Rslt ='NO'
print(Rslt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave a left footprint on the *i*-th block. If there already is a footprint on the *i*-th block, the new footprint will cover the old one.
At the beginning, there were no footprints. Then polar bear Alice starts from the *s*-th block, makes a sequence of moves and ends in the *t*-th block. It is known that Alice never moves outside of the road.
You are given the description of Alice's footprints. Your task is to find a pair of possible values of *s*,<=*t* by looking at the footprints.
|
```python
'''input
11
.RRRLLLLL..
'''
def main():
n = int(input())
s = input()
rI = []
lI = []
for index, i in enumerate(s):
if i == 'R':
rI.append(index + 1)
if i == 'L':
lI.append(index + 1)
if len(rI) != 0:
print(rI[0], rI[-1])
else:
print(lI[-1], lI[0]-1)
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel is playing a game with numbers now.
Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* > *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum of all numbers as small as possible.
Please help Ciel to find this minimal sum.
|
```python
input()
li = [int(x) for x in input().split()]
li.sort()
mi = min([ li[i]-li[i-1] if li[i]>li[i-1] else li[i] for i in range(1,len(li))])
print(mi*len(li))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the *k*-rounding of *n*.
|
```python
import math
import sys
a, k = map(int, input().split())
f = pow(10, k)
ans = a*f/(math.gcd(a, f))
print(int(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
s=input()
up,lp=0,0
for i in range(len(s)):
if(s[i].islower()):
lp+=1
elif(s[i].isupper()):
up+=1
if(up>lp):
print(s.upper())
else:
print(s.lower())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed *k* hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.
Vasya has a train lighting schedule for all *n* hours of the trip — *n* numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose *k* hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.
|
```python
n, k = map(int,input().split())
a = list(map(int,input().split()))
num_dict = dict(enumerate(a))
sorted_dict = sorted(num_dict.items(),key=lambda item:item[1],reverse=True)
print(sorted_dict[k-1][1])
ans = []
for i in range(k):
ans.append(sorted_dict[i][0]+1)
ans.sort()
print(*ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
a, b = map(int, input().split())
x1 = 0
x2 = 0
x0 =0
for i in range(1,7):
if abs(a-i)<abs(b-i):
x1 += 1
elif abs(a-i)>abs(b-i):
x2 += 1
else:
x0 += 1
print(x1,x0,x2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The "BerCorp" company has got *n* employees. These employees can use *m* approved official languages for the formal correspondence. The languages are numbered with integers from 1 to *m*. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
|
```python
def main():
def root(a):
b = f[a]
while b != a:
a, b = b, f[b]
return a
n, m = map(int, input().split())
f = list(range(n))
lang = []
for _ in range(n):
ll = [False] * m
for i in map(int, input().split()[1:]):
ll[i - 1] = True
lang.append(ll)
for i, langi in enumerate(lang):
for j in range(i):
if j == root(j) and any(a and b for a, b in zip(lang[i], lang[j])):
f[j] = i
for _, flag in enumerate(lang[j]):
langi[_] |= flag
print(sum(i == root(i) for i in range(n)) - any(lang))
if __name__ == '__main__':
main()
```
|
|
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
# -*- coding: utf-8 -*-
"""amiel_waytoolongwords.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1tSoTlicf2NxgfqGfa7OVyjBCFZZHHF5E
"""
n = int(input())
wordlist = []
for ctr in range(n):
word = input()
wordlist.append(word)
for x in wordlist:
if len(x) <= 10:
print(x)
else:
print(x[0]+str(len(word)-2)+x[-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.
One of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.
Please help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.
|
```python
x,y=[int(x) for x in input().split()]
if x**y < y**x:
print("<")
elif x**y > y**x:
print(">")
else x**y==y**x:
print("=")
```
|
|
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()
if 'h' in s and 'e' in s and 'l' in s and s.count('l') >= 2 and 'o' in s:
if s.index('h') < s.index('e') < s.index('l') < s.index('o'):
print('YES')
else:
print('NO')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.
Array *a* is *k*-period if its length is divisible by *k* and there is such array *b* of length *k*, that *a* is represented by array *b* written exactly times consecutively. In other words, array *a* is *k*-periodic, if it has period of length *k*.
For example, any array is *n*-periodic, where *n* is the array length. Array [2,<=1,<=2,<=1,<=2,<=1] is at the same time 2-periodic and 6-periodic and array [1,<=2,<=1,<=1,<=2,<=1,<=1,<=2,<=1] is at the same time 3-periodic and 9-periodic.
For the given array *a*, consisting only of numbers one and two, find the minimum number of elements to change to make the array *k*-periodic. If the array already is *k*-periodic, then the required value equals 0.
|
```python
l=list(map(int,input().split()))
n,k=l[0],l[1]
a=list(map(int,input().split()))
ans=0
count=[0 for _ in range(k)]
for i in range(n):
if a[i]==1:count[i%k]+=1
for i in range(k):
if count[i]!=n//k:
ans+=min(n//k-count[i],count[i])
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.
More formally, there are 3*n* gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the circle by numbers from 0 to 3*n*<=-<=1, let the gnome sitting on the *i*-th place have *a**i* coins. If there is an integer *i* (0<=≤<=*i*<=<<=*n*) such that *a**i*<=+<=*a**i*<=+<=*n*<=+<=*a**i*<=+<=2*n*<=≠<=6, then Tanya is satisfied.
Count the number of ways to choose *a**i* so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo 109<=+<=7. Two ways, *a* and *b*, are considered distinct if there is index *i* (0<=≤<=*i*<=<<=3*n*), such that *a**i*<=≠<=*b**i* (that is, some gnome got different number of coins in these two ways).
|
```python
n=int(input());print(((3**(3*n)-(7**n))%(int(1e9)+7))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).
We have a sequence of characters he has typed and we want to find the original message.
|
```python
s = input()
message = input()
key = 'qwertyuiopasdfghjkl;zxcvbnm,./'
new = ''
if s == "R":
for i in message:
new+=key[key.index(i)-1]
else:
for i in message:
new+=key[key.index(i)+1]
print(new)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub got bored, so he invented a game to be played on paper.
He writes *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices *i* and *j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) and flips all values *a**k* for which their positions are in range [*i*,<=*j*] (that is *i*<=≤<=*k*<=≤<=*j*). Flip the value of *x* means to apply operation *x*<==<=1 - *x*.
The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
|
```python
n=int(input())
#wut
a=list(map(int, input().split()))
counter = 0
maxm=0
alr=0
for i in range(n):
if a[i]==1:
alr+=1
for i in range(n):
if a[i] == 0:
counter+=1
maxm=max(maxm, counter)
elif counter > 0 :
counter-=1
if maxm > 0:
print(maxm+alr)
else:
print(alr-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera has got a rectangle table consisting of *n* rows and *m* columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row *x* and column *y* by a pair of integers (*x*,<=*y*).
Valera wants to place exactly *k* tubes on his rectangle table. A tube is such sequence of table cells (*x*1,<=*y*1), (*x*2,<=*y*2), ..., (*x**r*,<=*y**r*), that:
- *r*<=≥<=2; - for any integer *i* (1<=≤<=*i*<=≤<=*r*<=-<=1) the following equation |*x**i*<=-<=*x**i*<=+<=1|<=+<=|*y**i*<=-<=*y**i*<=+<=1|<==<=1 holds; - each table cell, which belongs to the tube, must occur exactly once in the sequence.
Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:
- no pair of tubes has common cells; - each cell of the table belongs to some tube.
Help Valera to arrange *k* tubes on his rectangle table in a fancy manner.
|
```python
def solve(n,m,k):
res = []
f = 0
for i in range(n):
for j in range(m):
if(f):
res.append([i+1,m-j])
else:
res.append([i+1,j+1])
f = ~f
print(res)
c = 0
for j in range(k-1):
print(2,res[c][0],res[c][1],res[c+1][0],res[c+1][1])
c += 2
print(len(res)-c , end=" ")
for i in range(c,len(res)):
print(res[i][0],res[i][1],end= " ")
print()
n,m,k = [int(ele) for ele in input().split()]
solve(n,m,k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel has some flowers: *r* red flowers, *g* green flowers and *b* blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:
- To make a "red bouquet", it needs 3 red flowers. - To make a "green bouquet", it needs 3 green flowers. - To make a "blue bouquet", it needs 3 blue flowers. - To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower.
Help Fox Ciel to find the maximal number of bouquets she can make.
|
```python
def f(r,g,b):
d = min(r, g, b)
return d + (r - d) // 3 + (g - d) // 3 + (b - d) // 3
a=0
be=0
c=0
r, g, b = map(int, input().split())
if r>=3:
a=f(r-3,g,b)+1
if g>=3:
be=f(r,g-3,b) +1
if b>=3:
c=f(r,g,b-3)+1
d=f(r,g,b)
print(max(a,be,c,d))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.
With that begins the watch of Jon Snow. He is assigned the task to support the stewards.
This time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.
Can you find how many stewards will Jon support?
|
```python
n,arr = int(input()),input().split()
print(0 if n<=2 else n-2)
```
|
|
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
import sys, io, os
import math
import bisect
import heapq
import string
import re
from decimal import *
from collections import defaultdict,Counter,deque
input = sys.stdin.readline
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
def WRITE(out):
return print('\n'.join(map(str, out)))
def WS(out):
return print(' '.join(map(str, out)))
def WNS(out):
return print(''.join(map(str, out)))
def WSNOPRINT(out):
return ''.join(map(str, out))
'''
'''
def valid(g):
s = sum(g[0])
ok = True
ok &= sum(g[1]) == s
ok &= sum(g[2]) == s
ok &= g[0][0]+g[1][1]+g[2][2] == s
ok &= g[2][0]+g[1][1]+g[0][2] == s
ok &= g[0][0]+g[1][0]+g[2][0] == s
ok &= g[0][1]+g[1][1]+g[2][1] == s
ok &= g[0][2]+g[1][2]+g[2][2] == s
return ok
def solve():
grid = []
for _ in range(3):
grid.append(LII())
d = {}
base = ord('a')
for i in range(9):
d[chr(base+i)] = grid[i//3][i%3]
for e in range(1, 10**5+1):
a = d['g']+d['h']-e
i = d['d']+d['f']-a
grid[0][0] = a
grid[1][1] = e
grid[2][2] = i
if valid(grid):
break
for row in grid:
WS(row)
def main():
solve()
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You're given a list of *n* strings *a*1,<=*a*2,<=...,<=*a**n*. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.
Given the list of strings, output the lexicographically smallest concatenation.
|
```python
from functools import cmp_to_key
def cmp(x,y):
if x+y>y+x:
return 1
else:
return -1
a=[]
n=int(input())
for i in range(n):
a.append(input())
ans=""
for s in sorted(a,key=cmp_to_key(cmp)):
ans+=s
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ohana Matsumae is trying to clean a room, which is divided up into an *n* by *n* grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.
Return the maximum number of rows that she can make completely clean.
|
```python
n = int(input())
d = dict()
for i in range(n):
a = input()
if a not in d:
d[a] = 1
else:
d[a] += 1
m = 0
for elem in d:
m = max(m, d[elem])
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility.
Initially Sam has a list with a single element *n*. Then he has to perform certain operations on this list. In each operation Sam must remove any element *x*, such that *x*<=><=1, from the list and insert at the same position , , sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.
Now the masters want the total number of 1s in the range *l* to *r* (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?
|
```python
def code(n):
if n==1 or n==0:
mn[0]+=1
if n==1 and mn[0]>=l and mn[0]<=r:
cnt[0]+=1
return
if mn[0]<=r:
code(n//2)
code(n%2)
code(n//2)
cnt=[0]
mn=[0]
n,l,r=[int(x) for x in input().split()]
code(n)
print(*cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer *t* Т-prime, if *t* has exactly three distinct positive divisors.
You are given an array of *n* positive integers. For each of them determine whether it is Т-prime or not.
|
```python
import math
def sieve_of_eratosthenes(limit):
is_prime = [True] * (limit + 1)
primes = []
for i in range(2, limit + 1):
if is_prime[i]:
primes.append(i)
for j in range(i * i, limit + 1, i):
is_prime[j] = False
return primes
a = sieve_of_eratosthenes(10**6)
b = int(input())
c = list(map(int, input().split()))
for t in c:
if math.sqrt(t).is_integer() and int(math.sqrt(t)) in a:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.
The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
|
```python
l = input()
l = [int(i) for i in l.split()]
t = input()
t = [int(i) for i in t.split()]
f,g = [],[]
for i in range(0,len(l) , 2):
f.append((l[i] , l[i+1]))
g.append((t[i] , t[i+1]))
side = (l[0] - l[2])**2 + (l[1]-l[3])**2
side = int(side**0.5)
y0 = l[1]
x0 = l[0]
if (l[0] , l[1]+side) in f :
y1 = l[1]+side
if (l[0]+side , l[1]) in f:
x1 = l[0]+side
else:
x1 = l[0]-side
else:
y1 = l[1] - side
if (l[0]+side , l[1]) in f:
x1 = l[0]+side
else:
x1 = l[0]-side
u= 0
for i in g :
if i[0]>=min(x0 , x1) and i[0]<=max(x0 , x1) and i[1]>=min(y0 , y1) and i[1]<=max(y0 , y1):
u=1
break
if u==0 :
for i in f :
for j in range(4):
if i[0]>=min(g[j][0] , g[(j+1)%4][0]) and i[0]<=max(g[j][0] , g[(j+1)%4][0]) and i[1]>=min(g[j][1] , g[(j+1)%4][1]) and i[1]<=max(g[j][1] , g[(j+1)%4][1]):
slope = (g[j][1] - g[(j+1)%4][1]) / (g[j][0] - g[(j+1)%4][0])
b = g[j][1] - (g[j][0]*slope)
if i[1]==(i[0]*slope + b):
u = 1
break
if u==1:
break
if u==1:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into *n* teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly *k* times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
|
```python
n,k=list(map(int,input().split()))
G=[]
_F=False
for i in range (1,n+1):
z=1
g=0
while g<k and z<n+1:
if [z,i] not in G and z!=i:
G=G+[[i,z]]
g+=1
z+=1
if g<k: _F=True
if not _F:
for i in range(len(G)): print(str(G[i][0])+' '+str(G[i][1]))
else: print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([[email protected]](/cdn-cgi/l/email-protection)).
It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots.
You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result.
Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.
|
```python
t = input()
k = len(t) - 3
t = t[0] + t[1: k].replace('dot', '.') + t[k: ]
k = t.find('at', 1)
print(t[:k] + '@' + t[k + 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
#"is it rated?" is most asked question on codeforces.
n=int(input())
sum_i=0
sum_j=0
sum_k=0
for i in range(n):
l1=list(map(int,input().split()))
sum_i+=l1[0]
sum_j+=l1[1]
sum_k+=l1[2]
if sum_i==0 and sum_j==0 and sum_k==0:
print("YES")
else:
print("NO")
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.