source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.
This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
|
```python
s = input()
d = {}
for i in s:
if i not in d:
d[i] = None
print("CHAT WITH HER!") if len(d) % 2 == 0 else print("IGNORE HIM!")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...
|
```python
string = input()
s = ['h', 'e', 'i', 'd', 'i']
ans = list()
for c in string:
if c in s:
ans.append(c)
ans = ''.join(ans)
if ans == 'heidi':
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
|
```python
a = input()
s = 6
ind = 0
for i in range(len(a)):
if a[i] == "1":
ind = i
break
for i in range(ind,len(a)):
if s == 0:
break
elif a[i] == "0":
s -= 1
if s == 0:
print("yes")
else:
print("no")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
|
```python
from functools import reduce
def main():
n = int(input())
cs = list(map(int, input().split()))
s = reduce(lambda x, y: x + y, cs)
sol = 0
for i in range(1, 6):
if ((i + s - 1) % (n + 1)) != 0:
sol += 1
print(sol)
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
|
```python
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
current_streak = 0
for i in range(1,n):
if current_streak >= k or a[0] == n:
print(a[0])
break
elif a[i] == n:
print(a[i])
break
elif a[i] > a[0]:
a[0] = a[i]
current_streak = 1
else:
current_streak += 1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
|
```python
def solve():
n = int(input())
dados = {}
yes = False
for i in range(n):
x,d = map(int,input().split())
dados[x] = (x+d)
if((x+d) in list(dados.keys()) and yes == False):
if(dados[x+d]==x):
print("YES")
yes = True
if(yes == False):
print("NO")
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.
Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?
Heidi's *n* friends are labeled 0 through *n*<=-<=1, and their network of connections forms a tree. In other words, every two of her friends *a*, *b* know each other, possibly indirectly (there is a sequence of friends starting from *a* and ending on *b* and such that each two consecutive friends in the sequence know each other directly), and there are exactly *n*<=-<=1 pairs of friends who know each other directly.
Jenny is given the number 0.
|
```python
n=int(input())
l={}
k={0}
r={}
o=[]
cc=set()
for i in range(n):
cc.add(i)
for i in range(n-1):
q,w,z=map(int,input().split())
if q in k:
r[w]=q
k.add(w)
cc.discard(q)
l[(w,q)]=z
elif w in k:
r[q]=w
k.add(q)
cc.discard(w)
l[(q,w)]=z
else:
o+=[[q,w,z]]
for i in o:
q,w,z=i[0],i[1],i[2]
if q in k:
r[w]=q
k.add(w)
cc.discard(q)
l[(w,q)]=z
elif w in k:
r[q]=w
k.add(q)
cc.discard(w)
l[(q,w)]=z
s=0
for i in cc:
aa=0
pp=-1
while pp!=0:
pp=r[i]
aa+=l[(i,pp)]
i=pp
s=max(s,aa)
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.
Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.
However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.
Write a program that models the behavior of Ankh-Morpork residents.
|
```python
n = int(input())
num = input()
num = list(int(x) for x in num.split(" "))
i = 0
while n > 0 and i < len(num):
if num[i] == n:
print(n, end=" ")
n -= 1
while n > 0:
if num.index(n) < i:
print(n, end=" ")
n -= 1
else:
print("\n", end ="")
break
else:
print(" ")
i += 1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
t=int(input())
l=[]
c=0
for i in range(0,t):
x=int(input())
y=int(input())
z=int(input())
l.append([x,y,z])
for j in range(0,3):
sum=0
for i in range(0,t):
sum=sum+l[i][j]
if sum=-=0:
c=c+1
if c==3:
print("YES")
else:
print("NO")
```
|
|
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
chessboard = input()
chessboard = int(chessboard)
#odd = n^2 - 1 / 2
#even = n^2 / 2
if chessboard % 2 == 0:
print(int((chessboard ** 2) / 2))
else:
print(int(((chessboard ** 2) - 1) / 2))
temp = 0
for i in range(0,chessboard):
for j in range(0,chessboard):
if temp == 0:
print('C',end='')
temp = temp + 1
else:
print('.',end='')
temp = 0
#special case for even
if chessboard % 2 == 0:
temp = 1 - temp
print('')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes).
|
```python
s = (str(input()))
for str in s:
print("NO")
if str == str in s:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
|
```python
cards = input()
l = "02468aeiou"
output = 0
for i in cards:
if(i in l):
output += 1
print(output)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A frog lives on the axis *Ox* and needs to reach home which is in the point *n*. She starts from the point 1. The frog can jump to the right at a distance not more than *d*. So, after she jumped from the point *x* she can reach the point *x*<=+<=*a*, where *a* is an integer from 1 to *d*.
For each point from 1 to *n* is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and *n*.
Determine the minimal number of jumps that the frog needs to reach home which is in the point *n* from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
|
```python
n, d = list(map(int, input().split()))
s = input()
count = 0
i = 0
while(i < n):
countStart = count
for _d in range(d, 0, -1):
if i+_d < n and s[i+_d] == '1':
i += _d
count += 1
break
if countStart == count:
count = -1
break
if i == n-1: break
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given positive integer number *n*. You should create such strictly increasing sequence of *k* positive numbers *a*1,<=*a*2,<=...,<=*a**k*, that their sum is equal to *n* and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.
If there is no possible sequence then output -1.
|
```python
from math import sqrt
def factors(n,k):
i=2;p=(k*(k-1))//2;s=0
while i<=sqrt(n):
if n%i==0:
if n//i-p>k-1:s=max(s,i)
if i-p>k-1:s=max(s,n//i)
i+=1
return 1 if s==0 else s
def solve(n,k):
p=(2*n)/(k*(k+1));m=factors(n,k)
if p<1 or k>=n:return [-1]
if p%1==0:return [x*int(p) for x in range(1,k+1)]
return [x*m for x in range(1,k)]+[n-(m*k*(k-1))//2]
n,k=map(int,input().split())
print(n) if k==1 else print(*solve(n,k))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
|
```python
S = list(input()); S.sort(); S = ''.join(S); print("YES" if "1111111" in S or "0000000" in S else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
|
```python
n = int(input())
s = []
for i in range(n):
if len(s) == 0:
s.append(input())
else:
v = input()
if v in s:
s.remove(v)
s += [v]
else:
s += [v]
[print(s[x]) for x in range(len(s) - 1, -1, -1)]
```
|
|
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
number = input("put numbers of watermelon: ")
watermelon = float(number)
modulo = watermelon / 2
if watermelon%2 == 0:
if modulo % 2 == 0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n=raw_input(n)
number_of_evens=0
for i in range(0,len(n)):
if n[i]%2==0:
number_of_evens+=1
index_even=(n.index(n[i]))+1
else:
index_odd=(n.index(n[i]))+1
number_of_odds=len(n)-number_of_evens
if number_of_odds==1:
print(index_odd)
if number_of_evens==1:
print( index_even)
```
|
|
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
a, b = map(int,input().split())
b = 240 - b
val = 0
for i in range(1, a+1):
if b >= 5*i:
b -= 5*i
val += 1
print(val)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following *m* days.
Determine the number of days starting from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.
|
```python
n, p, m = input().split()
n = int(n)
p = int(p)
m = int(m)
ans = 0
curb = 0
curd = 1
for i in range(0, n):
#print(curb)
tday, tplus = input().split()
tday = int(tday)
tplus = int(tplus)
if curb < 0:
ans += (tday - curd)
curb -= p * (tday - curd)
elif curb - p * (tday - curd) < 0:
curb -= p * (tday - curd)
x = -curb
xx = x // p
if xx * p < x:
xx += 1
x = xx
ans += x
else:
curb -= p * (tday - curd)
curd = tday
#print(curb)
curb += tplus
tday = m + 1
if curb < 0:
ans += (tday - curd)
curb -= p * (tday - curd)
elif curb - p * (tday - curd) < 0:
curb -= p * (tday - curd)
x = -curb
xx = x // p
if xx * p < x:
xx += 1
x = xx
ans += x
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are *n* destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The *n* destinations are described by a non-negative integers sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents that the *k*th destination is at distance *a**k* kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer *x* and next destination, located at kilometer *y*, is |*x*<=-<=*y*| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all *n* destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
|
```python
import math
n = int(input())
l = [int(x) for x in input().split()]
a1 = sum(l)
a2 = n
a3 = 0
temp = 0
for i in range(n):
temp += l[n-i-1]
a3-=(a1-temp)
a3+=(n-i-1)*(l[n-i-1])
a1 = a1+a3+a3
a4 = math.gcd(a1, a2)
print(a1//a4, a2//a4)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".
For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).
It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again.
Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative.
As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.
We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.
|
```python
(((( return
```
|
|
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
import math
def domino(numbers):
num = numbers.split(" ")
n= int(num[0])
m=int(num[1])
a=int(num[2])
return (math.ceil(n/a) * math.ceil(m/a))
numbers=input("")
print(domino(numbers))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:
- Assume that the rows are numbered 1 to *n* from top to bottom and the columns are numbered 1 to *m* from left to right, and a cell in row *i* and column *j* is represented as (*i*,<=*j*). - First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,<=1)<=→<=...<=→<=(1,<=*m*)<=→<=(2,<=1)<=→<=...<=→<=(2,<=*m*)<=→<=...<=→<=(*n*,<=1)<=→<=...<=→<=(*n*,<=*m*). Waste cells will be ignored. - Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on.
The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.
Now she is wondering how to determine the crop plants in some certain cells.
|
```python
n,m,k,t = [int(x) for x in input().split()]
mapp ={0:'Carrots',1:'Kiwis',2:'Grapes'}
iamdistruption = []
for i in range(k):
x,y = [int(x) for x in input().split()]
iamdistruption.append((x,y))
for i in range(t):
x,y = [int(x) for x in input().split()]
orig = ((m*(x-1))+y-1)
disbeforeme = 0
for x,y in iamdistruption:
if m*(x-1)+y-1==orig:
print("Waste")
break
elif m*(x-1)+y-1<orig:
disbeforeme+=1
else:
afterdis = ((orig%3) - disbeforeme)%3
print(mapp[afterdis])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For each string *s* consisting of characters '0' and '1' one can define four integers *a*00, *a*01, *a*10 and *a*11, where *a**xy* is the number of subsequences of length 2 of the string *s* equal to the sequence {*x*,<=*y*}.
In these problem you are given four integers *a*00, *a*01, *a*10, *a*11 and have to find any non-empty string *s* that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1<=000<=000.
|
```python
def getxs(n):
D = 1 + 4 * n
x1 = (-1 + D**0.5) / 2 + 1
x2 = (-1 - D**0.5) / 2 + 1
if x1 > 1e-6 and abs(round(x1) - x1) < 1e-6:
return round(x1)
elif x2 > 1e-6 and abs(round(x2) - x2) < 1e-6:
return round(x2)
return -1
a00, a01, a10, a11 = map(int, input().split())
if a01 == 0 and a10 == 0:
if a00 != 0 and a11 != 0:
print('Impossible')
exit(0)
if a00 != 0:
kol_0 = getxs(a00 * 2)
if kol_0 != -1:
print(kol_0 * '0')
exit(0)
else:
print('Impossible')
exit(0)
if a11 != 0:
kol_1 = getxs(a11 * 2)
if kol_1 != -1:
print(kol_1 * '1')
exit(0)
else:
print('Impossible')
exit(0)
kol_0 = getxs(a00 * 2)
kol_1 = getxs(a11 * 2)
if kol_1 < 0 or kol_0 < 0 or kol_1 * kol_0 != a10 + a01:
print('Impossible')
exit(0)
zeros_right = a10 // kol_1
last_zero = a10 % kol_1
print('0' * (kol_0 - zeros_right - 1) + '1' * last_zero + '0' + '1' * (kol_1 - last_zero) + '0' * zeros_right)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
|
```python
number = input()
for i in range(len(number)):
if i == 0 and number[i] == '9':
print(9, end='')
elif int(number[i]) >= 5:
print(9 - int(number[i]), end='')
else:
print(number[i], end='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
import sys
n=[ ]
a=int(input())
n=list(map(int,input().split()))
n1=n2=0
for i in range (len(n)):
if n[i] %2==0:
n1=n1+1
c=i+1
else :
n2=n2+1
b=i+1
if n1>n2 :
print(b)
else :
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of *a* in any order. What is the maximum possible number of indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), such that *a**i*<=+<=1<=><=*a**i*.
|
```python
n=int(input())
lst = list(map(int, input().strip().split(' ')))
lst.sort()
l=[[lst[0]]]
for i in range(1,n):
j=0
while(True):
if j==len(l):
l.append([lst[i]])
break
else:
if l[j][-1]!=lst[i]:
l[j].append(lst[i])
break
else:
j+=1
s=0
for i in range(len(l)):
s+=len(l[i])-1
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A country has *n* cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given *m* pairs of cities — roads cannot be constructed between these pairs of cities.
Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
|
```python
n, m = map(int,input().split())
no_connections = list(map(int,input().split()))
root = 1
for i in range(1,n+1):
if i not in no_connections:
root = i
break
print(n-1)
for i in range(1,n+1):
if i!=root:
print(f'{root} {i}')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:
- there wouldn't be a pair of any side-adjacent cards with zeroes in a row; - there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought *n* cards with zeroes and *m* cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
|
```python
n,m = map(int,input().split())
if n > m:
ans = '001'*(m)
n -=(m*2)
ans += '0'*(n)
elif n < m:
ans = '110'*(n)
m -= (n*2)
ans += '1'*(m)
else:
ans = '10'*(m)
flag = True
for i in range(len(ans)-2):
a = ans[i]+ans[i+1]+ans[i+2]
if a == '000' or a == '111':
flag = False
break
print(ans if flag else -1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.
Help the dwarfs find out how many triangle plants that point "upwards" will be in *n* years.
|
```python
def main():
year = int(input())
end = pow(2,year)
ans = sum(range(1,end+1))
print(ans)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* beacons located at distinct positions on a number line. The *i*-th beacon has position *a**i* and power level *b**i*. When the *i*-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance *b**i* inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.
Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.
|
```python
n = int(input())
a = [tuple(map(int, input().split())) for _ in range(n)]
a.sort()
dp = [1] * n
res = n - 1
for i in range(n):
j = i - 1
while j >= 0 and a[j][0] + a[j][1] <= a[i][0]:
j -= 1
if j >= 0:
dp[i] = dp[j] + 1
else:
dp[i] = 1
res = min(res, n - dp[i])
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has *m* faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the *m*-th face contains *m* dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice *n* times.
|
```python
m, n = [int(i) for i in input().split()]
res = 0
for i in range(1,m+1):
res += i*(pow(i,n) - pow((i-1),n))/pow(m,n)
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Tonio has a keyboard with only two letters, "V" and "K".
One day, he has typed out a string *s* with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.
|
```python
s=input()
visited=False
t=l=0
if len(s)==2:
if s[0]=="V" and s[1]=="K":
t+=1
elif s[0]=="V" and s[1]=="V":
t+=1
elif s[0]=="K" and s[1]=="K":
t+=1
else:
i=1
while i<len(s):
if s[i]=="K" and s[i-1]=="V":
t+=1
i+=1
elif i<len(s)-1 and s[i]=="V" and s[i-1]=="V" and s[i+1]=="V" and visited==False:
l+=1
i+=2
visited=True
elif i<len(s)-1 and s[i]=="K" and s[i-1]=="K" and s[i+1]=="K" and visited==False:
l+=1
i+=2
visited=True
else:
i+=1
if l>0:
t+=1
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky.
|
```python
a = [4, 7]
for i in ('47'):
for j in ('47'):
a.append(int(i + j))
for t in ('47'):
for i in ('47'):
for j in ('47'):
a.append(int(i + j + t))
n = int(input())
flag = False
for i in a:
if n % i == 0:
print('YES')
flag = True
break
if flag == False:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.
The river banks can be assumed to be vertical straight lines *x*<==<=*a* and *x*<==<=*b* (0<=<<=*a*<=<<=*b*).
The west village lies in a steppe at point *O*<==<=(0,<=0). There are *n* pathways leading from the village to the river, they end at points *A**i*<==<=(*a*,<=*y**i*). The villagers there are plain and simple, so their pathways are straight segments as well.
The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are *m* twisted paths leading from this village to the river and ending at points *B**i*<==<=(*b*,<=*y*'*i*). The lengths of all these paths are known, the length of the path that leads from the eastern village to point *B**i*, equals *l**i*.
The villagers want to choose exactly one point on the left bank of river *A**i*, exactly one point on the right bank *B**j* and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |*OA**i*|<=+<=|*A**i**B**j*|<=+<=*l**j*, where |*XY*| is the Euclidean distance between points *X* and *Y*) were minimum. The Euclidean distance between points (*x*1,<=*y*1) and (*x*2,<=*y*2) equals .
Help them and find the required pair of points.
|
```python
__author__ = 'Michael Ilyin'
import math
# debug = True
debug = False
def dist(x1, y1, x2, y2):
return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
def get_y(x1, y1, x2, y2, x):
return (((x - x1) * (y2 - y1)) / (x2 - x1)) + y1
if debug:
with open("input.txt", "r") as inp:
firstLine = inp.readline()
secondLine = inp.readline()
thirdLine = inp.readline()
fourthLine = inp.readline()
else:
firstLine = input()
secondLine = input()
thirdLine = input()
fourthLine = input()
first = firstLine.split()
n = int(first[0])
m = int(first[1])
a = int(first[2])
b = int(first[3])
A = [int(x) for x in secondLine.split()]
B = [int(x) for x in thirdLine.split()]
L = [int(x) for x in fourthLine.split()]
optimalLen = float("inf")
optimalBIdx = -1
for i, bi in enumerate(B):
d = dist(0, 0, b, bi) + L[i]
if d < optimalLen:
optimalLen = d
optimalBIdx = i
if debug:
print(optimalBIdx + 1, optimalLen)
intersectY = get_y(0, 0, b, B[optimalBIdx], a)
if debug:
print(intersectY)
pointDist = float("inf")
optimalAIdx = -1
for i, ai in enumerate(A):
d = dist(a, ai, a, intersectY)
if d < pointDist:
pointDist = d
optimalAIdx = i
if debug:
print(optimalAIdx + 1, pointDist)
print(optimalAIdx + 1, optimalBIdx + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
User ainta has a stack of *n* red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack.
- While the top ball inside the stack is red, pop the ball from the top of the stack. - Then replace the blue ball on the top with a red ball. - And finally push some blue balls to the stack until the stack has total of *n* balls inside.
If there are no blue balls inside the stack, ainta can't apply this operation. Given the initial state of the stack, ainta wants to know the maximum number of operations he can repeatedly apply.
|
```python
n, b = input(), input().replace('R', '0').replace('B', '1')
print(int(b[:: -1], 2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)$. You need to find for each query the sum of elements of the array with indexes from $l_i$ to $r_i$, inclusive.
The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
|
```python
n,m=[int(x) for x in input().split()]
arr=[int(x) for x in input().split()]
ans=[0 for _ in range(n)]
for _ in range(m):
x,y=[int(x) for x in input().split()]
ans[x-1]+=1
if y!=n:
ans[y]-=1
for i in range(1,n):
ans[i]+=ans[i-1]
ans.sort()
arr.sort()
# print(arr)
# print(ans)
solution=0
for i in range(n):
solution+=(ans[i]*arr[i])
print(solution)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Bad Luck Island is inhabited by three kinds of species: *r* rocks, *s* scissors and *p* papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
|
```python
n = int(input())
a = [i for i in range(1, 2 * n + 1)]
b = [0] * (n * 2 + 1)
cnt = 0
for _ in range(n):
x, y = map(int, input().split())
a[x - 1], a[y - 1] = a[y - 1], a[x - 1]
def merge(l, mid, r):
i, j, k = l, mid + 1, l
while i <= mid and j <= r:
if a[i] <= a[j]:
b[k] = a[i]
i += 1
else:
b[k] = a[j] # 存在逆序对
j += 1
global cnt
cnt += mid - i + 1
k += 1
while i <= mid or j <= r: # 归并到b中
if i <= mid:
b[k] = a[i]
i += 1
else:
b[k] = a[j]
j += 1
k += 1
a[l:r + 1] = b[l:r + 1] # 合并
def merge_sort(l, r):
if l >= r:return
mid = l + r >> 1
merge_sort(l, mid)
merge_sort(mid + 1, r)
merge(l, mid, r)
merge_sort(0, n * 2 - 1)
print(cnt)
# n = int(input())
# a = [i for i in range(1, 2 * n + 1)]
# b = [0] * (n * 2 + 1)
# cnt = 0
# for _ in range(n):
# x, y = map(int, input().split())
# a[x - 1], a[y - 1] = a[y - 1], a[x - 1]
#
# def merge(l, mid, r):
# i, j, k = l, mid + 1, l
# while i <= mid and j <= r:
# if a[i] <= a[j]: # 小于填到b中
# b[k] = a[i]
# i += 1
# else:
# b[k] = a[j] # 存在逆序对
# j += 1
# global cnt
# cnt += mid - i + 1 # 计入答案
# k += 1
# b[k:k + mid + 1 - i] = a[i:mid + 1] # 合并
# b[k:k + r + 1 - j] = a[j:r + 1]
# a[l:r + 1] = b[l:r + 1]
#
# def merge_sort(l, r):
# if l >= r: return
# mid = l + r >> 1
# merge_sort(l, mid)
# merge_sort(mid + 1, r)
# merge(l, mid, r)
# merge_sort(0, n * 2 - 1)
# print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number *n*.
The presenter has *m* chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number *i* gets *i* chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given *n* and *m* how many chips the presenter will get in the end.
|
```python
n,m=input("").split(" ")
n=int(n);m=int(m)
m%=(n*(n+1)/2)
for i in range(1,n+1):
if(m<i):
break;
m -= i
print(int(m))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.
Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the *i*-th safe from the left is called safe *i*. There are *n* banknotes left in all the safes in total. The *i*-th banknote is in safe *x**i*. Oleg is now at safe *a*. There are two security guards, one of which guards the safe *b* such that *b*<=<<=*a*, i.e. the first guard is to the left of Oleg. The other guard guards the safe *c* so that *c*<=><=*a*, i.e. he is to the right of Oleg.
The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.
|
```python
a,b,c=list(map(int,input().split()))
n=int(input())
ed=sorted(list(map(int,input().split())))
say=0
bas=0
t=0
son=len(ed)
for i in range(n):
if ed[i]==b:
bas=i
if ed[i]==c:
son=i
if ed[i]==a:
t=i
if a>b and a<c:
for i in ed[bas:son]:
if i!=b and i!=c:
say+=1
elif a<b:
for i in ed[bas:son]:
if i!=b and i!=c:
say+=1
elif a>c:
for i in ed[bas:son]:
if i!=b and i!=c:
say+=1
print(say)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump.
Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability.
The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.
|
```python
#https://codeforces.com/problemset/problem/733/A
a = input()
vow = ["A","E","I","O","U","Y"]
mind = 1
cdist= 1
if (all(map(lambda x: x not in vow, a))):
print(len(a)+1)
else:
for x in a:
if x not in vow:
cdist+=1
else:
if mind<cdist:
mind = cdist
cdist=1
print(mind)
```
|
|
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
from collections import *
import sys
input=sys.stdin.readline
# "". join(strings)
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
n = ri()
if n % 2 == 0:
print(n // 2 * n)
for i in range(n):
if i % 2 == 0:
print("C."*(n//2))
else:
print(".C"*(n//2))
if n % 2 == 1:
k = n // 2 # n = 2*k + 1
print((k+1)**2 + k**2)
for i in range(n):
if i % 2 == 0:
print("C."*k + "C")
else:
print(".C"*k + ".")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
def too_long(n):
if len(n)>0 and len(n)<=100:
f=n[0]
l=n[-1]
m=n[1:-1]
b=len(m)
print(f"{f}{b}{l}")
n=input()
too_long(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0.
It is allowed to leave *a* as it is.
|
```python
a=sorted(input())
b=int(input())
a=a[::-1]
p=""
while a:
for i, z in enumerate(a):
n=p+a[i]+"".join(sorted(a[:i]+a[i+1:]))
if int(n)<=b:
p+=z
a.pop(i)
break
print(p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are *n* showplaces in the city, numbered from 1 to *n*, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.
Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace *n*. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than *T* time units.
Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace *n* within a time not exceeding *T*. It is guaranteed that there is at least one route from showplace 1 to showplace *n* such that Irina will spend no more than *T* time units passing it.
|
```python
# n,m,T=map(int, input().split())
# d={i:[] for i in range(n)}
# for i in range(m):
# a,b,t=map(int, input().split())
# a-=1 ; b-=1
# d[a].append([b,t])
# dp=[[[float('inf'),-1] for _ in range(n)] for _ in range(n)]
# dp[0][0]=[0,-1]
# q=[0]
# while q:
# q1=[]
# for node in q:
# for child, t in d[node]:
# for count in range(1,n):
# if dp[child][count][0]>dp[node][count-1][0]+t:
# dp[child][count][0] = dp[node][count-1][0]+t
# dp[child][count][1] = node
# q1.append(child)
# q=q1
# # print(dp[n-1])
# ans=-1
# for i in range(n):
# if dp[n-1][i][0]<=T:
# ans=i
# l=[]
# node=n-1
# for i in range(ans,-1,-1):
# l.append(node+1)
# node=dp[node][i][1]
# l=l[::-1]
# print(ans+1)
# print(*l)
n, m, T = map(int, input().split())
adj = [[] for _ in range(n+1)]
adw = [[] for _ in range(n+1)]
dp = [[0 for _ in range(n+1)] for _ in range(n+1)]
pv = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(m):
a, b, t = map(int, input().split())
adj[b].append(a)
adw[b].append(t)
if a == 1:
dp[b][2] = t
pv[b][2] = 1
for c in range(3, n+1):
for v in range(2, n+1):
for i, nx in enumerate(adj[v]):
if dp[nx][c-1]:
dist = dp[nx][c-1] + adw[v][i]
if dist <= T and (not dp[v][c] or dist < dp[v][c]):
dp[v][c] = dist
pv[v][c] = nx
for i in range(n,0,-1):
if pv[n][i]:
break
res = [n]
while pv[res[-1]][i] != 1:
res.append(pv[res[-1]][i])
i -= 1
res += [1]
print(len(res))
print(' '.join(map(str, res[::-1])))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
|
```python
n = int(input())
a = list(map(int, input().split()))
c = len(set(a))
was = set()
ans = -1
for i in a[::-1]:
if i not in was:
was.add(i)
ans = i
if len(was) == c:
print(ans)
exit()
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
|
```python
n=int(input());
l1=[];l2=[];l3=[];
sum1=0;sum2=0;sum3=0;
l1 = list(map(int, input().split()))
sum1=sum(l1);
l2 = list(map(int, input().split()))
sum2=sum(l2);
l3 = list(map(int, input().split()))
sum3=sum(l3);
print(abs(sum1-sum2))
print(abs(sum2-sum3))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, *m* icons can fit in a horizontal row in any window.
Igor K.'s computer contains *n* folders in the D: disk's root catalog. The folders are numbered from 1 to *n* in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from *a* to *b* inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from *a* to *b* and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
|
```python
'''input
20 5 2 20
'''
from sys import stdin
import math
# main starts
n, m, a, b = list(map(int, stdin.readline().split()))
if n < m:
print(1)
exit()
upper = math.ceil(a / m)
lower = math.ceil(b / m)
count = 0
if (upper - 1) * m + 1 == a:
pass
else:
count += 1
if (lower)* m == b:
pass
else:
count += 1
if upper + 1 <= lower - 1:
count += 1
print(count)
```
|
|
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
def rounding(num):
num=str(num)
v=num
rounddown=["1","2","3","4","5"]
roundup=["6","7","8","9"]
if num[-1]=="0":
return(num)
elif num[-1] in rounddown:
return(num[:-1:]+"0")
elif num[-1] in roundup:
return(num[:-2:]+str(int(v[-2])+2)+"0")
a=int(input())
print(rounding(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.
You are given a string *s* consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.
A substring of a string is a nonempty sequence of consecutive characters.
For example if string *s* is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
```python
count = 0
x = input()
for i in range(len(x)-1):
z = x[i:i+2]
if int(z)%4 == 0:
count += i+1
for j in range(len(x)):
if x[j] in ['0', '4', '8']:
count+= 1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result.
Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
|
```python
n=int(input())
s=input()
c0=0
c1=0
for i in s:
if i=='0':
c0+=1
c1=n-c0
ans=abs(c1-c0)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A frog lives on the axis *Ox* and needs to reach home which is in the point *n*. She starts from the point 1. The frog can jump to the right at a distance not more than *d*. So, after she jumped from the point *x* she can reach the point *x*<=+<=*a*, where *a* is an integer from 1 to *d*.
For each point from 1 to *n* is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and *n*.
Determine the minimal number of jumps that the frog needs to reach home which is in the point *n* from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
|
```python
from sys import stdin
n,d=map(int,stdin.readline().split())
s=input()
last=0
jump=0
while last!=n-1:
for i in range(n-1,last,-1):
if s[i]=='1':
if i-last<=d:
last=i
jump+=1
break
if jump==0:
break
print(jump if jump>0 else -1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya has *n* integers: 1,<=2,<=3,<=...,<=*n*. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.
Help Petya to split the integers. Each of *n* integers should be exactly in one group.
|
```python
n = int(input())
if n % 4 == 0:
print(0)
ans = []
x = 1
for i in range(n // 4):
ans.append(x)
ans.append(n + 1 - x)
x += 1
print(len(ans), *ans)
elif n % 4 == 1:
x = 2
ans = []
print(1)
for i in range(n // 4):
ans.append(x)
ans.append(n + 1 - x)
x += 1
print(len(ans), *ans)
elif n % 4 == 2:
x = 3
ans = [2]
print(1)
for i in range(n // 4):
ans.append(x)
ans.append(n + 1 - x)
x += 1
print(len(ans), *ans)
else:
print(0)
x = 2
ans = [3]
print(1)
for i in range(n // 4):
ans.append(x)
ans.append(n + 1 - x)
x += 1
print(len(ans), *ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
|
```python
string = input()
res = 0
for i in range(len(string)):
if string[i] == 'A':
res += (string[:i].count('Q') * string[i:].count('Q'))
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
On the planet Mars a year lasts exactly *n* days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
|
```python
q=int(input())
if q==1 or q==6:
print(0,1)
elif q%7==0:
print(q//7*2,q//7*2)
elif q<7:
print(0,0)
elif q%7==6:
print(q//7*2+1,q//7*2+2)
elif q%7>2:
print(q//7*2,q//7*2+2)
else:
print(q//7*2,q//7*2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*s**p*2... *s**p**k* (1 <=≤<= *p*1<=<<=*p*2<=<<=...<=<<=*p**k* <=≤<= |*s*|) a subsequence of string *s* = *s*1*s*2... *s*|*s*|, where |*s*| is the length of string *s*. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String *x* = *x*1*x*2... *x*|*x*| is lexicographically larger than string *y* = *y*1*y*2... *y*|*y*| if either |*x*| > |*y*| and *x*1<==<=*y*1, *x*2<==<=*y*2, ...,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=<<=|*x*|, *r*<=<<=|*y*|) that *x*1<==<=*y*1, *x*2<==<=*y*2, ..., *x**r*<==<=*y**r* and *x**r*<=<=+<=<=1<=><=*y**r*<=<=+<=<=1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String *s* = *s*1*s*2... *s*|*s*| is a palindrome if it matches string *rev*(*s*) = *s*|*s*|*s*|*s*|<=-<=1... *s*1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
|
```python
s=input()
p=''
k=max(s)
for i in range(len(s)):
if(s[i]==k):
p+=s[i]
i+=1
print(p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than *n* matchboxes so that the total amount of matches in them is maximal.
|
```python
n,m=map(int,input().split(" "))
list=[]
for i in range (m):
temp_list=[int(k) for k in input().split()]
for j in range(temp_list[0]):
list.append(temp_list[1])
list.sort(reverse=True)
print(list)
sum=0
for k in range(n):
sum+=int(list[k])
print(sum,end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to *n* computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.
Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to *n*. So the *i*-th hacked computer is located at the point *x**i*. Moreover the coordinates of all computers are distinct.
Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.
Leha should calculate a sum of *F*(*a*) for all *a*, where *a* is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote *A* the set of all integers from 1 to *n*. Noora asks the hacker to find value of the expression . Here *F*(*a*) is calculated as the maximum among the distances between all pairs of computers from the set *a*. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109<=+<=7.
Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
|
```python
import math
n = int(input())
s = list(map(int, input().split()))
s = list(sorted(s, reverse = True))
res = 0
for i in range(0, len(s)-1):
for j in range(i+1, len(s)):
res = res + (s[i] - s[j])*int(math.pow(2,(j-i-1)))
print(res % 1000000007)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!
There are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.
Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
|
```python
n = int(input())
ans = 1
lst = list(map(int, input().split()))
for it in lst:
ans = ans * it
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?
|
```python
n = int(input())
cnt = 0
a = list(map(int, input().split()))
for i in range(len(a)):
if (sum(a) - a[i]) % 2 == 0:
cnt = cnt + 1
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with *k* vertices and *k*<=-<=1 edges, where *k* is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to *n*. For each Ball *i* we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
|
```python
from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addedge(self,u,v):
self.graph[u].append(v)
self.graph[v].append(u)
def dfs(self,s):
stack=[]
stack.append(s)
#print(self.visited)
while len(stack)!=0:
a=stack[-1]
#print(a,self.visited,s)
#print(stack)
stack.pop()
if(self.visited[a]==False):
#print(a)
self.visited[a]=True
for node in self.graph[a]:
if(self.visited[node]==False):
stack.append(node)
return
def dfsutill(self):
l=list(self.graph.keys())
self.visited=[False for i in range(len(l)+1)]
#print(self.visited)
#print(l)
c=0
for v in l:
if(self.visited[v]==False):
c+=1
self.dfs(v)
#print(self.visited)
return c
n=int(input())
l=list(map(int,input().split()))
g=Graph()
for i in range(1,n+1):
g.addedge(i,l[i-1])
print(g.dfsutill())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu".
Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something!
Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.
|
```python
s = list(input())
out = [s[0]]
for i in range(1, len(s)):
if len(out) > 0 and s[i] == out[-1]:
out.pop()
else:
out.append(s[i])
print(''.join(out))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (*l* — left, *s* — straight, *r* — right) and a light *p* for a pedestrian crossing.
An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.
Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.
|
```python
matrix = [list(map(int, input().split())) for _ in range(4)]
p1 = any([matrix[0][1], matrix[0][2], matrix[0][0], matrix[1][0], matrix[2][1], matrix[3][2]])
p2 = any([matrix[0][2], matrix[1][0], matrix[1][2], matrix[1][1], matrix[2][0], matrix[3][1]])
p3 = any([matrix[0][1], matrix[1][2], matrix[2][0], matrix[2][1], matrix[2][2], matrix[3][0]])
p4 = any([matrix[0][0], matrix[1][1], matrix[2][2], matrix[3][0], matrix[3][1], matrix[3][2]])
if (matrix[0][3] and p1) or (matrix[1][3] and p2) or (matrix[2][3] and p3) or (matrix[3][3] and p4):
print('Yes')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.
|
```python
def pashmak_and_garden():
points = [int(point) for point in input().split()]
conj_points = (points[0] == points[2]) or (points[1] == points[3])
diff = [points[i] - points[i+2] for i in range(2)]
print(diff)
unique_diff = list(set(diff))
nunique_diff = len(unique_diff)
if (nunique_diff == 1):
other_points = [str(points[0]), str(points[1] - unique_diff[0]), str(points[0] - unique_diff[0]), str(points[1])]
print(" ".join(other_points))
elif (conj_points):
other_points = [[points[i]+diff[i-1], points[i+2]+diff[i-1]] for i in range(2)]
other_points = [str(point[0]) for point in other_points] + [str(point[1]) for point in other_points]
print(" ".join(other_points))
else:
print(-1)
pashmak_and_garden()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little penguin Polo has an *n*<=×<=*m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a**ij*.
In one move the penguin can add or subtract number *d* from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
|
```python
n, m, d = map(int, input().split())
a = []
for i in range(n):
a += list(map(int, input().split()))
a = sorted(a)
mod = a[0] % d
piv = a[(n*m)//2]
ans = 0
for i in range(n*m):
if a[i] % d != mod:
print(-1)
break
ans += abs(a[i]-piv) // d
else:
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
|
```python
num = int(input())
time = 0
while num > 0:
for i in range(5,0,-1):
if (num-i) >= 0:
num -= i
time += 1
break
print(time)
```
|
|
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
a = input()
b = input()
t1 = list(a)
t2 = list(b)
ans = ''
for i in range(len(t1)):
if(t1[i] != t2[i]):
ans += '1'
else:
ans += '0'
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Xenia the beginner programmer has a sequence *a*, consisting of 2*n* non-negative integers: *a*1,<=*a*2,<=...,<=*a*2*n*. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value *v* for *a*.
Namely, it takes several iterations to calculate value *v*. At the first iteration, Xenia writes a new sequence *a*1 *or* *a*2,<=*a*3 *or* *a*4,<=...,<=*a*2*n*<=-<=1 *or* *a*2*n*, consisting of 2*n*<=-<=1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence *a*. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is *v*.
Let's consider an example. Suppose that sequence *a*<==<=(1,<=2,<=3,<=4). Then let's write down all the transformations (1,<=2,<=3,<=4) <=→<= (1 *or* 2<==<=3,<=3 *or* 4<==<=7) <=→<= (3 *xor* 7<==<=4). The result is *v*<==<=4.
You are given Xenia's initial sequence. But to calculate value *v* for a given sequence would be too easy, so you are given additional *m* queries. Each query is a pair of integers *p*,<=*b*. Query *p*,<=*b* means that you need to perform the assignment *a**p*<==<=*b*. After each query, you need to print the new value *v* for the new sequence *a*.
|
```python
#IXABO
import sys
LINES = sys.stdin.read().splitlines()[::-1]
input = lambda: LINES.pop()
def get_list_of_ints():
return list(map(lambda x: int(x), input().split()))
def get_tree_index(n, i):
return 2 ** n - 2 + i
def set_op_value(tree, i, parity):
if parity % 2:
tree[i] = tree[2 * (i + 1) - 1] ^ tree[2 * (i + 1)]
else:
tree[i] = tree[2 * (i + 1) - 1] | tree[2 * (i + 1)]
def update_tree(tree, n, query):
p, b = query
start = get_tree_index(n, p)
tree[start] = b
i = int((start - 1) / 2)
parity = 0
while True:
set_op_value(tree, i, parity)
if i == 0:
break
i = int((i - 1) / 2)
parity += 1
def create_tree(n, a):
tree = [0] * (2 ** n - 1) + a
level = n - 1
while True:
i = 2 ** level - 1
parity = n - level + 1
while i < 2 ** (level + 1) - 1:
set_op_value(tree, i, parity)
i += 1
if level == 0:
break
level -= 1
return tree
if __name__ == '__main__':
n, m = get_list_of_ints()
a = get_list_of_ints()
queries = []
for i in range(0, m):
queries.append(get_list_of_ints())
tree = create_tree(n, a)
for q in queries:
update_tree(tree, n, q)
print(tree[0])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
|
```python
def shops(n, prices, q, money):
s = []
for i in range(q):
d = 0
for j in range(n):
if prices[j] <= money[i]:
d += 1
s.append(d)
return s
n = int(input())
prices = list(map(int, input().split()))
q = int(input())
money = [int(input()) for _ in range(q)]
a = shops(n, prices, q, money)
for i in a:
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink.
|
```python
input()
a = input().split()
summ = 0
for i in range(len(a)):
summ += int(a[i])
print(round(summ / len(a)), 10)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.
For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.
Write a program that will print the name of a man who will drink the *n*-th can.
Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
|
```python
import math
from collections import OrderedDict
from collections import Counter
from itertools import combinations
from itertools import accumulate
import operator
import bisect
import copy
#a= list(map(int, input("").strip().split()))[:n]
'''
def solve(a,x):
t=int(input(""))
for _ in range(t):
n,x= list(map(int, input("").strip().split()))[:2]
a= list(map(int, input("").strip().split()))[:n]
solve(a,x)
'''
def solve(n):
d={0:"Sheldon",1:"Leonard",2:"Penny",3:"Rajesh",4:"Howard"}
while n>4:
n=(n-5)//2
print(d[n])
n=int(input(""))
solve(n-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence *p*1,<=*p*2,<=...,<=*p**n* for his birthday.
Jeff hates inversions in sequences. An inversion in sequence *a*1,<=*a*2,<=...,<=*a**n* is a pair of indexes *i*,<=*j* (1<=≤<=*i*<=<<=*j*<=≤<=*n*), such that an inequality *a**i*<=><=*a**j* holds.
Jeff can multiply some numbers of the sequence *p* by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
|
```python
n = int(input())
sequence = list(map(int, input().split()))
inversions = 0
for i in range(n):
for j in range(i + 1, n):
if sequence[i] > sequence[j]:
inversions += 1
print(inversions)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly *n*1 balls and second player's box contains exactly *n*2 balls. In one move first player can take from 1 to *k*1 balls from his box and throw them away. Similarly, the second player can take from 1 to *k*2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
|
```python
def mod():
a=int(input())
b=int(input())
c=int(input())
d=int(input())
if a+c>b+d:
print("frist")
else:
print("second")
mod()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
|
```python
n=int(input())
notes = list(map(int,input().split()))
print((min(notes),-1)[min(notes)==1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 12 14:41:22 2021
@author: lcarv
"""
m = {}
l = []
n = int(input())
for i in range(n):
s = str(input())
l.append(s)
m[s] = 0
for j in range(n-1, -1, -1):
k = l[j]
if m[k] == 0:
print(k)
m[k] = 1
```
|
|
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())
t = 0
for i in range(n+1):
if i % 2 == 0:
t += i
else:
t -= i
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
|
```python
def haiku(line):
vowel = 'aiueo'
count = 0
for i in line:
if i in vowel:
count = count + 1
return count
first = input().lower()
second = input().lower()
third = input().lower()
if haiku(first) == 5 and haiku(second) == 7 and haiku(third) == 5:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*?
|
```python
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 11 16:51:30 2022
@author: 帝落梦魂
"""
t = int(input())
for i in range(0,t):
a = int(input())
if 360%(180-a)==0:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.
You are given a string *s*. Check if the string is "s-palindrome".
|
```python
[print("TAK" if [s[i]+s[-1-i] in "AA.HH.II.MM.OO.oo.TT.UU.VV.vv.WW.ww.XX.xx.YY.bd.db.pq.qp" for i in range(len(s))]==[True]*len(s) else "NIE") for s in [(input())]]
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.
Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.
The profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\max\limits_{l \le i \le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.
You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.
For example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$.
|
```python
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = a.copy()
b.sort()
sum_ = 0
j = n - k
b = b[j: n]
for i in range(n - j):
sum_ += b[i]
count = 0
ans = []
for i in range(n):
if a[i] in b:
j = b.index(a[i])
b.pop(j)
if len(b) == 0:
ans.append(str(abs(count - n)))
else:
ans.append(str(abs(count - i - 1)))
count = i + 1
s_ans = ' '.join(ans)
print(sum_)
print(s_ans)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task:
An expression of counting sticks is an expression of type:
Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if *A*<=+<=*B*<==<=*C*.
We've got an expression that looks like *A*<=+<=*B*<==<=*C* given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.
We really aren't fabulous at arithmetics. Can you help us?
|
```python
s=input()
a,b=s.split('+')
b,c=b.split('=')
a=list(a)
b=list(b)
c=list(c)
if len(a)+len(b)==len(c):
stp=''
for i in a:
stp=stp+i
stp=stp+'+'
for i in b:
stp=stp+i
stp=stp+'='
for i in c:
stp=stp+i
elif len(a)+len(b)<len(c):
i=0
while(i<4):
if i==0:
a.remove('|')
c.append('|')
if len(a)+len(b)==len(c):
break
else:
a.append('|')
c.remove('|')
i=i+1
elif i==1:
b.remove('|')
c.append('|')
if len(a)+len(b)==len(c):
break
else:
b.append('|')
c.remove('|')
i=i+1
elif i==2:
c.remove('|')
a.append('|')
if len(a)+len(b)==len(c):
break
else:
c.append('|')
a.remove('|')
i=i+1
elif i==3:
c.remove('|')
b.append('|')
if len(a)+len(b)==len(c):
break
else:
c.append('|')
b.remove('|')
i=i+1
else:
i=i+1
stp=''
for i in a:
stp=stp+i
stp=stp+'+'
for i in b:
stp=stp+i
stp=stp+'='
for i in c:
stp=stp+i
else:
i=0
while(i<4):
if i==0:
a.remove('|')
c.append('|')
if len(a)+len(b)==len(c):
break
else:
a.append('|')
c.remove('|')
i=i+1
elif i==1:
b.remove('|')
c.append('|')
if len(a)+len(b)==len(c):
break
else:
b.append('|')
c.remove('|')
i=i+1
elif i==2:
c.remove('|')
a.append('|')
if len(a)+len(b)==len(c):
break
else:
c.append('|')
a.remove('|')
i=i+1
elif i==3:
c.remove('|')
b.append('|')
if len(a)+len(b)==len(c):
break
else:
c.append('|')
b.remove('|')
i=i+1
else:
i=i+1
stp=''
for i in a:
stp=stp+i
stp=stp+'+'
for i in b:
stp=stp+i
stp=stp+'='
for i in c:
stp=stp+i
if len(a)+len(b)==len(c):
print(stp)
else:
print('Impossible')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with *n* vertices and *m* edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
|
```python
class Graph:
def __init__(self, edges, a):
# Adjacency list representation
self.adjacencyList = [[] for _ in range(a)]
for (source, destination) in edges:
print(source,destination)
self.adjacencyList[source].append(destination)
self.adjacencyList[destination].append(source)
# Function for DFS_Traversal traversal
def DFS_Traversal(graph, v, visited, parent_node=-1):
# assign current node as
visited[v] = True
# loop for every edge (v, u)
for u in graph.adjacencyList[v]:
# if `u` is not visited
if not visited[u]:
if DFS_Traversal(graph, u, visited, v):
return True
# if `u` is visited, and `u` is not a parent_node
elif u != parent_node:
# found a back-edge
return True
# No back-edges were found
return False
n,m=map(int,input().split())
"""
n = 6
m = 6
data = [
"6 3",
"6 4",
"5 1",
"2 5",
"1 4",
"5 4",
]
"""
edges = []
for i in range(m):
a,b=map(int,input().split())
#a,b=map(int,data[i].split(' '))
#g.addEdge(a, b)
edges.append((a-1,b-1))
constructed_graph = Graph(edges, n)
# note the visited and unvisited nodes
visited = [False] * n
if DFS_Traversal(constructed_graph, 0, visited):
print("FHTAGN!")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky.
|
```python
n=int(input())
if n%10==4 or n%10==7 or n%4==0 or n%7==0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.
As before, the chessboard is a square-checkered board with the squares arranged in a 8<=×<=8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.
Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.
It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
|
```python
def solve():
row_list = []
col_list = []
for i in range(8):
row = input()
row_list.append(row)
for j in range(8):
l = ''
for row in chessboard_list1:
l += row[j]
col_list.append(l)
r_count = row_list.count('BBBBBBBB')
if r_count == 8:
print(8)
else:
sum = r_count + chessboard_list2.count('BBBBBBBB')
print(sum)
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" $\rightarrow$ "100210"; - "010210" $\rightarrow$ "001210"; - "010210" $\rightarrow$ "010120"; - "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
|
```python
s = input()
oneCnt = s.count('1')
sNo1s = s.replace('1','')
oneStr = '1' * oneCnt
first2 = sNo1s.find('2')
if first2 < 0:
print(sNo1s + oneStr)
else:
print(sNo1s[:first2] + oneStr + sNo1s[first2:])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).
You've got some number of pairs (*a**i*,<=*b**i*). How many operations will be performed for each of them?
|
```python
n=int(input())
for i in range(n):
ans=0
x,y=map(int,input().split())
if(y>x):
x,y=y,x
while(y>0):
ans+=x//y
x=x%y
x,y=y,x
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence *a*1,<=*a*2,<=...,<=*a**n* of length *n*. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A subsegment is a contiguous slice of the whole sequence. For example, {3,<=4,<=5} and {1} are subsegments of sequence {1,<=2,<=3,<=4,<=5,<=6}, while {1,<=2,<=4} and {7} are not.
|
```python
n = int(input())
data = list(map(int, input().split()))
if n % 2 == 1 and data[0] % 2 == 1 and data[-1] % 2 == 1:
print("Yes")
else:
print("No")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now *n* people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code *a**i* is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city *x*, then all people who are going to city *x* should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city *x*, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position *l* to position *r* is equal to XOR of all distinct codes of cities for people on the segment from position *l* to position *r*. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
|
```python
def dp(curi):
global cache
try:
return cache[curi]
except KeyError:
if curi >= len(sections):
cache[curi] = 0
else:
_, curend, curcomfort = sections[curi]
nextsection = curi + 1
try:
while sections[nextsection][0] <= curend:
nextsection += 1
except IndexError:
# Loop til end
inc = curcomfort
else:
inc = curcomfort + dp(nextsection)
exc = dp(curi + 1)
cache[curi] = max(inc, exc)
return cache[curi]
n = int(input())
zs = list(map(int, input().split()))
sections = []
seenstartz = set()
first = {z: i for i, z in reversed(list(enumerate(zs)))}
last = {z: i for i, z in enumerate(zs)}
for start, z in enumerate(zs):
if z in seenstartz:
continue
end = last[z]
comfort = z
seen = set([z])
i = start + 1
while i <= end:
if zs[i] not in seen:
seen.add(zs[i])
comfort ^= zs[i]
end = max(end, last[zs[i]])
i += 1
sections.append((start, end, comfort))
seenstartz.add(z)
cache = {}
ans = dp(0)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.
After practice competition, participant number *i* got a score of *a**i*. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.
|
```python
import math
A = list(map(int,input().split()))
for i in range(len(A)):
A[i]=math.fabs(A[i])
A.sort()
cmnd1=A[0]+A[3]
cmnd2=A[1]+A[2]
if(cmnd1>cmnd2):
cmnd1+=A[4]
cmnd2+=A[5]
else:
cmnd1+=A[5]
cmnd2+=A[4]
if(cmnd1==cmnd2):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5.
Formally, Alyona wants to count the number of pairs of integers (*x*,<=*y*) such that 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* and equals 0.
As usual, Alyona has some troubles and asks you to help.
|
```python
if __name__ == '__main__':
A = list(map(int, input().split()))
n = A[0]
m = A[1]
first = max(n, m)
second = min(n, m)
totaldevisors = 0
for i in range(5):
if i != 0:
totaldevisors += ((second + 5 - i) // 5) * ((first + i) // 5)
else:
totaldevisors += (((second + 5 - i) // 5) - 1) * ((first + i) // 5)
print(totaldevisors)
```
|
|
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
word = input().lower()
word = word[word.find('h'):]
#print(word)
if len(word[1:word.find('e')]) == 1 and word[1:word.find('e')] == 'h':
word = word[0]+word[2:]
else:
word = word.replace(word[1:word.find('e')],'')
#print(word)
if len(word[2:word.find('l')]) ==1 and word[2:word.find('l')] == 'e':
word = word[0:2] + word[3:]
else:
word = word.replace(word[2:word.find('l')],'')
#print(word)
wordd = word[:2]+word[3:]
if len(wordd)<4:
print('NO')
else:
if wordd[2] == 'l':
if len(word[4:word.find('o')]) == 1 and word[4:word.find('o')] == 'l':
word = word[:4]+word[5]
else:
word = word[:4]+word[word.find('o')]
# print(word)
else:
word = word.replace(word[3:wordd.find('l')+1],'')
if len(word[4:word.find('o')]) == 1 and word[4:word.find('o')] == 'l':
word = word[:4]+word[word.find('o')]
else:
word = word.replace(word[4:word.find('o')],'')
word = word[:5]
# print(word)
if word == 'hello':
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.
The total income *A* of his kingdom during 0-th year is known, as well as the total income *B* during *n*-th year (these numbers can be negative — it means that there was a loss in the correspondent year).
King wants to show financial stability. To do this, he needs to find common coefficient *X* — the coefficient of income growth during one year. This coefficient should satisfy the equation:
Surely, the king is not going to do this job by himself, and demands you to find such number *X*.
It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient *X* must be integers. The number *X* may be zero or negative.
|
```python
import math
# import sys
def cal(q,a,b,n):
if q*a==b:
h=math.pow(q,1/n)
h=int(h)
print(q,h**n)
if q==h**n:
# print('helkjl')
return h,True
return 0,False
a=0
b=0
n=10
ab=False
if a==0:
# print('no solution')
ab=False
# sys.exit(0)
if (a==0 and b==0 or b==0 and a>0):
ab=True
x=0
# print(0)
# sys.exit(0)
if a!=0:
q=int(math.fabs(b//a))
if a>0 and b>0:
f=cal(q,a,b,n)
x=f[0]
elif a<0:
# print('kldk')
if b<0:
f= cal(q,a,b,n)
else:
if n&1==1:
# print('kdk')
f=cal(q,-a,b,n)
x=-f[0]
# print(q,a,b,n)
elif b>0:
if a<0:
f= cal(q,a,b,n)
else:
if n&1==1:
f=cal(q,a,-b,n)
x=-f[0]
if ab or f[1] :
print(x)
else:
print(f[1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Given a positive integer *n*, find *k* integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to *n*.
|
```python
n,k=map(int,input().split())
l=[]
for i in range(2,n+1):
if n%i==0:
while n%i==0 and len(l)<(k-1):
n//=i
l.append(i)
if n>1:
l.append(n)
if len(l)==k:
print(*l)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.
We know that the *i*-th star on the pedal axle has *a**i* (0<=<<=*a*1<=<<=*a*2<=<<=...<=<<=*a**n*) teeth, and the *j*-th star on the rear wheel axle has *b**j* (0<=<<=*b*1<=<<=*b*2<=<<=...<=<<=*b**m*) teeth. Any pair (*i*,<=*j*) (1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (*i*,<=*j*) has a gear ratio, equal to the value .
Since Vasya likes integers, he wants to find such gears (*i*,<=*j*), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (*i*,<=*j*) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.
In the problem, fraction denotes division in real numbers, that is, no rounding is performed.
|
```python
n = int(input())
starsPedal = list(map(int, input().split()))
m = int(input())
starsRear = list(map(int, input().split()))
maxVal = -1
totalGears = 0
for i in range(n):
for j in range(m):
if starsRear[j] % starsPedal[i] == 0:
if starsRear[j]//starsPedal[i] == maxVal:
totalGears += 1
elif starsRear[j]//starsPedal[i] > maxVal:
maxVal = starsRear[j]//starsPedal[i]
totalGears = 1
print(totalGears)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer *n* is decided first. Both Koyomi and Karen independently choose *n* distinct positive integers, denoted by *x*1,<=*x*2,<=...,<=*x**n* and *y*1,<=*y*2,<=...,<=*y**n* respectively. They reveal their sequences, and repeat until all of 2*n* integers become distinct, which is the only final state to be kept and considered.
Then they count the number of ordered pairs (*i*,<=*j*) (1<=≤<=*i*,<=*j*<=≤<=*n*) such that the value *x**i* xor *y**j* equals to one of the 2*n* integers. Here xor means the [bitwise exclusive or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.
Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.
|
```python
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
i=0
count=0
while i<n:
j = i
while j<n:
z = x[i] ^ y[j]
if z in x or z in y:
count+=1
j+=1
i+=1
if count%2==0:
print("Karen")
else:
print("Koyomi")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got *n* positive integers. He wonders, how many of those integers have not more than *k* lucky digits? Help him, write the program that solves the problem.
|
```python
x,y=map(int,input().split(' ',1))
array=list(map(int,input().split(' ')))
lucky=[4,7]
count=0
for i in array:
kk1=0
num=str(i)
for x in range(len(num)):
if int(num[x]) in lucky:
kk1+=1
if kk1<=y:
count+=1
print(count)
# if num[x] in lucky:
# k+=1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) и 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "ВSCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.
Polycarpus has *n**b* pieces of bread, *n**s* pieces of sausage and *n**c* pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are *p**b* rubles for a piece of bread, *p**s* for a piece of sausage and *p**c* for a piece of cheese.
Polycarpus has *r* rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.
|
```python
import sys
input=sys.stdin.readline
m=1000000007
#------------------------------------#
recipe=input()
B=recipe.count("B")
S=recipe.count("S")
C=recipe.count("C")
nb,ns,nc=map(int,input().split())
pb,ps,pc=map(int,input().split())
r=int(input())
count=0
if B==0:
nb=float("inf")
B=1
pb=0
if C==0:
nc=float("inf")
C=1
pc=0
if S==0:
ns=float("inf")
S=1
ps=0
if nb//B and ns//S and nc//C:
#atleast 1 sandwich can made without buying
count+=min(nb//B,ns//S,nc//C)
nb-=count*B
ns-=count*S
nc-=count*C
#using all existing ingredients
if nb//B and ns//S:
#C not there
cost=pc*(C*min(nb//B,ns//S)-nc)
if cost<r:
r=r-cost
count+=min(nb//B,ns//S)
nc=0
nb-=B*min(nb//B,ns//S)
ns-=S*min(nb//B,ns//S)
else:
count+=(r+nc*pc)//(pc*C)
print(count)
exit()
if nc//C and ns//S:
#B not there
cost=pb*(B*min(nc//C,ns//S)-nb)
if cost<r:
r=r-cost
count+=min(nb//B,ns//S)
nb=0
nc-=C*min(nc//C,ns//S)
ns-=S*min(nb//B,ns//S)
else:
count+=(r+nb*pb)//(pb*B)
print(count)
exit()
if nb//B and nc//C:
#S not there
cost=ps(S*min(nc//C,nb//B)-ns)
if cost<r:
r=r-cost
count+=min(nc//C,nb//B)
ns=0
nb-=B*min(nc//C,nb//B)
ns-=S*min(nc//C,nb//B)
else:
count+=(r+ns*ps)//(ps*S)
print(count)
exit()
if nb//B:
#S and C not there
cost=ps*(S*(nb//B)-ns)+pc*(C*(nb//B)-nc)
if r>cost:
r=r-cost
count+=nb//B
ns=0
nc=0
nb-=B*(nb//B)
else:
cost=ps*(S-ns)+pc*(C-nc)
if r>cost:
count+=1
r=r-cost
count+=r//(ps*S+pc*C)
print(count)
exit()
else:
print(count)
exit()
if ns//S:
#B and C not there
cost=pb*(B*(ns//S)-nb)+pc*(C*(ns//S)-nc)
if r>cost:
r=r-cost
count+=ns//S
nb=0
nc=0
ns-=S*(ns//S)
else:
cost=pb*(S-nb)+pc*(C-nc)
if r>cost:
count+=1
r=r-cost
count+=r//(pb*B+pc*C)
print(count)
else:
print(count)
exit()
if nc//C:
#B and S not there
cost=pb*(B*(nc//C)-nb)+ps*(S*(nc//C)-ns)
if r>cost:
r=r-cost
count+=nc//C
nb=0
nc-=nc//C
ns=0
else:
cost=pb*(S-nb)+ps*(S-ns)
if r>cost:
count+=1
r=r-cost
count+=r//(pb*B+ps*S)
print(count)
else:
print(count)
exit()
cost=(B-nb)*pb+(C-nc)*pc+(S-ns)*ps
if cost>r:
print(count)
else:
r=r-cost
count+=1
count+=r//(pb*B+ps*S+pc*C)
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are *n* planes on Earth, numbered from 1 to *n*, and the plane with number *i* likes the plane with number *f**i*, where 1<=≤<=*f**i*<=≤<=*n* and *f**i*<=≠<=*i*.
We call a love triangle a situation in which plane *A* likes plane *B*, plane *B* likes plane *C* and plane *C* likes plane *A*. Find out if there is any love triangle on Earth.
|
```python
def soln(inp):
lines = inp.strip('\n').split('\n')[:-1]
# print(lines)
output_string=""
for line in lines[1:]:
# print("---",line)
line_split=line.split()
elm = 1
len_line = len(line_split)
sign_flag=True
one_flag=False
# if line_split[0]=="0":
# # one_flag=True
# sign_flag=not sign_flag
for i in range(len_line-2):
elm=i+1
el=elm
for i in range(3):
el=int(line_split[el-1])
if el==elm:
print("YES")
return None
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
|
```python
import math
def solve():
garbo = input()
numbers = input().split()
new = []
for number in numbers:
new.append(int(number))
new = sorted(new)
largest = 0
for number in new:
if math.sqrt(number) % 1 == 0:
pass
else:
largest = number
print(largest)
# print(new)
# for _ in range(int(input())):
solve()
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.