source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.
Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.
Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.
|
```python
l,r,a=map(int,input().split())
if l>=r:
n=r*2
l-=n
if l>=a:
n+=(a*2)
else:
n+=(a//2)*2
else:
n=l*2
r-=n
if r>=a:
n+=(a*2)
else:
n+=(a//2)*2
print(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
|
```python
print("will do it")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
- There are *n* knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won — the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*.
Write the code that calculates for each knight, the name of the knight that beat him.
|
```python
def search(D,p,ln):
k = p+1
#print(k)
for i in range(ln):
if k>=D[i][0] and k<=D[i][1] and k != D[i][2]:
return(D[i][2])
return(0)
def main():
D = []
Result = []
L = list(map(int,input().split()))
ln = L[1]
for i in range(ln):
D.append(list(map(int,input().split())))
#print(D)
for i in range(L[0]):
print(str(search(D,i,ln)),end = " ")
#print(" ".join(map(lambda x:str(x) ,Result)))
exit()
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
|
```python
# LUOGU_RID: 112614184
s = str(input())
n = len(s)
print(26 * (n + 1) - n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.
Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.
Peter decided to tie his car to point *P* and now he is wondering what is the area of the region that will be cleared from snow. Help him.
|
```python
import functools
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def squared_distance(self, another_point):
return (self.x - another_point.x) ** 2 + (self.y - another_point.y) ** 2
class SnowBlower:
def solution(self):
first_line = input()
first_line = first_line.split(" ")
num_vertices = int(first_line[0])
origin = Point(int(first_line[1]), int(first_line[2]))
vertices = []
for _ in range(num_vertices):
point = input()
point = point.split(" ")
vertices.append(Point(int(point[0]), int(point[1])))
min_distance = float("inf")
max_distance = float("-inf")
for vertex in vertices:
squared_distance = origin.squared_distance(vertex)
min_distance = squared_distance if min_distance > squared_distance else min_distance
max_distance = squared_distance if squared_distance > max_distance else max_distance
pi = 3.14159265358
print(pi * (max_distance - min_distance))
if __name__ == "__main__":
snow_blower = SnowBlower()
snow_blower.solution()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
|
```python
s = input()
countQPassed = 0
countQNotPassed = len([x for x in s if x == 'Q'])
countRes = 0
for x in s:
if x == 'A':
countRes += countQPassed * countQNotPassed
elif x == 'Q':
countQPassed += 1
countQNotPassed -= 1
print(countRes)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a permutation *p* of length *n*. Remove one element from permutation to make the number of records the maximum possible.
We remind that in a sequence of numbers *a*1,<=*a*2,<=...,<=*a**k* the element *a**i* is a record if for every integer *j* (1<=≤<=*j*<=<<=*i*) the following holds: *a**j*<=<<=*a**i*.
|
```python
def find_max_records_to_remove(n, p):
records = []
max_records = 0
max_records_element = 0
for i in range(n):
if i == 0 or p[i] > p[i - 1]:
records.append(i)
for i in range(len(records)):
remove_element1 = p[records[i]]
remove_element2 = p[records[i] - 1] if records[i] > 0 else float('inf')
count_after_removal = max(records[i], n - records[i] - 1)
if count_after_removal > max_records:
max_records = count_after_removal
max_records_element = min(remove_element1, remove_element2)
return max(max_records_element, p[-1])
def main():
n = int(input())
p = list(map(int, input().split()))
max_records_element = find_max_records_to_remove(n, p)
print(max_records_element)
if __name__ == "__main__":
main()# 1690233908.4629285
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
|
```python
import re
in1 = int(input())
in2 = re.split("\\s", input())
test = {}
count = 0
for x in in2:
test[x] = count
count += 1
print(min(test, key=test.get))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the *N* attendees love to play a very risky game...
Every zombie gets a number *n**i* (1<=≤<=*n**i*<=≤<=*N*) written on his forehead. Although no zombie can see his own number, he can see the numbers written on the foreheads of all *N*<=-<=1 fellows. Note that not all numbers have to be unique (they can even all be the same). From this point on, no more communication between zombies is allowed. Observation is the only key to success. When the cuckoo clock strikes midnight, all attendees have to simultaneously guess the number on their own forehead. If at least one of them guesses his number correctly, all zombies survive and go home happily. On the other hand, if not a single attendee manages to guess his number correctly, all of them are doomed to die!
Zombies aren't very bright creatures though, and Heidi has to act fast if she does not want to jeopardize her life. She has one single option: by performing some quick surgery on the brain she managed to get from the chest, she has the ability to remotely reprogram the decision-making strategy of all attendees for their upcoming midnight game! Can you suggest a sound strategy to Heidi which, given the rules of the game, ensures that at least one attendee will guess his own number correctly, for any possible sequence of numbers on the foreheads?
Given a zombie's rank *R* and the *N*<=-<=1 numbers *n**i* on the other attendees' foreheads, your program will have to return the number that the zombie of rank *R* shall guess. Those answers define your strategy, and we will check if it is flawless or not.
|
```python
t = int(input())
for i in range(t):
n, r = map(int, input().split())
l = list(map(int, input().split()))
if r == 1:
s = sum(l) % n
if s == 0:
s = n
print(s)
else:
s = 2 * l[0] - r + 1 - sum(l)
s = s % n
if s == 0:
s = n
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
n = int(input())
for i in range(n):
x = input()
g = len(x)
if g <= 10:
print(st)
else:
print(x[0], g - 2, x[g - 1], sep="")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip.
You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
|
```python
a=list(map(int,input().split()))[:4]
s=str(input())
sum=0
for i in s:
if i =='1':
sum+=a[0]
elif i =='2':
sum+=a[1]
elif i=='3':
sum+=a[2]
elif i=='4':
sum+=a[3]
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
n = int(input())
a,b,c = 0,0,0
for i,j,k in [int(x) for x in input().split()]:
a += i
b+=j
c +=k
if a == 0 and b ==0 and c==0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array consisting of *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to *n* defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
|
```python
h=int(input())
l=[*map(int,input().split())]
d=[*map(int,input().split())]
o=2
for i in range(h):
for j in range(h):
l[d[j] - 1] = -1
sums=[]
x=0
y=0
for k in range(o):
while l[x]!=-1 :
y+=l[x]
x+=1
if x==h:
break
sums.append(y)
y=0
x+=1
if x>=h:
break
o+=1
print(max(sums))
if max(sums)==0:
exit(0)
sums=[]
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hands that shed innocent blood!
There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=<<=*i* and *j*<=≥<=*i*<=-<=*L**i*.
You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
|
```python
n=int(input())
a=list(map(int,input().split()))
b=0
if n==1:
print(1)
else:
ans=0
for i in range(n-1,-1,-1):
if b==0:
ans+=1
#print(b,'b',b-1,'b-1',a[i],'a[i]',i,'i')
b=max(b-1,a[i],0)
#print('b',b)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja and his friends went to a picnic. The guys had *n* soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.
Sereja knows that the *i*-th bottle is from brand *a**i*, besides, you can use it to open other bottles of brand *b**i*. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.
Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.
|
```python
x,y,c=0,0,0
for i in range(int(input())):
a,b=map(int, input().split())
if b-a==0: c+=1
print(c)
```
|
|
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(lambda x : int(x)%2 ,input().split()))
s=sum(l[:3])
x=-1
if s<=1:x=1
else:x=0
for i in range(n):
if l[i]==x:break
print(1+i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with *n* rows and *m* columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
|
```python
lis=input().split()
n,m=map(int,lis[:-1])
c=lis[-1]
ans=['0'*(m+2)]
l=[]
b={'0','.',c}
for i in range(n):
ans.append('0'+input()+'0')
ans.append('0'*(m+2))
for i in range(n):
for j in range(m):
if ans[i+1][j+1]==c:
l.append(ans[i+1][j])
l.append(ans[i+1][j+2])
l.append(ans[i][j+1])
l.append(ans[i+2][j+1])
print(len(set(l)-b))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game.
|
```python
input();s=0
for i in map(int,input().split()):
if i-s>15:break
else:s=i
print([s+15,90][(s+15)>90])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rectangles.
Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?
|
```python
a1,b1 = map(int,input().split())
a2,b2 = map(int,input().split())
a3,b3 = map(int,input().split())
n2 = [a2,b2]
n3 = [a3,b3]
l = []
for d2 in range(2):
for d3 in range(2):
l.append([n2[d2]+n3[d3],max(n2[d2-1],n3[d3-1])])
def c(l,a1,b1):
a = False
for i in l:
if a1 >= i[0] and b1 >= i[1]:
a = True
return a
z = c(l,a1,b1) or c(l,b1,a1)
print('YES' if z else 'NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of *s*.
|
```python
n = int(input())
s = input()
balance_indices = {0: -1}
balance = 0
max_length = 0
for i in range(n):
if s[i] == '0':
balance -= 1
else:
balance += 1
if balance in balance_indices:
max_length = max(max_length, i - balance_indices[balance])
else:
balance_indices[balance] = i
print(max_length)# 1691082864.9898152
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
```python
if __name__=='__main__':
s_arr = input()
n_arr = []
for i in s_arr:
n_arr.append(i)
# print(s_arr, n_arr)
ab = 0
ba = 0
for i in range(len(n_arr)-1):
c = n_arr[i]
# print(c)
if c == 'A' and n_arr[i+1] == 'B':
# print("ab case")
ab=1
n_arr[i]='x'
n_arr[i+1]='x'
elif c == 'B' and n_arr[i+1] == 'A':
# print("ba case")
ba=1
n_arr[i]='x'
n_arr[i+1]='x'
n_arr.append(c)
if ab == 1 and ba == 1:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Easter Rabbit laid *n* eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
- Each of the seven colors should be used to paint at least one egg. - Any four eggs lying sequentially should be painted different colors.
Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.
|
```python
n=int(input())
c="ROYGBIV"
if n%7:
m=n//7+1
c*=m
print(c[:n])
else:
m=n//7
print(c*m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend *i* the number of a friend who has given him a gift.
|
```python
#Presents
n=int(input())
arr=[int(i) for i in input().split()]
ans=[]
respuesta = ""
for i in range(n+1): ans.append(0)
for i in range(0,n): ans[arr[i]] = i+1
for i in range(1,len(ans)): respuesta+=str(ans[i])
print(respuesta)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
|
```python
n, m = map(int, input().split())
tv = list(map(int, input().split()))
tv.sort()
result = 0
for i in range(m):
result -= tv[i]
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
```python
n, arr = int(input()), [int(t) for t in input().split()]
ub = max(arr)
count, dp = [0] * (ub + 1), [0] * (ub + 1)
for i in arr: count[i] += i
dp[1], dp[2] = count[1], count[2]
for i in range(3, ub + 1):
dp[i] = count[i] + max(dp[i - 2], dp[i - 3])
print(max(dp[-1], dp[-2]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have *n* layers. The first layer is hate, second one is love, third one is hate and so on...
For example if *n*<==<=1, then his feeling is "I hate it" or if *n*<==<=2 it's "I hate that I love it", and if *n*<==<=3 it's "I hate that I love that I hate it" and so on.
Please help Dr. Banner.
|
```python
print(" that ".join(["I hate","I love"][i%2] for i in range(int(input()))),end=" it\n")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Masha and Grisha like studying sets of positive integers.
One day Grisha has written a set *A* containing *n* different integers *a**i* on a blackboard. Now he asks Masha to create a set *B* containing *n* different integers *b**j* such that all *n*2 integers that can be obtained by summing up *a**i* and *b**j* for all possible pairs of *i* and *j* are different.
Both Masha and Grisha don't like big numbers, so all numbers in *A* are from 1 to 106, and all numbers in *B* must also be in the same range.
Help Masha to create the set *B* that satisfies Grisha's requirement.
|
```python
def get_numbers(numbers):
result_numbers = []
tmp = []
for i in range(1, 10 ** 6):
if len(result_numbers) == len(numbers):
break
for elem in numbers:
summ = i + elem
#print(not (summ in tmp or i in result_numbers), i, result_numbers)
if not (summ in tmp or i in result_numbers):
tmp.extend([elem + i for elem in numbers])
tmp = list(set(tmp))
result_numbers.append(i)
if i == 10 ** 6 - 1:
return 'NO'
return '\nYES\n' + ' '.join([str(x) for x in result_numbers])
count_tasks = int(input())
result = ''
for i in range(count_tasks):
count = input()
numbers = [int(x) for x in input().split()]
result += get_numbers(numbers)
print(result[1:])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little penguin Polo adores strings. But most of all he adores strings of length *n*.
One day he wanted to find a string that meets the following conditions:
1. The string consists of *n* lowercase English letters (that is, the string's length equals *n*), exactly *k* of these letters are distinct. 1. No two neighbouring letters of a string coincide; that is, if we represent a string as *s*<==<=*s*1*s*2... *s**n*, then the following inequality holds, *s**i*<=≠<=*s**i*<=+<=1(1<=≤<=*i*<=<<=*n*). 1. Among all strings that meet points 1 and 2, the required string is lexicographically smallest.
Help him find such string or state that such string doesn't exist.
String *x*<==<=*x*1*x*2... *x**p* is lexicographically less than string *y*<==<=*y*1*y*2... *y**q*, if either *p*<=<<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or there is such number *r* (*r*<=<<=*p*,<=*r*<=<<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=<<=*y**r*<=+<=1. The characters of the strings are compared by their ASCII codes.
|
```python
n,k = map(int,input().split())
if n<k:
print(-1)
else:
L = [chr(ord('a') + 2 + i) for i in range(k)]
end = "".join(L)
s = 'ab'*((n-k)//2)
if (n-k)%2 == 0:
print(s + end)
else:
print(s + 'a' + end)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given the string *s* of length *n* and the numbers *p*,<=*q*. Split the string *s* to pieces of length *p* and *q*.
For example, the string "Hello" for *p*<==<=2, *q*<==<=3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".
Note it is allowed to split the string *s* to the strings only of length *p* or to the strings only of length *q* (see the second sample test).
|
```python
n, p, q = map(int, input().split())
s = str(input())
for i in range(101):
for j in range(101):
if p*i+q*j == n:
ans = []
for k in range(i):
ans.append(s[p*k:p*(k+1)])
for l in range(j):
ans.append(s[p*i+q*l:p*i+q*(l+1)])
print(len(ans))
for m in range(len(ans)):
print(ans[m])
exit()
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of *n* elements. Petya immediately decided to find there a segment of consecutive elements, such that the *xor* of all numbers from this segment was maximal possible. Help him with that.
The *xor* operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
|
```python
n = int(input())
array = input().split()
maximum = 0
possible_max = 0
for number in array:
possible_max = maximum ^ int(number)
if possible_max > maximum:
maximum = possible_max
if int(number) > maximum:
maximum = int(number)
print(maximum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a given sequence of integers *a*1,<=*a*2,<=...,<=*a**n*, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.
|
```python
n=int(input())
l=list(map(int, input().split()))[:n]
x=[]
x.append(l.count(1))
x.append(l.count(2))
x.append(l.count(3))
x.sort()
print(x[0]+x[1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
```python
n = int(input())
a = [int(x) - 1 for x in input().split()]
ans = 0
for i in range(n):
if a[i] == -1:
continue
ans ^= 1
x = i
while x != -1:
y = a[x]
a[x] = -1
x = y
if ans:
print("Um_nik")
else:
print("Petr")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theater stage is a rectangular field of size *n*<=×<=*m*. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
- there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
|
```python
n, m=map(int, input().split())
a=[list(map(int, input().split())) for _ in range(n)]
ans=p=0
def f(x):
global ans, p
if x==0:
ans+=p
else:
p=1
for i in range(n):
p=0
for j in range(m):
f(a[i][j])
p=0
for j in range(m-1, -1, -1):
f(a[i][j])
for i in range(m):
p=0
for j in range(n):
f(a[j][i])
p=0
for j in range(n-1, -1, -1):
f(a[j][i])
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasily has a deck of cards consisting of *n* cards. There is an integer on each of the cards, this integer is between 1 and 100<=000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.
You are to determine the total number of times Vasily takes the top card from the deck.
|
```python
n = int(input())
f = []
for i in range(n):
avg = int(input())
y=[avg,i+1]
f.append(y)
f.sort()
last = -1
ans = 0
numberContinueing = 0
for i in f:
if(i[1]>last):
last = i[1]
numberContinueing+=1
else:
ans+=n
n-=numberContinueing
numberContinueing=1
last = i[1]
print(ans+n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
|
```python
n,m,k=map(int,input().split())
p,matrix=0,[[0 for _ in range(m+2)]for _ in range(n+2)]
l=[[1,1],[-1,1],[1,-1],[-1,-1]]
for q in range(1,1+k):
i,j=map(int,input().split())
matrix[i][j]=1
if sum([matrix[i][j],matrix[i+p[0]][j],matrix[i][j+p[1]],matrix[i+p[0]][j+p[1]]]==[1,1,1,1]for p in l)!=0:
p=q
break
print(p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
|
```python
l=list(map(int,list(input())))
c=[]
t=len(l)
for x in range(9):
s=''
for x in range(t):
if l[x]>0:
l[x]-=1
s+='1'
else: s+='0'
c.append(int(s))
if c[-1]==0: c.pop();break
print(len(c))
print(*c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The input contains a single integer *a* (1<=≤<=*a*<=≤<=40).
Output a single string.
|
```python
a = int(input())
pr = ['Washington', 'Adams', 'Jefferson', 'Madison', 'Monroe', 'Quincy Adams', 'Jackson', 'Van Buren', 'Henry Harrison', 'Tyler', 'Polk', 'Taylor', 'Fillmore', 'Pierce', 'Buchanan', 'Lincoln', 'Johnson', 'S. Grant', 'B. Hayes', 'A. Garfield', 'A. Arthur', 'Cleveland', 'Harrison', 'Cleveland', 'McKinley', 'Roosevelt', 'H. Taft', 'Wilson', 'Harding', 'Coolidge', 'Hoover', 'D. Roosevelt', 'S Truman', 'D. Eisenhower', 'F. Kennedy', 'B. Johnson', 'M. Nixon', 'R. Ford', 'Carter', 'W. Reagan', 'Bush', 'J. Clinton']
print(pr[a-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)).
Max starts to type all the values from *a* to *b*. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.
For example if *a*<==<=1 and *b*<==<=3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.
|
```python
a,b=map(int,input().split())
count=0
dict={"0":6,"6":6,"9":6,"1":2,"2":5,"3":5,"4":4,"5":5,"7":3,"8":7}
for i in range(a,b+1):
i=str(i)
for j in range(len(str(i))):
count+=dict[i[j]]
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.
A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?
|
```python
k,n,s,p=map(int,input().split())
q=s
i=1
while q<n:
q=s
q*=i
i+=1
sheets_required_per_person=q
total_no_of_sheets=q*k
packs=1
while total_no_of_sheets>(p*packs*s):
packs+=1
print(packs)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.
Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть *n* точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке *x*1 километров вдоль улицы, второй — в точке *x*2 и так далее, *n*-й велопрокат находится в точке *x**n*. Школа Аркадия находится в точке *x*1 (то есть там же, где и первый велопрокат), а дом — в точке *x**n* (то есть там же, где и *n*-й велопрокат). Известно, что *x**i*<=<<=*x**i*<=+<=1 для всех 1<=≤<=*i*<=<<=*n*.
Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.
За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше *k* километров вдоль улицы.
Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.
|
```python
helper = 0
n = ''
k = ''
myList = []
firstData = input()
for i in firstData:
if i != ' ' and helper == 0:
n += i
elif i != ' ':
k += i
else:
helper += 1
n = int(n)
k = int(k)
helper = 0
helpStr = ''
secondData = input()
for i in secondData:
if i != ' ':
helper = 0
helpStr += i
elif i == ' ' and helper == 0:
myList.append(int(helpStr))
helpStr = ''
helper += 1
myList.append(int(helpStr))
index = 1
countBike = 0
while index < len(myList):
helpe = 0
helper = myList[index + helpe] - myList[index - 1]
while helper <= k:
helpe += 1
if index + helpe< len(myList):
helper = myList[index + helpe] - myList[index - 1]
else:
break
if helpe == 0 :
countBike = -1
break
else:
countBike += 1
index += helpe
print(countBike)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
You have a sequence of integers *a*1,<=*a*2,<=...,<=*a**n*. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
|
```python
n, val = int(input()), 0
for x, y in zip(sorted(int(x) for x in input().split()), range(1, n + 1)):
val += abs(x - y)
print(val)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
|
```python
a = input()
print(a[0].capitalize() + a[1:])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are *n* pages numbered by integers from 1 to *n*. Assume that somebody is on the *p*-th page now. The navigation will look like this:
When someone clicks the button "<<" he is redirected to page 1, and when someone clicks the button ">>" he is redirected to page *n*. Of course if someone clicks on a number, he is redirected to the corresponding page.
There are some conditions in the navigation:
- If page 1 is in the navigation, the button "<<" must not be printed. - If page *n* is in the navigation, the button ">>" must not be printed. - If the page number is smaller than 1 or greater than *n*, it must not be printed.
You can see some examples of the navigations. Make a program that prints the navigation.
|
```python
X = list(map(int, input().split()))
Pages = [str(i + 1) for i in range(X[0])]
Pages[X[1] - 1] = '(' + Pages[X[1] - 1] + ')'
if X[-1] <= X[1] - X[-1]:
print("<< ", end="")
print(*Pages[max(0, X[1] - X[-1] - 1):min(X[0], X[1] + X[-1])], end=" ")
if X[1] < X[0] - X[-1]:
print(">>")
# Caption: God bless you General Soleimani
# ---------Hard Revenge---------
# ****** Rest in Peace ******
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.
Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist.
|
```python
n=int(input())
price=[]
quility=[]
flag=True
for _ in range(n):
a,b=map(int,input().split())
price.append(a)
quility.append(b)
for i in range(n):
if price[i]<price[i-1] and quility[i]>quility[i-1]:
flag=True
break
else:
flag=False
print("Happy Alex") if flag==True else print("Poor Alex")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.
Right now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.
|
```python
A,B = map(int, input().split())
x,y,z = map(int, input().split())
A1 = 2*x + y - A
B1 = 3*z + y - B
final = 0
if A1 > 0:
final = final + A1
if B1 > 0:
final = final + B1
print(final)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
|
```python
n=int(input())
a=list(map(int,input().split()))
a.sort()
for i in range(n):
if math.sqrt(a[n-i-1])%1!=0:
print(a[n-1-i])
exit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.
|
```python
from collections import Counter
m,n=list(map(int,input().split()))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
res=[]
counter=Counter(a)
sortedKeys=sorted(counter.keys())
for num in b:
sum=0
for x in sortedKeys:
if x>num:
break
sum+=counter[x]
res.append(sum)
res=list(map(str,res))
print(" ".join(res))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
The problem is:
You are given a lucky number *n*. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of *n*?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
|
```python
from sys import stdin; inp = stdin.readline
from math import dist, ceil, floor, sqrt, log
def IA(): return list(map(int, inp().split()))
def FA(): return list(map(float, inp().split()))
def SA(): return inp().split()
def I(): return int(inp())
def F(): return float(inp())
def S(): return inp()
from itertools import permutations
def main():
n = I()
l = len(str(n))
s = list(str(n))
s = ['4']*l + ['7']*l
res = set()
for i in range(1, l+1):
p = permutations(s, i)
for r in p:
if len(r) == 1:
dig = int(r[0])
else:
y = [*r]
k = ''.join(y)
dig = int(k)
if dig not in res and dig <= n:
res.add(dig)
out = sorted(res)
return out.index(n)+1
if __name__ == '__main__':
print(main())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (*l* — left, *s* — straight, *r* — right) and a light *p* for a pedestrian crossing.
An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.
Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.
|
```python
a = [0] * 4
for i in range(4):
a[i] = list(map(int, input().split()))
if a[0][3] == 1:
if a[3][3] or a[1][0] or a[2][1] or a[0][0] or a[0][1] or a[0][2]:
print('YES')
else:
print('NO')
elif a[1][3] == 1:
if a[1][0] or a[1][1] or a[1][2] or a[0][2] or a[2][0] or a[3][1]:
print('YES')
else:
print('NO')
elif a[2][3] == 1:
if a[2][0] or a[2][1] or a[2][2] or a[0][1] or a[1][2] or a[3][0]:
print('YES')
else:
print('NO')
else:
if a[3][0] or a[3][1] or a[3][2] or a[0][0] or a[1][1] or a[2][2]:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For a positive integer *n* let's define a function *f*:
*f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n*
Your task is to calculate *f*(*n*) for a given integer *n*.
|
```python
n=int(input())
sum_e=0
sum_o=0
for i in range(1,n+1):
if i%2==0:
sum_e=sum_e+i
else:
sum_o=sum_o-i
sum_t=sum_e+sum_o
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. *n* best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. *n*·(*n*<=-<=1)<=/<=2 games were played during the tournament, and each participant had a match with each other participant.
The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «*x**i* *y**i*», where *x**i* and *y**i* are the numbers of participants. The first number in each pair is a winner (i.e. *x**i* is a winner and *y**i* is a loser). There is no draws.
Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value *p**j* — the speed of falling asleep. The person who has lower speed wins. Every person has its own value *p**j*, constant during the life.
It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.
|
```python
def solve():
n = int(input().strip())
v = [x for x in range(1, n + 1)]
count = [0 for x in range(1, n + 1)]
won = [0 for x in range(1, n + 1)]
for i in range(int(n * (n - 1) / 2) - 1):
a, b = map(int, input().split())
count[a - 1] += 1
count[b - 1] += 1
won[a - 1] += 1
last = []
for i in range(len(count)):
if count[i] == n - 2:
last.append(i + 1)
# print(last, won)
a_i = v.index(last[0])
b_i = v.index(last[1])
if won[a_i] > won[b_i]:
print(last[0], last[1])
else:
print(last[1], last[0])
# print(v)
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*).
|
```python
n,k=map(int,input().split())
m=[]
num=0
for i in range(0,n):
m=list(map(int,input().split()))
for i in range(0,len(m)):
if(a[i]>k):
num=num+1
break
print(num)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A bus moves along the coordinate line *Ox* from the point *x*<==<=0 to the point *x*<==<=*a*. After starting from the point *x*<==<=0, it reaches the point *x*<==<=*a*, immediately turns back and then moves to the point *x*<==<=0. After returning to the point *x*<==<=0 it immediately goes back to the point *x*<==<=*a* and so on. Thus, the bus moves from *x*<==<=0 to *x*<==<=*a* and back. Moving from the point *x*<==<=0 to *x*<==<=*a* or from the point *x*<==<=*a* to *x*<==<=0 is called a bus journey. In total, the bus must make *k* journeys.
The petrol tank of the bus can hold *b* liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.
There is a gas station in point *x*<==<=*f*. This point is between points *x*<==<=0 and *x*<==<=*a*. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain *b* liters of gasoline.
What is the minimum number of times the bus needs to refuel at the point *x*<==<=*f* to make *k* journeys? The first journey starts in the point *x*<==<=0.
|
```python
a,b,f,k=map(int,input().split())
petrol=b
ans=0
for i in range(k):
if petrol<0:
print(-1)
exit()
if i%2==0:
if petrol>=a:
petrol-=a
elif petrol>=f:
petrol=b-(a-f)
ans+=1
else:
ans+=1
petrol=b-f
if petrol>=a:
petrol-=a
elif petrol>=f:
petrol=b-a+f
ans+=1
else:
print(-1)
exit()
else:
if petrol>=a:
petrol-=a
elif petrol>=a-f:
petrol=b-(f)
ans+=1
else:
ans+=1
petrol=b-a+f
if petrol>=a:
petrol-=a
elif petrol>=f:
petrol=b-f
ans+=1
else:
print(-1)
exit()
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer *q*. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
|
```python
def factorize(n):
p = 2
r = []
while p * p <= n:
while n % p == 0:
r.append(p)
n //= p
p += 1
if n > 1:
r.append(n)
return r
q = int(input())
f = factorize(q)
if len(f) <= 1:
print(1)
print(0)
elif len(f) == 2:
print(2)
else:
print(1)
print(f[0] * f[1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
n = int(input())
answers=[]
for i in range(n):
accword = []
word = str(input()).strip()
if len(word) > 4:
for char in word:
accword.append(char)
new = accword[0]+str(len(word))+accword[-1]
answers.append(new)
else:
answers.append(word)
for i2 in answers:
print(i2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.
Suppose the graph *G* is given. Subset *A* of its vertices is called a vertex cover of this graph, if for each edge *uv* there is at least one endpoint of it in this set, i.e. or (or both).
Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.
They have agreed to give you their graph and you need to find two disjoint subsets of its vertices *A* and *B*, such that both *A* and *B* are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).
|
```python
flag = 0
n, e = [int(i) for i in input().split(" ")]
edges = []
for i in range(e):
k = [int(i) for i in input().split(" ")]
edges.append(k)
dictionary = {}
visited = [0] * (n+1)
def backtrack(ind, set_1, set_2):
if ind >= len(edges):
return [True, set_1, set_2]
u = edges[ind][0]
v = edges[ind][1]
if visited[u] == 1 and visited[v] == 1:
if u in set_1 and v in set_1:
return False
elif u in set_2 and v in set_2:
return False
else:
return backtrack(ind+1, set_1, set_2)
elif visited[u] == 0 and visited[v] == 0:
set_1.append(u)
set_2.append(v)
visited[u] = 1
visited[v] = 1
if backtrack(ind+1, set_1, set_2):
return [True, set_1, set_2]
else:
set_1.remove(u)
set_2.remove(v)
set_1.append(v)
set_2.append(u)
return backtrack(ind+1, set_1, set_2)
else:
if visited[u] == 1:
if u in set_1:
set_2.append(v)
else:
set_1.append(v)
visited[v] = 1
return backtrack(ind+1, set_1, set_2)
else:
if v in set_1:
set_2.append(u)
else:
set_1.append(u)
visited[u] = 1
return backtrack(ind+1, set_1, set_2)
r = backtrack(0, [], [])
k1 = r[1]
k2 = r[2]
# print(r)
if r is not False:
# print(r[1], r[2])
print(len(r[1]))
for i in range(len(k1)):
print(k1[i], end=" ")
print()
print(len(k2))
for i in range(len(k2)):
print(k2[i], end=" ")
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an equation:
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
|
```python
import math
a = float(input())
b = float(input())
c = float(input())
special = b**2 - 4*a*c
if special < 0:
print(0)
elif special == 0:
x = (-b)/(2*a)
print(1)
print(x)
elif special > 9999999999:
print(-1)
else:
x1 = float( (-b-math.sqrt(special))/(2*a) )
x2 = float( (-b+math.sqrt(special))/(2*a) )
print(2)
print(round(x1,5))
print(x2 + 0.00000)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
|
```python
n=list(map(int,list(input())))
ans=int(max(n))
print(ans)
s=""
while(ans):
for i in range(len(n)):
if(n[i]>=1):
s+="1"
n[i]-=1
else:
s+=str(n[i])
print(s,end=" ")
s=""
ans-=1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?
|
```python
a, b = map(int, input().split())
f = list(map(int, input().split()))
f = [f[i] + b for i in range(a)]
r = 0
for _ in range(a):
if f[_] <= 5:
r+=1
#print(*f)
print(r//3)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).
Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.
For each city calculate two values *min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city
|
```python
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from queue import Queue
import heapq
import math
from itertools import permutations, combinations, islice
n = int(stdin.readline())
a = [*map(int, stdin.readline().strip().split())]
for i in range(n):
prev = a[i-1]
next = a[i+1] if (i+i) <= n else a[0]
stdout.write(f"{min(abs(a[i]-prev), abs(a[i]-next))} {max(abs(a[i]-prev), abs(a[i]-next))}\n")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
|
```python
from typing import DefaultDict
letters = DefaultDict(lambda :0)
for i in range(3):
line = input()
f = line[0]
s = line[1]
l = line[2]
if s=='>':
letters[f]+=1
if s=='<':
letters[l]+=1
order = [None]*3
res = ''
for letter in 'ABC':
v = letters[letter]
if order[v] is not None:
res = 'Impossible'
break
else:
order[v]=letter
if res=='':
res = ''.join(order)
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mike is trying rock climbing but he is awful at it.
There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
|
```python
n = int(input())
arr = list(map(int,input().split()))
l = []
for i in range(1 , n-1):
x = arr.pop(i)
d = []
#print(x)
for j in range(len(arr) - 1):
d.append(arr[j+1] - arr[j])
#print(d)
l.append(max(d))
arr.append(x)
arr.sort()
print(min(l))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Consider the infinite sequence of integers: 1,<=1,<=2,<=1,<=2,<=3,<=1,<=2,<=3,<=4,<=1,<=2,<=3,<=4,<=5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).
Find the number on the *n*-th position of the sequence.
|
```python
n = int(input())
i, s = 1, 0
while s + i < n:
s += i
i += 1
print(n - s if n - s <= i else i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a 2<=×<=*n* maze.
Imagine a maze that looks like a 2<=×<=*n* rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move from an empty cell of the maze to any side-adjacent empty cell. The shortest path problem is formulated as follows. Given two free maze cells, you need to determine the minimum time required to go from one cell to the other.
Unfortunately, the developed algorithm works well for only one request for finding the shortest path, in practice such requests occur quite often. You, as the chief R2 programmer, are commissioned to optimize the algorithm to find the shortest path. Write a program that will effectively respond to multiple requests to find the shortest path in a 2<=×<=*n* maze.
|
```python
n, m = map(int, input().split())
s1 = input()
s1 = 'X' + s1
s2 = input()
s2 = 'X' + s2
blocks = []
groups = [0 for i in range(n)]
res = [0 for i in range(2 * n)]
group = 0
for i in range(n + 1):
el1 = s1[i]
el2 = s2[i]
if el1 == el2 == 'X':
blocks.append(3)
elif el1 == 'X':
blocks.append(1)
elif el2 == 'X':
blocks.append(2)
else:
blocks.append(0)
for i in range(1, n + 1):
if blocks[i] == 3:
continue
if blocks[i - 1] == 3 or blocks[i - 1] + blocks[i] == 3:
group += 1
groups[i - 1] = group
if s1[i] != 'X':
res[i - 1] = 0
if s2[i] != 'X':
res[n + i - 1] = 1
continue
groups[i - 1] = group
if blocks[i - 1] == 2:
if blocks[i] == 0:
res[i - 1] = res[i - 2] + 1
res[n + i - 1] = res[i - 1] + 1
else:
res[i - 1] = res[i - 2] + 1
elif blocks[i - 1] == 1:
if blocks[i] == 0:
res[n + i - 1] = res[n + i - 2] + 1
res[i - 1] = res[n + i - 1] + 1
else:
res[n + i - 1] = res[n + i - 2] + 1
else:
if blocks[i] == 1:
res[n + i - 1] = res[n + i - 2] + 1
elif blocks[i] == 2:
res[i - 1] = res[i - 2] + 1
else:
res[n + i - 1] = res[n + i - 2] + 1
res[i - 1] = res[i - 2] + 1
for i in range(m):
a, b = map(int, input().split())
a_ = a - 1
if a_ >= n:
a_ -= n
b_ = b - 1
if b_ >= n:
b_ -= n
if groups[a_] != groups[b_]:
print(-1)
else:
print(abs(res[a - 1] - res[b - 1]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.
Everybody knows that the World history encompasses exactly *n* events: the *i*-th event had continued from the year *a**i* to the year *b**i* inclusive (*a**i*<=<<=*b**i*). Polycarpus easily learned the dates when each of *n* events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event *j* includes an event *i* if *a**j*<=<<=*a**i* and *b**i*<=<<=*b**j*. Your task is simpler: find the number of events that are included in some other event.
|
```python
# Getting Problem-Data from Codeforces.
eventCount,pairs = int(input()),[]
for i in range(eventCount):
newPair = tuple(map(int,input().split(' ')))
pairs.append(newPair)
# Sorting Pairs by first componenet.
from operator import itemgetter
pairs.sort(key=itemgetter(0))
# Method to detemine if event-a contains event-b.
def isIncluded(a,b):
return a[0]<b[0] and b[1]<a[1]
# Method to deduce which of the two events is larger.
def maxEvent(a,b):
if a[1]-a[0] > b[1]-b[0]:
return a
else: return b
# Algorithm.
maxPrev,count = pairs[0],0
for j in range(1,eventCount):
if isIncluded(maxPrev,pairs[j]):
count = count+1
maxPrev = maxEvent(maxPrev,pairs[j])
# Solution.
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if *n*<==<=3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
|
```python
import random
a = input()
a = int(a)
t1 = input()
t2 = input()
mor = 0
s = []
n = []
for i in range(0,a):
s.append(int(t1[i]))
n.append(int(t2[i]))
n.sort()
t = 1
for i in range(0,a):
t = t * (a - i)
mor = a * 2
sher = 0
for i in range (0,t * 2):
random.shuffle(n)
test1 = 0
test2 = 0
for i in range(0,a):
if n[i] == s[i]:
continue
if n[i] < s[i]:
test1 += 1
if n[i] > s[i]:
test2 += 1
if test1 < mor:
mor = test1
if test2 > sher:
sher = test2
print (mor)
print (sher)
```
|
|
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
import math
k = {'s':'Sheldon' , 'l' : 'Leonard' , 'p' :'Penny' , 'r' : "Rajesh" , 'h' :'Howard'}
h = ""
st = "slprh"
g = int(input())
h = int(math.log(g/5 + 1 , 2))
su = 5*(2**h - 1)
diff = g - su
p = 2**h
ind = math.ceil(diff/p)
print( k[st[ind-1]])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* boys and *m* girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to *n*<=+<=*m*. Then the number of integers *i* (1<=≤<=*i*<=<<=*n*<=+<=*m*) such that positions with indexes *i* and *i*<=+<=1 contain children of different genders (position *i* has a girl and position *i*<=+<=1 has a boy or vice versa) must be as large as possible.
Help the children and tell them how to form the line.
|
```python
nm=input().split()
n=int(nm[0])
m=int(nm[1])
output=[]
if n>=m:
i=0
while(i<m):
output.append('B')
output.append('G')
i+=1
j=0
while(j<n-m):
output.append('B')
j+=1
elif m>n:
i=0
while(i<n):
output.append('G')
output.append('B')
i+=1
j=0
while(j<m-n):
output.append('G')
j+=1
output="".join(output)
print(output)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
|
```python
# Problem: http://codeforces.com/contest/731/problem/A
# Time: ms
# Space: KB
# String -> int
# returns minimum no. of rotations of the wheel (either c.w. or a.c.w starting from a) needed to print the given string
# stub
# def countSteps(string):
# return 0
# unit tests
# def test():
# assert countSteps("zeus") == 18
# assert countSteps("map") == 35
# assert countSteps("ares") == 34
# solution
def countSteps(string):
wheel = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
currentIndex = 0
steps = 0
for letter in string:
newIndex = wheel.index(letter)
dist = abs(currentIndex - newIndex)
if dist < 13:
steps += dist
else:
steps += 26 - dist
currentIndex = newIndex
return steps
# main
if __name__ == "__main__":
# test()
string = input()
print(countSteps(string))
```
|
|
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
n = int(input())
footprints = list(input())
start = 0
ending = 0
if 'R' in footprints:
for i in range(n):
if footprints[i] == 'R' and footprints[i - 1] == '.':
start = i + 1
if footprints[i] == 'R' and footprints[i + 1] == '.':
ending = i + 2
elif footprints[i] == 'R' and footprints[i + 1] == 'L':
ending = i + 1
else:
for i in range(n):
if footprints[i] == 'L' and footprints[i - 1] == '.':
ending = i
if footprints[i] == 'L' and footprints[i + 1] == '.':
start = i + 1
print(start, ending)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.
|
```python
n=int(input())
l=list(map(int,input().split()))
ones=l.count(1)
twos=l.count(2)
if ones==0:
print(0)
else:
res=0
if ones>=twos:
res=twos
ones-=twos
res+=(ones//3)
else:
res+=ones
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with.
Nicholas has *n* sticks whose lengths equal *a*1,<=*a*2,<=... *a**n*. Nicholas does not want to break the sticks or glue them together. To make a *h*<=×<=*w*-sized frame, he needs two sticks whose lengths equal *h* and two sticks whose lengths equal *w*. Specifically, to make a square frame (when *h*<==<=*w*), he needs four sticks of the same length.
Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
|
```python
n = int(input())
A = list(map(int, input().split()))
from collections import Counter
C = Counter(A)
cnt = 0
for k, v in C.items():
cnt += v//2
print(cnt//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
|
```python
from collections import defaultdict
n, m = map(int, input().split())
amigos = defaultdict(set)
for _ in range(m):
c, d = map(int, input().split())
amigos[c].add(d)
amigos[d].add(c)
is_reasonable = all(amigos[i].intersection(amigos[j]) for i in amigos for j in amigos[i] if i != j)
print("YES" if is_reasonable else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
|
```python
n=Int(input())
r=input()
c=0
for i in range(0,n-1):
if r[i]==r[i+1]:
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her *t* queries, each of one of the following type:
1. <=+<= *a**i* — add non-negative integer *a**i* to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer. 1. <=-<= *a**i* — delete a single occurrence of non-negative integer *a**i* from the multiset. It's guaranteed, that there is at least one *a**i* in the multiset. 1. ? *s* — count the number of integers in the multiset (with repetitions) that match some pattern *s* consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer *x* matches the pattern *s*, if the parity of the *i*-th from the right digit in decimal notation matches the *i*-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is *s*<==<=010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
|
```python
cnt = [0]*262200
trans = str.maketrans('0123456789', '0101010101')
t = int(input())
for _ in range(t):
o, a = input().split()
if o == '+':
cnt[int(a.translate(trans), 2)] += 1
elif o == '-':
cnt[int(a.translate(trans), 2)] -= 1
else:
print(cnt[int(a, 2)])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.
|
```python
n = int(input())
p = list(map(int, input().split()))
amount_of_ones = 0
amount_of_twos = 0
for i in range(n):
if p[i] == 1:
amount_of_ones += 1
if p[i] == 2:
amount_of_twos += 1
x = min(amount_of_twos, amount_of_ones)
if amount_of_ones/3 > amount_of_twos:
print (amount_of_ones - (amount_of_ones%3) // 3)
else:
print (x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
High school student Vasya got a string of length *n* as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than *k* characters of the original string. What is the maximum beauty of the string he can achieve?
|
```python
n,k=map(int,input().split())
s=input()
i,j=0,0
rm=k
ans=0
while i<n and j<n:
while j<n and (rm>0 or s[j]=='a'):
if s[j]=='b': rm-=1
j+=1
ans=max(ans,j-i)
if j==n: break
while s[i]=='a':
i+=1
i+=1
rm+=1
i,j=0,0
rm=k
while i<n and j<n:
while j<n and (rm>0 or s[j]=='b'):
if s[j]=='a': rm-=1
j+=1
ans=max(ans,j-i)
if j==n: break
while s[i]=='b':
i+=1
i+=1
rm+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
|
```python
s = list(map(int, input().split('+')))
s.sort()
print(*s, sep='+')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.
Output the probability that SmallR will win the match.
|
```python
from sys import stdin,stdout
ii1 = lambda: int(stdin.readline().strip())
is1 = lambda: stdin.readline().strip()
iia = lambda: list(map(int, stdin.readline().strip().split()))
isa = lambda: stdin.readline().strip().split()
mod = 1000000007
a, b, c, d = iia()
p = a / b
q = (1 - c / d) * (1 - a / b)
print(p / (1 - q))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
|
```python
a = int(input())
s = list(map(int,input().split()))
s1 = sum(s)
c = 0
for i in range(1,5+1):
if (s1+i)%(a+1)!=1:
c+=1
print(c)
```
|
|
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
a= input()
if "0000000" in a or "1111111" in a:
print("yes")
else:
print("no")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*?
|
```python
for _ in range(int(input())):
a = int(input())
print("YES" if (360/(180-a)).is_integer() else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are *n* days, at the *i*-th day, Arya finds *a**i* candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran *k* candies before the end of the *n*-th day. Formally, you need to output the minimum day index to the end of which *k* candies will be given out (the days are indexed from 1 to *n*).
Print -1 if she can't give him *k* candies during *n* given days.
|
```python
import math
alph="abcdefghijklmnopqrstuvwxyz"
#-----------------------------------
n,k=map(int,input().split())
a=list(map(int,input().split()))
p=0
for i in range(n):
if a[i]>8:
k-=8
p+=a[i]-8
else:
k-=a[i]
if p!=0:
k-=min(p,8-a[i])
p-=min(p,8-a[i])
if k<=0:
print(i+1)
break
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2<=×<=2 square, such that from the four letters of this square you can make word "face".
You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.
|
```python
n, m = map(int, input().split())
a = []
ans = 0
for i in range(n):
a.append(input())
for i in range(1, n):
for j in range(1, m):
c = [a[i][j], a[i - 1][j], a[i - 1][j - 1], a[i][j - 1]]
if 'f' in c and 'a' in c and 'c' in c and 'e' in c:
ans += 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
|
```python
from numpy import array
a = array([int] * 1000)
def solve():
n = int(input())
h = int(input())
k = 0
for i in range(n):
a[i] = int(input())
if a[i] <= h:
k = k + 1
else:
k = k + 2
print(k)
'''def main():
t = int(input())
i = 0
while i < t:
solve()
i = i + 1
main()
'''
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
|
```python
M_N,S_A = map(int, input().split())
for _R in range(M_N):
if any(x in 'CMY' for x in input().split())
print('#Color')
break
else: print('#Black&White')
```
|
|
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()
k=0
for i in s:
if i.upper()== i:
k+=1
if k> len(s)//2:
print(s.upper())
else:
print(s.lower())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.
You are given a string *s* consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.
A substring of a string is a nonempty sequence of consecutive characters.
For example if string *s* is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
```python
# A number is divisible by 4 when its last two digits are divisible by 4
s= input()
ans = 0
# First find sigle substring divisible by 4
for i in s:
if int(i)%4 == 0:
ans+=1
n = len(s)
# when two digits form a number divisible by 4 then increase the answer by the index of the right one
for i in range(0,n-1):
print(s[i:i+2])
if int(s[i:i+2])%4 == 0:
ans+=i+1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after *k* minutes after turning on.
During cooking, Julia goes to the kitchen every *d* minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.
It is known that the chicken needs *t* minutes to be cooked on the stove, if it is turned on, and 2*t* minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.
|
```python
"""Problem C - Save Energy!.
http://codeforces.com/contest/937/problem/C
Julia is going to cook a chicken in the kitchen of her dormitory. To save
energy, the stove in the kitchen automatically turns off after k minutes after
turning on.
During cooking, Julia goes to the kitchen every d minutes and turns on the
stove if it is turned off. While the cooker is turned off, it stays warm. The
stove switches on and off instantly.
It is known that the chicken needs t minutes to be cooked on the stove, if it
is turned on, and 2t minutes, if it is turned off. You need to find out, how
much time will Julia have to cook the chicken, if it is considered that the
chicken is cooked evenly, with constant speed when the stove is turned on and
at a constant speed when it is turned off.
Input:
The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).
Output:
Print a single number, the total time of cooking in minutes. The relative or
absolute error must not exceed 10 - 9.
Namely, let's assume that your answer is x and the answer of the jury is y.
The checker program will consider your answer correct if .
"""
import logging
import math
fmt = '%(levelname)s - %(name)s (line:%(lineno)s) - %(message)s'
formatter = logging.Formatter(fmt)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger = logging.getLogger('sae')
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
def solve(k, d, t):
if k % 2 == 0:
r = 0
elif k > d:
r = d - k % d
elif k < d:
r = d % k
n = t / (k + 0.5 * r)
cooked = math.floor(n) * (k + 0.5 * r)
diff = t - cooked
time = math.floor(n) * (k + r)
if diff > 0:
time += diff
return time
def main():
k, d, t = [int(x) for x in input().strip().split()]
result = solve(k, d, t)
print(result)
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not nice.
Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?
|
```python
s = input()
n = len(s)
if n < 26:
print(-1)
exit()
characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
substring = []
for i in range(n):
while len(substring) == 26 or (s[i] in substring and s[i] != "?"):
substring.pop(0)
substring.append(s[i])
if len(substring) == 26:
unique_chars = set(substring) - {"?"}
missing_chars = characters - unique_chars
if len(missing_chars) == 26 - len(unique_chars):
new = [char if char != "?" else missing_chars.pop() for char in substring]
replaced_s = s.replace("?", "A")
print(replaced_s[: i - 25] + "".join(new) + replaced_s[i + 1 :])
exit()
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function *f*, which is defined as follows:
In the above formula, 1<=≤<=*l*<=<<=*r*<=≤<=*n* must hold, where *n* is the size of the Main Uzhlyandian Array *a*, and |*x*| means absolute value of *x*. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of *f* among all possible values of *l* and *r* for the given array *a*.
|
```python
n = int(input())
A =list(map(int, input().split()))
B = []
for i in range(n-1):
B.append(abs(A[i]-A[i+1]))
dpmin = [0] * n
dpmax = [0] * n
for i in range(n-2,-1,-1):
dpmax[i] = B[i]
dpmin[i] = B[i]
dpmin[i] = min(dpmin[i], B[i] - dpmax[i+1])
dpmax[i] = max(dpmax[i], B[i] - dpmin[i+1])
print(dpmax[0])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
m,n=map(int,input().split())
area=m*n
if area<2:
print(0)
else:
print(area//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time *x* (in seconds), so he asked you to tell him if it's gonna bark at that time.
|
```python
a,b,c=map(int,input().split())
d=c//b
if a==c or (d>0 and (c%b==a or c%b==a+1)) :print("YES")
else:print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.
As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (*n*<=-<=1) friends. Determine if Sereja's friends can play the game so that nobody loses.
|
```python
n, s = map(int, input().split())
a = list(map(int, input().split()))
a.remove(max(a))
ans = sum(a) > s
print("NO" if ans else "YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ann has recently started commuting by subway. We know that a one ride subway ticket costs *a* rubles. Besides, Ann found out that she can buy a special ticket for *m* rides (she can buy it several times). It costs *b* rubles. Ann did the math; she will need to use subway *n* times. Help Ann, tell her what is the minimum sum of money she will have to spend to make *n* rides?
|
```python
l=list(map(int,input().split()))
n=l[0]
m=l[1]
a=l[2]
b=l[3]
total_cost=0
while(n>0):
if(n-m>=0):
current_cost=min(m*a,b)
total_cost+=current_cost
n=n-m
elif(n-1>=0):
current_cost=a;
total_cost+=current_cost
n=n-1
print(total_cost)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.
Consider positive integers *a*, *a*<=+<=1, ..., *b* (*a*<=≤<=*b*). You want to find the minimum integer *l* (1<=≤<=*l*<=≤<=*b*<=-<=*a*<=+<=1) such that for any integer *x* (*a*<=≤<=*x*<=≤<=*b*<=-<=*l*<=+<=1) among *l* integers *x*, *x*<=+<=1, ..., *x*<=+<=*l*<=-<=1 there are at least *k* prime numbers.
Find and print the required minimum *l*. If no value *l* meets the described limitations, print -1.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 6 23:37:57 2021
@author: LENOVO
"""
#método que crea un array (prim) desde 0 hasta b, dónde prim[i]=1 solo si i es un número primo
def PrimeGen(b):
prim=[1]*(b+1)
prim[0]=prim[1]=0
for i in range(2,b+1,1):
for j in range(i*i,b+1,i):
prim[j]=0
return prim
s = input() #s = "a b k"
l=a=b=k=y=x=0 #a,b,k,l representan lo mismo que en el enunciado del problema,
#x es el indice de s donde comienza el valor a asignar,
#y representa cuál de los 3 valores estamos asignando
for i in range(len(s)):
if s[i]==' ':
y+=1
if y==1:
a=int(s[x:i])
elif y==2:
b=int(s[x:i])
x=i+1
elif i==(len(s)-1):
k=int(s[x:])
prim = PrimeGen(b)
nop=[0]*(b+1) #number_of_primes.
for i in range(a,b+1):
nop[i]= nop[i-1]+prim[i]; #nop[i] representa cuántos números primos hay desde a hasta i
if nop[b] < k: # si desde a hasta b no hay k numeros primos, devolvemos -1
print(-1)
else: #buscamos l tal que cumpla con las condiciones establecidas en el problema
l=1
for x in range(a-1,b-l+1):
while (l>=1 and l<=b-a+1 and x+l<=b and (nop[x+l]-nop[x])<k ):
l+=1
print(l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to *y*. Some of them (more precise, from 2 to *p*) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch *x* can jump to branches .
Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.
In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.
|
```python
import math
def printDivisors(n):
i = 2
s = set()
while i <= math.sqrt(n):
if (n % i == 0):
if (n // i == i):
s.add(i)
else:
s.add(i)
s.add(n//i)
i = i + 1
return s
p,y = map(int,input().split())
m = -1
j = y
while(j > p):
e = printDivisors(j)
f = 0
for i in e:
if i <= p:
f = 1
break
if f == 0:
m = j
break
j = j-1
print(m)
```
|
|
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
n, k = input().split()
k = int(k)
n = int(n)
a = n
b = 10**k
if n%10 == 5 or n%10 == 0:
while a%2 == 0 and b%2 == 0:
a = a//2
b = b//2
while a%5 == 0 and b%5 == 0:
a = a//5
b = b//5
a = n*b
else:
a = a*(10**k)
print (a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.
On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.
Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.
|
```python
a = input()
n = len(a)
ans = []
cnt = 1
m = 1 #for max
ans.append(1)
for i in range(1,n):
if(a[i] == a[0]):
cnt+=1
else:
cnt -=1
ans.append(cnt)
m = max(m,cnt)
# print(ans)
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.
Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square.
Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.
|
```python
#!/usr/bin/env python3
number_of_mines = int(input())
x_coords = []
y_coords = []
for _ in range(number_of_mines):
x, y = (int(value) for value in input().split())
x_coords.append(x)
y_coords.append(y)
print(max(abs(max(x_coords) - min(x_coords)), abs(max(y_coords) - min(y_coords))) ** 2)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.