source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Anton likes to play chess, and so does his friend Danik.
Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
|
```python
count=int(input())
wins=input()
A=0
D=0
for i in wins:
if i=='A':
A+=1
else:
D+=1
if A>D:
print('Anton')
elif A<D:
print('Danik')
else:
print('Friendship')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fafa owns a company that works on huge projects. There are *n* employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best *l* employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees *n*, find in how many ways Fafa could choose the number of team leaders *l* in such a way that it is possible to divide employees between them evenly.
|
```python
n=int(input())
nb=bin(n).replace("0b","")
lnb=len(nb)
x=lnb-1
print(x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
|
```python
n, b, d = map(int, input().split())
arr = list(map(int, input().split()))
sum_, count = 0, 0
for i in range(n):
if arr[i] < b:
sum_ += arr[i]
if sum_ >= d:
count += 1
sum_ = 0
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.
With that begins the watch of Jon Snow. He is assigned the task to support the stewards.
This time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.
Can you find how many stewards will Jon support?
|
```python
n = int(input())
stewards = list(map(int, input().split()))
count = 0
sm = 10000000000
lg = -10000000000
for i in stewards:
sm = min(i, sm)
lg = max(i, lg)
for i in stewards:
if i > sm and i < lg:
count += 1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.
Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".
You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
|
```python
characters = int(input())
string = input()
removals = 0
for i in range(0, characters - 2):
if string[i] == 'x' and string[i + 1] == 'x' and string[i + 2] == 'x':
removals = removals + 1
print(removals)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences.
Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?
|
```python
n = int(input())
a = list(map(int,input().split()))
c = 0
for i in range(n):
c += abs(a[i])
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
|
```python
n=int(input())
x=list()
y=list()
for i in range(n):
a,b=map(int,input().split())
x.append(a)
y.append(b)
x0=x.count(0)
x1=n-x0
y0=y.count(0)
y1=n-y0
# if(x0>x1 and y1>y0):
# print(x1+y0)
# elif(x0>x1 and y1>y0):
# print(x0)
if x0+y1>y0+x1:
print(x1+y0)
else:
print(y0+x1)
```
|
|
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()
ctru,ctrl=0,0
for i in s:
if i.islower():ctrl+=1
else:ctru+=1
if ctrl>ctru:s=s.lower()
else: s=s.upper()
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than *k* millimeters.
The library has *n* volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is *h**i*. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.
|
```python
from collections import deque
n,k = [int(i) for i in input().split()]
h = [int(i) for i in input().split()]
r = []
d = deque()
cnt = 0
for i in range(len(h)):
d.append(h[i])
if max(d) - min(d) > k:
temp = len(d)-1
if temp > cnt:
cnt = temp
r = []
r.append((i-len(d)+2,i))
elif temp == cnt:
r.append((i-len(d)+2,i))
while max(d) - min(d) > k:
d.popleft()
temp = len(d)
if cnt == 0:
r.append((len(h)-len(d)+1,len(h)))
elif temp == cnt:
r.append((len(h)-len(d)+1,len(h)))
elif temp > cnt:
r = []
r.append((len(h)-len(d)+1,len(h)))
print('{0} {1}'.format(r[0][1]-r[0][0]+1,len(r)))
for i in range(len(r)):
print('{0} {1}'.format(r[i][0],r[i][1]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
|
```python
n = input()
n = str(n)
a = n.replace("a",".")
b = n.replace("b",".")
c = n.replace("c",".")
d = n.replace("d",".")
e = n.replace("e",".")
f = n.replace("f",".")
g = n.replace("g",".")
h = n.replace("h",".")
i = n.replace("i",".")
j = n.replace("j",".")
k = n.replace("k",".")
l = n.replace("l",".")
m = n.replace("m",".")
n = n.replace("n",".")
o = n.replace("o",".")
p = n.replace("p",".")
q = n.replace("q",".")
r = n.replace("r",".")
s = n.replace("s",".")
t = n.replace("t",".")
u = n.replace("u",".")
v = n.replace("v",".")
w = n.replace("w",".")
x = n.replace("x",".")
y = n.replace("y",".")
z = n.replace("z",".")
ee = n.count(".")
print(ee)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time.
Order is important everywhere, so the painters' work is ordered by the following rules:
- Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=<<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
|
```python
import sys
import math
def fn(n,m,a):
if n==1:
t1=0
for i in range(m):
t1=t1+a[i][0]
print(t1,end=' ')
return 0
t=[0]*n
t[0]=a[0][0]
for i in range(1,n):
t[i] = a[0][i]+ t[i-1]
print(t[n-1],end=' ')
for i in range(1,m):
for j in range(n-1):
t[j] = t[j] + a[i][j]
if t[j+1]<t[j]:
t[j+1] = a[i][j+1]+ t[j]
else:
t[j+1] = t[j+1]+ a[i][j+1]
print(t[n-1],end=' ')
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = (data[1])
m = data[0]
a = [[0]*n for i in range(m)]
l= data[2:]
k=0
for i in range(m):
for j in range(n):
a[i][j] = l[k]
k=k+1
(fn(n,m,a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
|
```python
n = int(input())
string = str(input())
#str2 = ""
while string.find("ogo") > -1:
f = string.find("ogo")
end = f + 3
end2 = end + 2
while string[end:end2] == "go":
end += 2
end2 = end + 2
string = string[:f] + "***" + string[end:]
print(string)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A tourist hiked along the mountain range. The hike lasted for *n* days, during each day the tourist noted height above the sea level. On the *i*-th day height was equal to some integer *h**i*. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all *i*'s from 1 to *n*<=-<=1 the inequality |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1 holds.
At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1.
|
```python
N, M = map(int, input().split())
H = []
D = []
for i in range(M):
d, h = map(int, input().split())
H.append(h)
D.append(d)
res = max(max(H), H[M - 1] + N - D[M - 1])
for i in range(M - 1):
dest = D[i + 1] - D[i]
diff = abs(H[i + 1] - H[i])
if diff > dest:
res = float('inf')
break
else:
res = max(res, (dest - diff) // 2 + max(H[i + 1], H[i]))
if res == float('inf'):
print("IMPOSSIBLE")
else:
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, *mex*([4,<=33,<=0,<=1,<=1,<=5])<==<=2 and *mex*([1,<=2,<=3])<==<=0.
Vitya quickly understood all tasks of the teacher, but can you do the same?
You are given an array consisting of *n* non-negative integers, and *m* queries. Each query is characterized by one number *x* and consists of the following consecutive steps:
- Perform the bitwise addition operation modulo 2 (xor) of each array element with the number *x*. - Find mex of the resulting array.
Note that after each query the array changes.
|
```python
from sys import stdin, stdout
n,m = map(int,stdin.readline().rstrip().split())
a = set(map(int,stdin.readline().rstrip().split()))
q = 0
for _ in range(m):
q = q ^ int(stdin.readline().rstrip())
for i in range(n+1):
if q^i not in a:
print(i)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
|
```python
from collections import*
q=int(input())
lst=[]
for i in range(q):
h,m=map(int,input().split())
d=str(h)+str(m)
lst.append(d)
s=1
for i,x in Counter(lst).items():
if x>=2:
s+=1
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have *n* devices that you want to use simultaneously.
The *i*-th device uses *a**i* units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·*a**i* units of power. The *i*-th device currently has *b**i* units of power stored. All devices can store an arbitrary amount of power.
You have a single charger that can plug to any single device. The charger will add *p* units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·*p* units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.
You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
|
```python
from math import inf
n, p = [int(x) for x in input().split()]
l = []
for i in range(n):
a, b = [int(x) for x in input().split()]
l.append((a, b, b/a))
l.sort(key=lambda x: x[2])
asum = 0
bsum = 0
sumt = 0
for i in range(n):
a0, b0, _ = l[i]
c1 = inf if i == n-1 else l[i+1][2]
asum += a0
bsum += b0
dp = asum - p
if dp > 0:
t = bsum / dp
if t < c1:
print(t)
exit()
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*.
Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end.
Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened.
You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.
|
```python
ch=input()
x=len(ch)
a=0
i=0
while (a==0) and (i<x/2):
if ch[0:i+1]==ch[x-1-i:x]:
a=1
i+=1
t=ch[0:i]
c=len(t)
if (c>1):
if (a==1) and (t in ch[c:x-c]):
print(t)
else:
print("Just a legend")
else:
print("Just a legend")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).
Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from 1 to 4. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the *i*-th player is *a**i*, the attack skill is *b**i*.
Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.
We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.
The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.
|
```python
a=[int(k) for k in input().split()]
b=[int(k) for k in input().split()]
c=[int(k) for k in input().split()]
d=[int(k) for k in input().split()]
if (a[0]>c[1] and b[1]>d[0]) and (a[0]>d[1] and b[1]>c[0]):
print("Team 1")
elif (a[1]>c[0] and b[0]>d[1]) and (a[1]>d[0] and b[0]>c[1]):
print("Team 1")
elif ((c[1]>a[0] and d[0]>b[1]) or (d[1]>a[0] and c[0]>b[1])) and ((c[0]>a[1] and d[1]>b[0]) or (d[0]>a[1] and c[1]>b[0])):
print("Team 2")
else:
print("Draw")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
HQ9+ is a joke programming language which has only four one-character instructions:
- "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.
You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
|
```python
x = input()
instructions = "HQ9"
for char in x:
if char in instructions:
print("YES")
break
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In Ancient Berland there were *n* cities and *m* two-way roads of equal length. The cities are numbered with integers from 1 to *n* inclusively. According to an ancient superstition, if a traveller visits three cities *a**i*, *b**i*, *c**i* in row, without visiting other cities between them, a great disaster awaits him. Overall there are *k* such city triplets. Each triplet is ordered, which means that, for example, you are allowed to visit the cities in the following order: *a**i*, *c**i*, *b**i*. Vasya wants to get from the city 1 to the city *n* and not fulfil the superstition. Find out which minimal number of roads he should take. Also you are required to find one of his possible path routes.
|
```python
import sys
def find(b, road):
if b: find(pre[b][road], b)
print(road, end=' ')
_input = lambda:[*map(int, input().split())]
n, m, k = _input()
road_descs = [[]for i in range(n + 1)]
for i in range(m):
a, b = _input()
road_descs[a] += [b]
road_descs[b] += [a]
st = set()
for i in range(k): st.add(tuple(_input()))
pre = [[0] * (n + 1) for i in range(n + 1)]
tmp = [[100000000] * (n + 1)for i in range(n + 1)]
tmp[0][1] = 0
q = [(0, 1)]
while(q):
a, b = q.pop(0)
d = tmp[a][b]+1
for road in road_descs[b]:
if tmp[b][c] > d and (a, b, road) not in st:
q += [(b, road)]
tmp[b][road] = d
pre[b][road] = a
if road == n:
print(d)
find(b, road)
sys.exit(0)
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$.
Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list.
Mishka cannot solve a problem with difficulty greater than $k$. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by $1$. Mishka stops when he is unable to solve any problem from any end of the list.
How many problems can Mishka solve?
|
```python
n,m=map(int,input().split())
lst=list(map(int,input().split()))
vis=[0]*n
cnt=0
for i in range(n):
if lst[i]<=m:
cnt+=1
vis[i]=1
else:
break
for i in range(n-1,-1,-1):
if vis[i]==1 or lst[i]>m:
break
else:
cnt+=1
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it?
|
```python
s = int(input())
a = hex(s)[2:]
print(a.count('0') + a.count('4') + a.count('6') + a.count('8') * 2 + a.count('a') + a.count('9') + a.count('b') * 2 + a.count('d'))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer *n*?"
Petya knows only 5 integer types:
1) byte occupies 1 byte and allows you to store numbers from <=-<=128 to 127
2) short occupies 2 bytes and allows you to store numbers from <=-<=32768 to 32767
3) int occupies 4 bytes and allows you to store numbers from <=-<=2147483648 to 2147483647
4) long occupies 8 bytes and allows you to store numbers from <=-<=9223372036854775808 to 9223372036854775807
5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer *n*. Since BigInteger works much slower, Peter regards it last. Help him.
|
```python
item=input()
def LTE(a,b):
if(len(a)!=len(b)):
#smaller length always smaller
return len(a)<len(b)
#same len
for i in range(len(a)):
if(a[i]<b[i]):
return True
elif(a[i]>b[i]):
return False
#equal
return True
if(item[0]!='-'):
#positive
if LTE(item,'127'):
print("byte")
elif LTE(item,'32767'):
print("short")
elif LTE(item,'2147483647'):
print("int")
elif LTE(item,'9223372036854775807'):
print("long")
else:
print("BigInteger")
else:
#negative
item=item[1:]
if LTE(item,'128'):
print("byte")
elif LTE(item,'32768'):
print("short")
elif LTE(item,'2147483648'):
print("int")
elif LTE(item,'9223372036854775808'):
print("long")
else:
print("BigInteger")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY has a hash table with *p* buckets, numbered from 0 to *p*<=-<=1. He wants to insert *n* numbers, in the order they are given, into the hash table. For the *i*-th number *x**i*, DZY will put it into the bucket numbered *h*(*x**i*), where *h*(*x*) is the hash function. In this problem we will assume, that *h*(*x*)<==<=*x* *mod* *p*. Operation *a* *mod* *b* denotes taking a remainder after division *a* by *b*.
However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the *i*-th insertion, you should output *i*. If no conflict happens, just output -1.
|
```python
p, n = [int(_) for _ in input().split()]
d = {}
ans = -1
f = True
for i in range(n):
x = int(input())
if f and x%p in d:
ans = i+1
f = False
else:
d[x%p] = 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
m,n,a = map(int, input().split())
if(a>=m and a>=n):
print(1)
elif(a==1):
print(m*n)
elif(a>=m and a <n and a >= n and a<m):
print((m*n)//(a*a) +1)
else:
print((m*n)//(a*a) +2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
|
```python
input()
km = input().split(' ')
k,m = int(km[0]),int(km[1])
ast = input().split(' ')[:k]
bst = input().split(' ')[:m]
a,b = list(),list()
for s in ast:
a.append(s)
for s in bst:
b.append(s)
a.sort()
b.sort()
if (a[len(a)-1] < b[0]):
print('YES')
else :
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array *a*. Some element of this array *a**i* is a local minimum iff it is strictly less than both of its neighbours (that is, *a**i*<=<<=*a**i*<=-<=1 and *a**i*<=<<=*a**i*<=+<=1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, *a**i*<=><=*a**i*<=-<=1 and *a**i*<=><=*a**i*<=+<=1). Since *a*1 and *a**n* have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.
|
```python
n = int(input())
L = list(map(int, input().split()))
ans = 0
for i in range(1, n-1):
if L[i] > L[i-1] and L[i] > L[i+1]:
ans += 1
if L[i] < L[i-1] and L[i] < L[i+1]:
ans += 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree *i* is described by the esthetic appeal *a**i* — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
- The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; - the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; - and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
|
```python
from math import inf
def solve_task5():
n = int(input())
trees = tuple(map(int, input().split(" ")))
reversed_trees = tuple(reversed(trees))
max_rating = -1 * inf
begin_tree = 0
end_tree = 0
deleted_trees = []
for i in range(n):
l = trees[i]
r = n - 1 - reversed_trees.index(trees[l])
if l != r:
temp_sum = trees[l] + trees[r]
for j in range(l + 1, r):
if trees[j] > 0:
temp_sum += trees[j]
if temp_sum > max_rating:
max_rating, begin_tree, end_tree = temp_sum, l, r
deleted_trees = list(range(begin_tree)) + list(range(end_tree + 1, n))
for i in range(begin_tree + 1, end_tree):
if trees[i] < 0:
deleted_trees.append(trees[i])
deleted_trees.sort()
deleted_trees = [el + 1 for el in deleted_trees]
k = len(deleted_trees)
return " ".join([str(max_rating), str(k)]) + "\n" + " ".join([str(el) for el in deleted_trees])
result = solve_task5()
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
```python
n, m = map(int, input().split())
words = {}
for _ in range(m):
first_lang, second_lang = input().split()
words[first_lang] = second_lang
lecture = input().split()
recorded_lecture = [words[word] if len(words[word]) < len(word) else word for word in lecture]
recorded_lecture = ' '.join(recorded_lecture)
print(recorded_lecture)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
|
```python
# https://codeforces.com/problemset/problem/34/A
def func_sol(raw_data):
temp = list(map(int, raw_data.split('\n')[1].split(' ')))
a = sorted([(idx, t) for idx, t in enumerate(temp)], key=lambda e: e[1])
min_diff = abs(a[0][1] - a[1][1])
x, y = a[0][0], a[1][0]
for idx in range(-1, len(a) - 1):
temp_min_diff = abs(a[idx][1] - a[idx + 1][1])
if temp_min_diff < min_diff:
min_diff = temp_min_diff
x, y = a[idx][0], a[idx + 1][0]
return str(x + 1) + ' ' + str(y + 1)
def main():
try:
from codeforces.utilities import run_tests
run_tests(func_sol)
except ImportError:
from sys import stdin
print(func_sol(stdin.read()))
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him.
|
```python
def solve(x, y):
global k
if x < 0 or x > n - 1 or y < 0 or y > m - 1 or arr[x][y] != '.' or vis[x][y] == True:
return
vis[x][y] = True
solve(x + 1, y)
solve(x - 1, y)
solve(x, y + 1)
solve(x, y - 1)
if k > 0:
arr[x][y] = 'X'
k -= 1
n, m, k = [int(x) for x in input().split()]
arr = []
vis = [[False for i in range(m + 10)] for j in range(n + 10)]
for i in range(n):
s = input()
s.strip()
arr.append([x for x in s])
i, j = 0, 0
for i in range(n):
for j in range(m):
if arr[i][j] == '.':
break
if j < m:
break
solve(i, j)
for i in arr:
print(*i, sep='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
|
```python
def game(a, b, c, x, y):
while True:
x=a
y=b
z=c
while z > 0:
x, z = z, x % z
c-=x
z=c
if c<b:
return 0
y=b
while z > 0:
y, z = z, y % z
c-=y
z=c
if c<a:
return 1
a, b, c = map(int, input().split())
x = a
y = b
z=c
print(game(a, b, c, x, y))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a square painted on a piece of paper, the square's side equals *n* meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (*n*<=+<=1) meters, he draws a cross (see picture for clarifications).
John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?
|
```python
import math
def lcm(x,y):
return x * y // math.gcd(x,y)
n = int(input())
arr = list(map(int, input().split()))
for i in arr:
print((lcm(4*i, i+1) // (i+1)) + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
zscoder loves simple strings! A string *t* is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string *s*. He wants to change a minimum number of characters so that the string *s* becomes simple. Help him with this task!
|
```python
from sys import stdin,stdout
input = stdin.readline
print = stdout.write
s = list(input())
s.pop()
for i in range(1, len(s)):
if s[i] == s[i-1] and i != len(s)-1:
if s[i-1] != 'a' and s[i+1] != 'a':
s[i] = 'a'
elif s[i-1] != 'b' and s[i+1] != 'b':
s[i] = 'b'
elif s[i-1] != 'c' and s[i+1] != 'c':
s[i] = 'c'
if i == len(s)-1 and s[i] == s[i-1]:
if s[i-1] != 'a':
s[i] = 'a'
else:
s[i] = 'b'
print(''.join(s))
```
|
|
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()
h = 0
l = 0
for c in s:
if c.isupper():
h = h + 1
elif c.islower():
l = l +1
else:
pass
if h > l:
print(s.upper())
elif h < l:
print(s.lower())
elif h == l:
print(s.upper())
else:
pass
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array of *n* integer numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
|
```python
n=int(input())
a=[]
s=10
d=0
for i in input().split():
a.append(int(i))
m=min(a)
p0=a.index(m)
for i in range(p0+1,len(a)):
if a[i]==m:
d=i-p0
if d<s:
s=d
p0=i
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
- the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color.
Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.
|
```python
t = int(input())
ref = {"red":"Reality","purple":"Power","yellow":"Mind","orange":"Soul","green":"Time","blue":"Space"}
ans = []
for x in range(t):
stone = input().lower()
ans.append(stone)
mis = [b for a,b in ref.items() if a not in ans]
print (6-t)
for z in mis:
print (z)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. We all know that 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.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope with the task.
|
```python
inf = 1000000000
def solve():
n = int(input())
num4 = inf
num7 = inf
for num_4 in range(n // 4):
left = n - 4 * num_4
if left % 7 != 0:
continue
num_7 = left // 7
if num_4 + num_7 <= num4 + num7:
num4 = num_4
num7 = num_7
if num4 == inf:
print(-1)
else:
if num4 == 0:
print('7'*num7)
elif num7 == 0:
print('4'*num4)
else:
print('4'*num4 + '7'*num7)
if __name__ == "__main__":
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (*x*,<=*y*), he can move to (or attack) positions (*x*<=+<=1,<=*y*), (*x*–1,<=*y*), (*x*,<=*y*<=+<=1) and (*x*,<=*y*–1).
Iahub wants to know how many Coders can be placed on an *n*<=×<=*n* chessboard, so that no Coder attacks any other Coder.
|
```python
n = int(input())
for i in range(0,n):
for j in range(0,n):
if((i + 1) % 2 == 0):
if( (j + 1)% 2 == 0):
print("C",end = "")
else:
print(".",end = "")
else:
if( (j + 1)% 2 == 1):
print("C",end = "")
else:
print(".",end = "")
print()
```
|
|
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 = int(input())
lst = list(map(int, input().split()))
lst.sort()
tot = 0
for i in range(n):
tot += abs((i+1) - lst[i])
print(tot)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1,<=2,<=...,<=*n* in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2,<=3,<=...,<=*n* (in this particular order). And then she puts a walnut in each region inside the polygon.
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
|
```python
import math as mt
import sys,string
input=sys.stdin.readline
#print=sys.stdout.write
import random
import collections
from heapq import heappush,heapify,heappop
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
n=I()
print((n-2)**2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!
Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All *n* people who came to the barbecue sat in a circle (thus each person received a unique index *b**i* from 0 to *n*<=-<=1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the *j*-th turn was made by the person with index *b**i*, then this person acted like that:
1. he pointed at the person with index (*b**i*<=+<=1) *mod* *n* either with an elbow or with a nod (*x* *mod* *y* is the remainder after dividing *x* by *y*); 1. if *j*<=≥<=4 and the players who had turns number *j*<=-<=1, *j*<=-<=2, *j*<=-<=3, made during their turns the same moves as player *b**i* on the current turn, then he had drunk a glass of juice; 1. the turn went to person number (*b**i*<=+<=1) *mod* *n*.
The person who was pointed on the last turn did not make any actions.
The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.
You can assume that in any scenario, there is enough juice for everybody.
|
```python
a=int(input());b=input();print(sum(b[i-1]==b[i-2]==b[i-3] for i in range(a,len(b),a)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word *s*. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
|
```python
n = int(input())
line = input()
lst = []
lst += line
vowels = "aeiouy"
for i in range(1, n):
if lst[i - 1] in vowels and lst[i] in vowels:
lst[i] = ""
print("".join(lst))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a lazy student. He has *m* clean bowls and *k* clean plates.
Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates.
When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.
|
```python
n,m,k = map(int, input().split())
al = list(map(int, input().split()))
k -= al.count(2)
m -= al.count(1) + max(0, -k)
print(max(0, -m))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result.
Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
|
```python
l, n = input(), input()
o = n.count("1")
z = n.count("0")
print(int(l)-2*min(z, o))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.
Each digit is allowed to occur in the number the same number of times it occurs in the set.
|
```python
n = int(input())
array = list(map(int,input().split()))
if 0 not in array:
print(-1)
else:
output = []
answer = ""
for i in range(len(array)):
if array[i] == 0 or array[i] % 2 == 0 or array[i] % 3 == 0 or array[i] % 5 == 0:
output.append(array[i])
output.sort()
output.reverse()
for i in range(len(output)):
answer += str(output[i])
print(answer)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
|
```python
def mcd(a, b):
resto = 0
while(b > 0):
resto = b
b = a % b
a = resto
return a
n=int(input())
y=n
k=2
p=0
r=0
for q in range (0, n-2):
n=y
while n>=k:
a=n%k
p=p+a
n=n//k
p=p+n
k=k+1
t=k-2
a=mcd(p,t)
nu=p//a
de=t//a
print(str(nu)+"/"+str(de))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The new "Die Hard" movie has just been released! There are *n* people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
|
```python
n=int(input())
x=input()
if(x==25 or x== 50):
print("Yes")
else:
print("No")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [*a*,<=*b*] covers segment [*c*,<=*d*], if they meet this condition *a*<=≤<=*c*<=≤<=*d*<=≤<=*b*.
|
```python
ans = -1
req = []
mx = 0
mn = 10**10
for _ in range(int(input())):
seg = list(map(int, input().split()))
# print(seg)
if seg[0] < mn:
mn = seg[0]
req = seg
ans = _+1
elif seg[0] == mn and seg[1] > mx:
mx = seg[1]
req = seg
ans = _+1
if seg[1] > mx:
mx = seg[1]
# print(mn, mx)
if req != [mn, mx]:
print(-1)
else:
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, firstly, was not gerater than *n*, and, secondly, was divisible by *k*.
Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.
|
```python
y,k,n=map(int,input().split())
if(y>=n):
print(-1)
else:
x=n//k
l=[]
for i in range(1,x+1):
if(k*i-y>0):
l.append((str(k*i-y)))
print(' '.join(l))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.
When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if *i*-th garland is switched on during *x*-th second, then it is lit only during seconds *x*, *x*<=+<=*k**i*, *x*<=+<=2*k**i*, *x*<=+<=3*k**i* and so on.
Mishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers *x*1, *x*2 and *x*3 (not necessarily distinct) so that he will switch on the first garland during *x*1-th second, the second one — during *x*2-th second, and the third one — during *x*3-th second, respectively, and during each second starting from *max*(*x*1,<=*x*2,<=*x*3) at least one garland will be lit.
Help Mishka by telling him if it is possible to do this!
|
```python
x1,x2,x3=[int(x1) for x1 in input().split()]
arr=[]
count=0
count2=0
if(x1==1 or x2==1 or x3==1):
print("YES")
else:
arr.append(x1)
arr.append(x2)
arr.append(x3)
for i in range(3):
if(arr[i]==2):
count=count+1
elif(arr[i]==4):
count2=count2+1
else:
pass
if(count==2 or count2==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())
s = 0
if n % 2 == 0:
s = n // 2
else:
s = n // 2 - n
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
|
```python
input()
L = list(map(int, input().split()))
L.sort()
flag = False
#print(L)
for i in range(1, len(L) - 1):
for j in range(0, len(L) - i - 1):
#print(L[j], L[len(L) - i - 1], L[len(L) - i])
if L[j] + L[len(L) - i - 1] >= L[len(L) - i]:
flag = True
break
print('YES') if flag else print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
a,b=map(int,input().split())
aw=0
draw=0
bw=0
for i in range(1,7):
if(abs(a-i)<abs(b-i)):
aw+=1
elif(abs(a-i)>abs(b-i)):
bw+=1
else:
draw+=1
print(aw,draw,bw)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores *t* points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of *s* sets, he wins the match and the match is over. Here *s* and *t* are some positive integer numbers.
To spice it up, Petya and Gena choose new numbers *s* and *t* before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores *t* points and the match is over as soon as one of the players wins *s* sets.
Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers *s* and *t* for the given match are also lost. The players now wonder what values of *s* and *t* might be. Can you determine all the possible options?
|
```python
import sys
n = int(input())
a = [int(i) for i in input().split()]
m = a[-1]
ans = []
for t in range(1, n + 1):
for s in range(1, n // t + 1):
s1, s2, i, k1, k2 = 0, 0, 0, 0, 0
while i != n:
if a[i] == m:
s1 += 1
else:
s2 += 1
if s1 == t:
s1, s2 = 0, 0
k1 += 1
if s2 == t:
s1, s2 = 0, 0
k2 += 1
i += 1
if s1 == s2 == 0 and s == k1 > k2:
ans.append([s, t])
break
ans.sort(key=lambda x: (x[0], x[1]))
print(len(ans))
for row in ans:
print(*row)
# Fri Jan 01 2021 15:18:31 GMT+0300 (Москва, стандартное время)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
|
```python
from math import gcd
n, s=int(input()), 0
for i in range(2,n):
k = n
while k != 0:
s+=k%i
k//=i
p=gcd(s,n-2)
print(f'{s//p}/{(n-2)//p}')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
|
```python
k, n ,w = map(int, input().split())
b, total = 0, 0
for x in range(1, w+1):
total += x * k
if (n - total) > -1:
print(n)
else:
print(abs(n-total))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let *a* is a permutation of an integers from 1 to *n*, inclusive, and *a**i* denotes the *i*-th element of the permutation. The Little Elephant's recursive function *f*(*x*), that sorts the first *x* permutation's elements, works as follows:
- If *x*<==<=1, exit the function. - Otherwise, call *f*(*x*<=-<=1), and then make *swap*(*a**x*<=-<=1,<=*a**x*) (swap the *x*-th and (*x*<=-<=1)-th elements of *a*).
The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to *n*, such that after performing the Little Elephant's function (that is call *f*(*n*)), the permutation will be sorted in ascending order.
|
```python
def f(m):
p[m-1],p[m]=p[m],p[m-1]
k=int(input())
p=[]
for i in range(1,k+1):
p.append(str(i))
for i in range(k,-1,-1):
if i==1:
break
else:
f(i-1)
print(' '.join(p))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded.
For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct.
For given *n* find out to which integer will Vasya round it.
|
```python
print(input()[:-1]+'0')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that:
- this list contains all Jinotega's flights in this year (in arbitrary order), - Jinotega has only flown from his hometown to a snooker contest and back, - after each competition Jinotega flies back home (though they may attend a competition in one place several times), - and finally, at the beginning of the year Jinotega was at home.
Please help them to determine Jinotega's location!
|
```python
n = int(input())
home = input()
flights = []
comesFrom = []
goesTo = []
for i in range(n):
flights.append(input())
goingFrom, comingTo = flights[i].split('->', 1)
if(goingFrom == home):
goesTo.append(comingTo)
if(comingTo == home):
comesFrom.append(goingFrom)
if(len(comesFrom) == len(goesTo)):
print('Home')
else:
print('Contest')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction — it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word *s*. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word *abacabaca* is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {*aca*,<=*ba*,<=*ca*}.
|
```python
from collections import defaultdict,Counter,deque
import math
import bisect
from itertools import accumulate
from math import ceil, log,gcd
from functools import lru_cache
from sys import stdin, stdout
import atexit
import io
import sys
def write(*args, **kwargs):
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
stdout.write(sep.join(str(a) for a in args) + end)
def read():
return stdin.readline().rstrip()
import sys
import random
from typing import List
def primes(n):
if n<=2:
return []
sieve=[True]*(n+1)
for x in range(3,int(n**0.5)+1,2):
for y in range(3,(n//x)+1,2):
sieve[(x*y)]=False
return [2]+[i for i in range(3,n,2) if sieve[i]]
def prime_factors(n):
i = 2
factors = []
for i in primes(int(n**0.5+1)):
while n % i == 0:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
# x = int(read())
# total = int(read())
# n,m= ([*map(int, read().split())])
# d = [{} for i in range(m)]
# p = [0]*n
# for i in range(m):
# x = ([*map(int, read().split())])
# cur = x[0]
# for j in x[1:]:
# d[i][cur] = j
# cur = j
# d[i][cur] = -1
# cc = 0
# for i in x:
# if p[i-1] == 0:
# c = 1
# cur = i
# while True:
# if cur == -1:
# break
# # print(cur,c)
# cc+=c
# p[cur-1] = 1
# n = True
# t = d[0][cur]
# for j in range(1,m):
# # print('!', d[j][cur] ,t)
# if d[j][cur] != t:
# n= False
# # print('!!!')
# break
# if n :
# c+=1
# cur = d[0][cur]
# else:
# break
# print(cc)
s = read()
d = set()
r = set()
n = len(s)
for i in range(n):
if i > 5:
if i!=n-2:
d.add(s[i-1:i+1])
if i > 6:
if i!=n-2:
d.add(s[i-2:i+1])
if i+2 < len(s):
if s[i-1:i+1]==s[i+1:i+3]:
r.add(s[i-1:i+1])
if i+3 < len(s):
if s[i-2:i+1]==s[i+1:i+4]:
r.add(s[i-2:i+1])
ret = [x for x in d if x not in r]
print(len(ret))
for x in ret:
print(x)
# total = int(read())
# x = ([*map(int, read().split())])
# # total = 10**5
# # x = sorted([random.randint(1, 10**5) for i in range(total)])
# mx = 0
# p = primes(10**5)
# d= defaultdict(lambda:0)
# for i in x:
# # print(i)
# t = []
# m = 0
# p = prime_factors(i)
# # print(i,p)
# for j in range(len(p)):
# if p[j] > i:
# break
# if i % p[j] == 0:
# t.append(j)
# m = max(m,d[p[j]])
# for j in t:
# d[p[j]] = m + 1
# mx = max(mx,m+1)
# write(mx)
# a= 1
# b = 1
# for i in range(1,1337):
# a,b = 4*a +b, a + 2*b
# a,b = a%1000000007,b%1000000007
# print((a+b)%1000000007)
# for _ in range(total):
# n = int(read())
# x = sorted(x)
# o = x.count(1)
# while True:
# if o ==0:
# break
# if not check(o):
# o-=1
# else:
# break
# write(o)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.
The playing field is a sequence of *n* non-negative integers *a**i* numbered from 1 to *n*. The goal of the game is to make numbers *a*1,<=*a*2,<=...,<=*a**k* (i.e. some prefix of the sequence) equal to zero for some fixed *k* (*k*<=<<=*n*), and this should be done in the smallest possible number of moves.
One move is choosing an integer *i* (1<=≤<=*i*<=≤<=*n*) such that *a**i*<=><=0 and an integer *t* (*t*<=≥<=0) such that *i*<=+<=2*t*<=≤<=*n*. After the values of *i* and *t* have been selected, the value of *a**i* is decreased by 1, and the value of *a**i*<=+<=2*t* is increased by 1. For example, let *n*<==<=4 and *a*<==<=(1,<=0,<=1,<=2), then it is possible to make move *i*<==<=3, *t*<==<=0 and get *a*<==<=(1,<=0,<=0,<=3) or to make move *i*<==<=1, *t*<==<=1 and get *a*<==<=(0,<=0,<=2,<=2) (the only possible other move is *i*<==<=1, *t*<==<=0).
You are given *n* and the initial sequence *a**i*. The task is to calculate the minimum number of moves needed to make the first *k* elements of the original sequence equal to zero for each possible *k* (1<=≤<=*k*<=<<=*n*).
|
```python
import math
n=int(input())
seq=list(map(int,input().split()))
move=0
while len(seq)>1:
lenth=len(seq)
while seq[0]!=0:
move+=1
seq[0]-=1
lgint=int(math.log2(lenth-1)//1)
seq[2**lgint]+=1
seq.remove(seq[0])
print(move)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.
An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
|
```python
import math
mod=10**9+7
n=int(input())
d = 0
abc = 3
for i in range(2,n+1):
d,abc = abc, 3*d+2*abc
print(d%mod)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.
A believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.
However, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.
As a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.
There are *n* experienced members and *m* newbies on the training session. Can you calculate what maximum number of teams can be formed?
|
```python
n, m = list(map(int, input().split()))
ans = 0
for i in range(n):
cur = i
f = n - i
mn = m - 2 * i
if mn >= f:
cur += min(mn, f // 2)
ans += max(cur, ans)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
# 01234
keyword = "hello"
n_keyword = len(keyword)
#keyword[0] == word[0] no
#keyword[0] == word[1] yes
#keyword[1] == word[2] no
#keyword[1] == word[3] yes
#keyword[2] == word[4] yes
#keyword[3] == word[5] yes
#keyword[4] == word[6] no
#keyword[4] == word[7] no
#keyword[4] == word[8] no
#keyword[4] == word[9] yes
#......
#until there is 5 yes
#or until all words have been checked
#if there is no 5 yes then print("NO")
# 012345678901
#word = "ahhellllloou"
word=input()
n_word = len(word)
#How to do WHILE you need to:
#1. initial counter
#2. ending condition
#3. counter increase/decrease
yes=0
counter = 0
counter2 = 0
while counter < n_keyword:
while counter2<n_word and yes<n_keyword:
#print(keyword[counter],"==",word[counter2], "?", end=" ")
if keyword[counter] == word[counter2]:
yes = yes + 1
counter = counter + 1
#print("Yes")
#else:
#print("No")
counter2 = counter2 + 1
counter = n_keyword
if yes == n_keyword:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, firstly, was not gerater than *n*, and, secondly, was divisible by *k*.
Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.
|
```python
y, k, n = map(int, input().split())
vals = []
for x in range(((y//k)+1)*k-y, n+1, k):
if x+y>n:
break
vals.append(str(x))
if not vals:
print(-1)
else:
print(*vals)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Ms Swan bought an orange in a shop. The orange consisted of *n*·*k* segments, numbered with integers from 1 to *n*·*k*.
There were *k* children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the *i*-th (1<=≤<=*i*<=≤<=*k*) child wrote the number *a**i* (1<=≤<=*a**i*<=≤<=*n*·*k*). All numbers *a**i* accidentally turned out to be different.
Now the children wonder, how to divide the orange so as to meet these conditions:
- each child gets exactly *n* orange segments; - the *i*-th child gets the segment with number *a**i* for sure; - no segment goes to two children simultaneously.
Help the children, divide the orange and fulfill the requirements, described above.
|
```python
n, k = [int(x) for x in input().split(' ')]
a = [int(x) for x in input().split(' ')]
b = [i for i in range(1, n * k + 1) if i not in a]
for i in range(k):
print(*([a[i]] + b[i*(n-1):(i+1)*(n-1)]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
|
```python
a=int(input())
b=int(input())
c=int(input())
d=int(input())
if (a+b>c) and (b+c>a) and (c+a>b):
print("TRIANGLE")
elif (a+b>d) and (a+d>b) and (d+b>a):
print("TRIANGLE")
elif (a+c>d) and (a+d>c) and (d+c>a):
print("TRIANGLE")
elif (b+c>d) and (b+d>c) and (b+c>a):
print("TRIANGLE")
elif (a+b==c) or (b+c==a) or (c+a==b):
print("SEGMENT")
elif (a+b==d) and (a+d==b) and (d+b==a):
print("SEGMENT")
elif (a+c==d) and (a+d==c) and (d+c==a):
print("SEGMENT")
elif (b+c==d) or (b+d==c) or (b+c==a):
print("SEGMENT")
elif (a+b<c) and (b+c<a) and (c+a<b):
print("IMPOSSIBLE")
elif (a+b<d) and (a+d<b) and (d+b<a):
print("IMPOSSIBLE")
elif (a+c<d) and (a+d<c) and (d+c<a):
print("IMPOSSIBLE")
elif (b+c<d) and (b+d<c) and (b+c<a):
print("IMPOSSIBLE")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
|
```python
a , b = map(int , input().split())
arr = [list(input()) for _ in range(a)]
ans = [['-']*b for _ in range(a)]
for i in range(a):
for j in range(b):
if arr[i][j] == '-': continue
if (i+j)%2==0: ans[i][j] = 'B'
else: ans[i][j] = 'W'
for i in ans: print(''.join(i))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of *r*1 cm, inner radius of *r*2 cm, (0<=<<=*r*2<=<<=*r*1) made of metal with density *p*1 g/cm3. The second part is an inner disk with radius *r*2 cm, it is made of metal with density *p*2 g/cm3. The disk is nested inside the ring.
The Olympic jury decided that *r*1 will take one of possible values of *x*1,<=*x*2,<=...,<=*x**n*. It is up to jury to decide which particular value *r*1 will take. Similarly, the Olympic jury decided that *p*1 will take one of possible value of *y*1,<=*y*2,<=...,<=*y**m*, and *p*2 will take a value from list *z*1,<=*z*2,<=...,<=*z**k*.
According to most ancient traditions the ratio between the outer ring mass *m**out* and the inner disk mass *m**in* must equal , where *A*,<=*B* are constants taken from ancient books. Now, to start making medals, the jury needs to take values for *r*1, *p*1, *p*2 and calculate the suitable value of *r*2.
The jury wants to choose the value that would maximize radius *r*2. Help the jury find the sought value of *r*2. Value *r*2 doesn't have to be an integer.
Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
|
```python
import math
x = [int(x) for x in input().split()][1:]
y = [int(x) for x in input().split()][1:]
z= [int(x) for x in input().split()][1:]
A,B = [int(x) for x in input().split()]
pi= 3.14159
x.sort()
y.sort()
z.sort()
r1 = x[-1]
p1 = y[-1]
p2 = z[0]
ans = r1 *(math.sqrt((B*p1)/(A*p2+B*p1)))
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an undirected graph with *n* vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to *n*.
You have to answer *q* queries. Each query is described by a segment of vertices [*l*;<=*r*], and you have to count the number of its subsegments [*x*;<=*y*] (*l*<=≤<=*x*<=≤<=*y*<=≤<=*r*), such that if we delete all vertices except the segment of vertices [*x*;<=*y*] (including *x* and *y*) and edges between them, the resulting graph is bipartite.
|
```python
import sys
readline=sys.stdin.readline
from bisect import bisect_right
N,M=map(int,readline().split())
graph=[[] for x in range(N)]
for m in range(M):
a,b=map(int,readline().split())
a-=1;b-=1
graph[a].append(b)
graph[b].append(a)
seen=[False]*N
finished=[False]*N
order=[None]*N
lowlink=[None]*N
idx=0
ps=[None]*N
preorder=[]
for s in range(N):
if seen[s]:
continue
stack=[s]
while stack:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append(x)
order[x]=idx
lowlink[x]=idx
idx+=1
preorder.append(x)
for y in graph[x]:
if not seen[y]:
stack.append(y)
ps[y]=x
elif not finished[x]:
finished[x]=True
bl=True
for y in graph[x]:
if ps[x]==y and bl:
bl=False
continue
lowlink[x]=min(lowlink[x],order[y])
if x!=s:
lowlink[ps[x]]=min(lowlink[ps[x]],lowlink[x])
order=[None]*N
for x in range(N):
order[preorder[x]]=x
graph=[[y for y in graph[x] if order[x]>=lowlink[y] and order[y]>=lowlink[x]] for x in range(N)]
seen=[False]*N
finished=[False]*N
right=[N]*N
for s in range(N):
if seen[s]:
continue
mi,ma=s,s
stack=[s]
while stack:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append(x)
mi=min(mi,x)
ma=max(ma,x)
for y in graph[x]:
if not seen[y]:
stack.append(y)
elif not finished[x]:
finished[x]=True
if mi!=ma:
right[mi]=ma
for l in range(N-2,-1,-1):
right[l]=min(right[l],right[l+1])
C=[0]+right
for i in range(1,N+1):
C[i]+=C[i-1]
Q=int(readline())
for q in range(Q):
L,R=map(int,readline().split())
L-=1
i=max(L,bisect_right(right,R))
ans=C[i]-C[L]+R*(R-i)-(L+R-1)*(R-L)//2
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The new "Die Hard" movie has just been released! There are *n* people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
|
```python
n = int(input())
money = [int(i) for i in input().split()]
stored = 0
flag = True
for i in range(n):
change = money[i] - 25
if stored >= 0 and change > 0:
stored = stored - change
if stored < 0:
flag = False
break
stored += 25
if flag:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
m,n,a= map(int,input().split())
M = 0
N = 0
if m % a == 0:
M = m // a
else:
M = (n // a) +1
if n % a == 0:
N = n // a
else:
N = (n // a) +1
print(M*N)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
|
```python
n,s = int(input()) - 1,list(map(int,input().split()))
print(max(int(sum(s) / n + 0.5),max(s)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and *L*, and they move towards each other with speed *v*1 and *v*2, respectively. Luke has width *d* and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.
|
```python
l,d,v1,v2=map(int,input().split())
v=v1+v2
a=v
x=d-l
if(v-x>19995):
v=2000
ans=str(x/v).split(".")
if(a-x>19995):
ans[1]="0"+ans[1]+"0"*(19-len(ans[1]))
print(ans[1])
else:
ans[1]=ans[1]+"0"*(20-len(ans[1]))
print(".".join(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
x=input().lower()
s=[]
hello=["h","e","l","l","o"]
if len(x)>5:
for i in x:
for j in hello:
if j==i:
s.append(i)
if len(s)<5:
print("NO")
else:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
|
```python
cost = 0
k, n, w = map(int, input().split())
for i in range(1 , w+1):
cost += i*k
print(cost-n) if cost > n else print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.
Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
|
```python
from math import ceil
n, t, k, d = map(int, input().split())
total_time = ceil(n / k) * t
if total_time > t + d:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
|
```python
w=int(input('no'))
assert 1<=w<=100
for i in range(2,w,2):
if (w-i)%2==0:
return YES
return NO
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players take turns crossing out exactly *k* sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than *k* sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
|
```python
n,k = map(int,input().split());s=0;t=0
if (n == 1 and k != 1) or (n == 1 and k == 1):
print("YES")
exit()
else:
while n - k > t:
t+=k
s+=1
if s % 2 == 0:
print("NO")
elif s % 2 != 0:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.
There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.
Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.
|
```python
## 2 - version
import re
s=input()
if re.search('C.*O.*D.*E.*F.*O.*R.*C.*E.*S',s):
print('YES')
else:
print('NO')
```
|
|
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=input()
summands=list(map(int,input().split()))
sorted_summands=sorted(summands)
new_sum="+".join(map(str,sorted_summands))
print(new_sum)
```
|
|
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
import sys
n1 = sys.stdin.readline().strip("\n")
n2= sys.stdin.readline().strip("\n")
i =0
r =""
while i < len(n1):
r+=str(int(n1[i])^ int(n2[i]))
i += 1
print(r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
|
```python
class Solution:
def __init__(self):
pass
def solve(self):
n = int(input())
arr = list(map(int, input().split()))
each = 2*sum(arr)//n
result = ""
for i in range(n - 1):
if arr[i] != 0:
for j in range(i+1, n):
if arr[j] + arr[i] == each:
result += "{} {}\n".format(i + 1, j + 1)
break
print(result)
if __name__ == "__main__":
sol = Solution()
sol.solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer *n*?"
Petya knows only 5 integer types:
1) byte occupies 1 byte and allows you to store numbers from <=-<=128 to 127
2) short occupies 2 bytes and allows you to store numbers from <=-<=32768 to 32767
3) int occupies 4 bytes and allows you to store numbers from <=-<=2147483648 to 2147483647
4) long occupies 8 bytes and allows you to store numbers from <=-<=9223372036854775808 to 9223372036854775807
5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer *n*. Since BigInteger works much slower, Peter regards it last. Help him.
|
```python
n = int(input())
sections = [int(i) for i in input().split()]
maximal = 0
for i in range(n):
counter = 0
for j in range(i, -1, -1):
if sections[j] > sections[i]:
break
counter += 1
for j in range(i + 1, n):
if sections[j] > sections[i]:
break
counter += 1
if counter > maximal:
maximal = counter
print(maximal)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a square painted on a piece of paper, the square's side equals *n* meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (*n*<=+<=1) meters, he draws a cross (see picture for clarifications).
John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?
|
```python
n=int(input())
for i in range(n):
t=int(input())
print(4*t+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
|
```python
n=input()
n=n[::-1]
v=['A','E','I','O','U','Y','a','e','i','o','u','y']
for i in range(len(n)):
if n[i]!='' and n[i]!='?':
if n[i] in v:
print("YES")
else:
print("NO")
break
```
|
|
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
#!/usr/bin/env python3.4
n, m = map(int, input().split())
board = []
for i in range(n):
board.append(input())
ok_set = set(['f', 'a', 'c', 'e'])
ans = 0
for i in range(n - 1):
for j in range(m - 1):
cur_set = set([board[i][j], board[i][j + 1], board[i + 1][j], board[i + 1][j + 1]])
if cur_set == ok_set:
ans += 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
l = list(map(int,input().split()))
x = l[1]%l[2]
y = l[0]%l[2]
a = (l[0]+y)//l[2]
b = (l[1]+x)//l[2]
print(a*b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to *n* (*n*<=≥<=2) burles and the amount of tax he has to pay is calculated as the maximum divisor of *n* (not equal to *n*, of course). For example, if *n*<==<=6 then Funt has to pay 3 burles, while for *n*<==<=25 he needs to pay 5 and if *n*<==<=2 he pays only 1 burle.
As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial *n* in several parts *n*1<=+<=*n*2<=+<=...<=+<=*n**k*<==<=*n* (here *k* is arbitrary, even *k*<==<=1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition *n**i*<=≥<=2 should hold for all *i* from 1 to *k*.
Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split *n* in parts.
|
```python
import sys
import math
def isprime(n):
if n == 1:
return False
if n == 2:
return True
if n == 3:
return True
if (n % 2 == 0) or (n % 3 == 0):
return False
for i in range(5, int(math.sqrt(n))+1, 6):
if (n % i == 0) or (n % (i + 2)) == 0:
return False
return True
def answer(n):
if isprime(n):
return 1
if n % 2 == 0:
return 2
if isprime(n-2):
return 2
else:
return 3
def main():
n = int(sys.stdin.readline())
print(answer(n))
return
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Daniel is organizing a football tournament. He has come up with the following tournament format:
1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 1. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are *x* teams, there will be games), and the tournament ends.
For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.
Daniel has already booked the stadium for *n* games. Help him to determine how many teams he should invite so that the tournament needs exactly *n* games. You should print all possible numbers of teams that will yield exactly *n* games in ascending order, or -1 if there are no such numbers.
|
```python
n, out, po = int(input()), set(), 1
for x in range(64):
be, en = 1, 2 * 10 ** 9
while be <= en:
md = (be + en) >> 1
val = md * (po - 1) + md * (md - 1) // 2
if val < n:
be = md + 1
elif val == n:
out.add(po * md)
break
else:
en = md - 1
po <<= 1
if not out:
exit(print(-1))
print('\n'.join(map(str, sorted(out))))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*.
|
```python
n=list(map(int,input().split()))
s=1
while(True):
n[0]=n[0]+1
if(n[0]%n[1]==0):
print(n[0])
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
|
```python
count = 0
wcount = 0
for i in range(int(input())):
a , b = map(int,input().split())
if (a == 0 and b == 0) or (a == 1 and b == 1):
count += 1
else:
wcount += 1
print(wcount)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to *n*. Let's assume that Misha chose number *m*, and Andrew chose number *a*.
Then, by using a random generator they choose a random integer *c* in the range between 1 and *n* (any integer from 1 to *n* is chosen with the same probability), after which the winner is the player, whose number was closer to *c*. The boys agreed that if *m* and *a* are located on the same distance from *c*, Misha wins.
Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number *n*. You need to determine which value of *a* Andrew must choose, so that the probability of his victory is the highest possible.
More formally, you need to find such integer *a* (1<=≤<=*a*<=≤<=*n*), that the probability that is maximal, where *c* is the equiprobably chosen integer from 1 to *n* (inclusive).
|
```python
n,m=map(int,input().split(' '))
if(m==1):
if(n==1):print(1)
else:print(2)
elif(m==n):print(n-1)
else:
if(m-1>=n-m):print(m-1)
else:print(n-m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya collects coins: he has exactly one coin for every year from 1 to *n*. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from *l* to *r* inclusively and put them in the reverse order. That is, he took a certain segment [*l*,<=*r*] and reversed it. At that the segment's endpoints did not coincide. For example, if *n*<==<=8, then initially Vasya's coins were kept in the order 1 2 3 4 5 6 7 8. If Vasya's younger brother chose the segment [2,<=6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Vasya suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 ... *n* using exactly one segment reversal. If it is possible, find the segment itself.
|
```python
n=int(input());A=list(map(int,input().split()));B=A.copy();B.sort();C=[]
if A==B:print(0,0)
else:
left=0;right=0
for i in range(n):
if A[i]!=B[i]:
C.append(abs(A[i]-B[i]))
if A[i]==B[i] and right==0:left=i+2
elif A[i]!=B[i]:right=i+1
if C==C[::-1]:print(left,right)
else:print(0,0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has *n* balls and *m* baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to *m*, correspondingly. The balls are numbered with numbers from 1 to *n*.
Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where *i* is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.
For every ball print the number of the basket where it will go according to Valeric's scheme.
Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
|
```python
n,m = map(int,input().split())
mid = (m+1)//2
lst = [0]*m
lst[0] = mid
p = 1
for i in range(1,mid):
lst[p] = mid-i
lst[p+1] = mid+1
p += 2
if m%2==0:
lst[n-1] = m
x = n//m
v = n-x*m
lst *= x
lst.extend(lst[:v])
print(*lst)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
s=input()
t=list(reversed(list(input())))
for letter_s,letter_t in zip(s,t):
if letter_s!=letter_t:
print("NO")
break
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
|
```python
n=int(input())
output=[]
for i in range(1,101):
listi=list(map(int,str(i)))
if(i+sum(listi)==n):
output.append(i)
print(len(output))
for i in range(len(output)):
print(output[i])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Duff is addicted to meat! Malek wants to keep her happy for *n* days. In order to be happy in *i*-th day, she needs to eat exactly *a**i* kilograms of meat.
There is a big shop uptown and Malek wants to buy meat for her from there. In *i*-th day, they sell meat for *p**i* dollars per kilogram. Malek knows all numbers *a*1,<=...,<=*a**n* and *p*1,<=...,<=*p**n*. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.
Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for *n* days.
|
```python
n = int(input())
m = []
p = []
for i in range(n):
mi, pi = map(int, input().split())
m.append(mi)
p.append(pi)
ans = 0
minp = p[0]
for i in range(n):
minp = min(p[i], minp)
ans += m[i]* minp
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve the *i*-th problem.
Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first.
How many problems can Limak solve if he wants to make it to the party?
|
```python
x,y=map(int,input().split())
c=240-y
p,q=0,0
while (c-p-5)>=0 and x>0:
p+=5
q+=1
x-=1
c-=p
print(e)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.