source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.
An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
|
```python
import sys
import math
from collections import Counter
input = sys.stdin.readline
N = 1000000007
#use input().strip()
def multiply(a, b):
mul = [[0 for x in range(2)]
for y in range(2)]
for i in range(2):
for j in range(2):
for k in range(2):
mul[i][j] += a[i][k] * b[k][j]
for i in range(2):
for j in range(2):
a[i][j] = mul[i][j]
return a
def power(F, n):
M = [[2, 3], [1, 0]]
if (n == 1):
return F[0][0]
power(F, int(n / 2))
F = multiply(F, F)
if (n % 2 != 0):
F = multiply(F, M)
return F[0][0]
n = int(input().strip())
if n == 1:
print(0)
elif n == 2:
print(3)
else:
a = [[2, 3], [1, 0]]
x = power(a, n - 2)
print((x * 3) % N)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
|
```python
x,y = input().split()
x = int(x)
y = int(y)
o = list(map(int, input().split()))
p = list(map(int, input().split()))
o.sort()
p.sort()
a = len(o)
b = len(p)
i = 0
j = 0
while(i < a):
while(j < b):
if(o[i] == p[j]):
print(o[i])
break
else:
j = j+1
i = i+1
if(o[0] > p[0]):
e = (p[0] * 10)+o[0]
print(e)
else:
e = (o[0] * 10)+ p[0]
print(e)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly *x* Roman soldiers, where *x* is a prime number, and next day they beat exactly *y* Roman soldiers, where *y* is the next prime number after *x*, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat *n* Roman soldiers and it turned out that the number *n* was prime! Today their victims were a troop of *m* Romans (*m*<=><=*n*). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
|
```python
def isPrime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to n-1
for i in range(2, n):
if (n % i == 0):
return False
return True
a=[int(i) for i in input().split()]
primes=[]
for i in range(a[0],a[1]+1):
primes.append(isPrime(i))
if sum(primes)==2:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp watched TV-show where *k* jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the *i*-th jury member gave *a**i* points.
Polycarp does not remember how many points the participant had before this *k* marks were given, but he remembers that among the scores announced after each of the *k* judges rated the participant there were *n* (*n*<=≤<=*k*) values *b*1,<=*b*2,<=...,<=*b**n* (it is guaranteed that all values *b**j* are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. *n*<=<<=*k*. Note that the initial score wasn't announced.
Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
|
```python
# Jury Marks
k, n = list(map(int, input().split(' ')))
jury_marks = list(map(int, input().split(' ')))
poly_marks = list(map(int, input().split(' ')))
potential = set()
current = poly_marks[0]
for mark in jury_marks:
current += -1 * mark
potential.add(current)
count = 0
for num in potential:
all_vals = set()
current = num
for mark in jury_marks:
current += mark
all_vals.add(current)
# print(all_vals, poly_marks)
for mark in poly_marks:
if not mark in all_vals:
break
else:
count += 1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to *n*.
It is known that during the day *q* tasks will come, the *i*-th of them is characterized with three integers: *t**i* — the moment in seconds in which the task will come, *k**i* — the number of servers needed to perform it, and *d**i* — the time needed to perform this task in seconds. All *t**i* are distinct.
To perform the *i*-th task you need *k**i* servers which are unoccupied in the second *t**i*. After the servers begin to perform the task, each of them will be busy over the next *d**i* seconds. Thus, they will be busy in seconds *t**i*,<=*t**i*<=+<=1,<=...,<=*t**i*<=+<=*d**i*<=-<=1. For performing the task, *k**i* servers with the smallest ids will be chosen from all the unoccupied servers. If in the second *t**i* there are not enough unoccupied servers, the task is ignored.
Write the program that determines which tasks will be performed and which will be ignored.
|
```python
def main():
n, k = map(int, input().split())
ser = [0] * n
for i in range(k):
t, ki, v = map(int, input().split())
ans = 0
for el in ser:
if el < t:
ans += 1
if ans > ki: break
if ans >= ki:
ans = 0
j = 0
while ki > 0:
if ser[j] < t:
ser[j] = t + v - 1
ki -= 1
ans += (j+1)
j += 1
print(ans)
else:
print(-1)
ans = 0
return 0
main()
```
|
|
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
|
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least *k* people must work in the store.
Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly *n* consecutive days, then rest for exactly *m* days, then work for *n* more days and rest for *m* more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day *x*, then he should work on days [*x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*n*<=-<=1], [*x*<=+<=*m*<=+<=*n*,<=*x*<=+<=*m*<=+<=*n*<=+<=1,<=...,<=*x*<=+<=*m*<=+<=2*n*<=-<=1], and so on. Day *x* can be chosen arbitrarily by Vitaly.
There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.
Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least *k* working employees, and one of the working employees should have the key to the store.
Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.
|
```python
n,m,k = map(int,input().split())
ans = [1 for i in range(k)]
transition = True
for i in range(n-1, n+m):
if transition:
if ans[-k]+n == i+1:
ans.append(i)
if k > 1:
transition = False
else:
if ans[-k]+n == i:
ans.extend([i]*(max(1, k-1)))
transition = True
print(*ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently *n* students from city S moved to city P to attend a programming camp.
They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.
*i*-th student comes to the end of the queue at the beginning of *l**i*-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of *r**i*-th second student *i* still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea.
For each student determine the second he will use the teapot and get his tea (if he actually gets it).
|
```python
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
g = [list(map(int, input().split())) for _ in range(n)]
d = []
c = 1
x = 0
for i in range(n):
if g[i][0] - x >= c:
d.append(g[i][0])
c = g[i][0] + 1
else:
c += 1
if g[i][1] <= c:
d.append(0)
else:
d.append(g[i][0]+c-x)
c -= 1
x = g[i][0]
print(*d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String *t* is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.
You are given some integer number *x*. Check if it's a quasi-palindromic number.
|
```python
a=input()
i=len(a)-1
while(a[i]=='0'):i-=1
if a[:i+1]==a[len(a)-i+1::-1]:print("YES")
else:print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([[email protected]](/cdn-cgi/l/email-protection)).
It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots.
You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result.
Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.
|
```python
email = input()
idx_at = email.index("at")
idx_dot = email.index("dot")
print(email[0:idx_at] + "@" + email[idx_at+2:idx_dot] + "." + email[idx_dot+3:len(email)])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
|
```python
ballons, friends = map(int, input().split())
color = input()
lencolor = len(color)
x = 0
count = [0] * 26 # букв всего 26б значит и индекс не мсжет быть болше 26
# tkcb кол-во одного цвета больше чем друзейб кто-то получит два одного цвета
for i in color:
nomer = ord(i) - 97
count[nomer] += 1 # индексы плюсуются
for i in range(26):
if count[i] > friends:
# print(chr(i + 97), count[i])
# elif count[i] > friends:
x += 1
if x > 0:
print('NO')
else:
print('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The child will follow the algorithm:
- If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great. - If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).
You are given a multiple-choice questions, can you predict child's choose?
|
```python
a=input()
b=input()
c=input()
d=input()
if((len(a)-2)>=(len(b)-2)*2 and (len(a)-2)>=(len(c)-2)*2 and (len(a)-2)>=(len(d)-2)*2):
print("A")
elif((len(b)-2)>=(len(a)-2)*2 and (len(b)-2)>=(len(c)-2)*2 and (len(b)-2)>=(len(d)-2)*2):
print("B")
elif((len(d)-2)>=(len(b)-2)*2 and (len(d)-2)>=(len(c)-2)*2 and (len(d)-2)>=(len(a)-2)*2):
print("D")
elif((len(a)-2)*2<len(b)-2 and (len(a)-2)*2<len(c)-2 and (len(a)-2)*2<len(d)-2):
print("A")
elif((len(b)-2)*2<len(a)-2 and (len(b)-2)*2<len(c)-2 and (len(b)-2)*2<len(d)-2):
print("B")
elif((len(d)-2)*2<len(b)-2 and (len(d)-2)*2<len(c)-2 and (len(d)-2)*2<len(a)-2):
print("D")
else:
print("C")
```
|
|
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
#556A - Case of the Zeros and Ones
x,s=int(input()),input()
print(abs(s.count("0")-s.count("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())
first = list(map(int , input().split()))
m = int(input())
second = list(map(int , input().split()))
maximum = 0
count = 0
for i in first:
for j in second:
if j%i == 0:
temp = j%i
if temp > maximum:
maximum = temp
count = 1
elif temp == maximum:
count += 1
else:
break
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.
The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2.
Diameter of multiset consisting of one point is 0.
You are given *n* points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed *d*?
|
```python
# http://codeforces.com/contest/940/problem/A
import sys
n_and_d = sys.stdin.readline()
tmp = n_and_d.split(' ')
n = int(tmp[0])
d = int(tmp[1])
l = sys.stdin.readline().strip().split(' ')
l = [int(l[i]) for i in range(0, n)]
l.sort()
min = n
for i in range(0, n):
upper_bound_value = l[i] + d
upper_bound_index = i
while upper_bound_index + 1 < n and l[upper_bound_index + 1] <= upper_bound_value:
upper_bound_index += 1
tmp = n - 1 - upper_bound_index + i;
if tmp < min:
min = tmp
print(min)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
|
```python
na, nb = map(int, input().split(" "))
ma, mb = map(int, input().split(" "))
LA = [int(x) for x in input().split()]
LA.sort()
LB = [int(x) for x in input().split()]
LB.sort()
if (LA[ma - 1] < LB[nb - mb]): print("YES")
else : print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
```python
n, m = map(int, input().split(" "))
graph = dict()
for i in range(m):
s1, s2 = map(str, input().split(" "))
graph[s1] = s2
s = list(input().split(" "))
for i in range(len(s)):
if len(s[i]) > len(graph[s[i]]):
s[i] = graph[s[i]]
print(" ".join(s))
```
|
|
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
a = list(map(int, input().split()))
for i in range(4):
for j in range(i + 1, 5):
for k in range(j + 1, 6):
if 2 * (a[i] + a[j] + a[k]) == sum(a):
print('YES')
exit()
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.
On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.
Determine the index of day when Polycarp will celebrate the equator.
|
```python
a= array('i',[])
sum1 = 0
sm = 0
n= int(input())
for i in range(n):
x=int(input())
a.append(x)
for l in a:
sum1=sum1+l
sum1=(sum1/2)
val=0
for m in a:
sm=sm+m
if(sm>=sum1):
break
else:
val=val+1
print(val+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.
Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1<=×<=5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:
As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.
|
```python
size = int(input())
number_section = list(map(int,input().split()))
counter=1
#find max
maximum =0
index_max=-1
for x in range(size):
if number_section[x]>maximum:
maximum=number_section[x]
index_max=x
if index_max==0:
#go right -->
for x in range(size-1):
if number_section[x+1]>number_section[x]:
break
counter+=1
elif index_max==size-1:
#go left <---
for x in range(size-1,0,-1):
if number_section[x-1]>number_section[x]:
break
counter+=1
else:
for x in range(index_max,0,-1):
if number_section[x-1]>number_section[x]:
break
counter+=1
for x in range(index_max,size-1):
if number_section[x+1]>number_section[x]:
break
counter+=1
print(counter)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Shaass has *n* books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the *i*-th book is *t**i* and its pages' width is equal to *w**i*. The thickness of each book is either 1 or 2. All books have the same page heights.
Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.
Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
|
```python
n = int(input())
dif=[]
li1=[]
li2=[]
a1=b1=0
#print(lis)
for i in range(n):
a,b=map(int,input().split())
if a==1:
li1.append(b)
else:
li2.append(b)
li1.sort(reverse=True)
li2.sort(reverse=True)
l1=len(li1)
l2=len(li2)
ans=10000000000
for i in range(l1):
for j in range(l2):
s=0
for k in range(i,l1):
s+=li1[k]
for k in range(j,l2):
s+=li2[k]
if i+2*j>=s:
ans=min(ans,i+2*j)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
|
```python
n=int(input())
x=[]
y=list(input().split())
for i in y:
m=0
for j in i:
if 65<=ord(j)<=90:
m+=1
x.append(m)
print(max(x))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete *k*<=-<=1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.
Overall, Dima has *n* tasks to do, each task has a unique number from 1 to *n*. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.
Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
|
```python
import sys
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7
n, k = rinput()
a = get_list()
ans = []
for i in range(k):
l = a[i::k]
ans.append([i+1, sum(l)])
ans.sort(key=lambda x:x[1])
print(ans[0][0])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
N = int(input())
aA = [0] * 3
for i in range(N):
bB = [int(x) for x in input().split()]
for j in range(3):
aA[j] += bB[j]
res = [x for x in aA if x == 0]
print('YES' if len(res) == 3 else 'NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers *a*1,<=*a*2,<=...,<=*a**n* of length *n*, that the following condition fulfills:
For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.
Alexander has *n* cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting *n*<=+<=1 cards to make an arithmetic progression (Alexander has to use all of his cards).
Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.
|
```python
n=int(input())
a=sorted(map(int,input().split()))
if (n<2):
print(-1)
else:
count={}
I=range(n-1)
for i in I:
d=a[i+1]-a[i]
count[d]=count.get(d,0)+1
d=min(count)
if( count[d]<n-2):
print(0)
else:
b=set()
if( count[d]+1==n):
b.add(a[0]*2-a[1])
b.add(a[-1]*2-a[-2])
for i in I:
e=a[i+1]-a[i]
if(not (e%2==0)):
f=e/2
count[f]=count.get(f,0)+2
count[e]-=1
if(count[min(d,f)]==n):
b.add(a[i]+f)
count[e]+=1
count[f]-=2
print(len(b))
print(' '.join(map(str,sorted(b))))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
```python
n = int(input())
arr = list(map(int,input().split(' ')))
if n == 1:
summary = arr[0]
elif n == 2:
summary = max(arr[0],arr[1])
else:
summary = 0
for i in range(1,n-1):
if arr[i] >= arr[i-1] + arr[i+1]:
summary += arr[i]
arr[i-1] = 0
arr[i+1] = 0
summary += arr[-1]
summary += arr[0]
print(summary)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*).
|
```python
a,b=map(int,input().split())
l=[]
for i in range(a):
l.append(input())
for j in l:
x=0
for i in range(b+1):
if str(i) not in j:
x=1
if x!=1:
c=c+1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:
- overall, there must be *m* dances;- exactly three people must take part in each dance;- each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland).
The agency has *n* dancers, and their number can be less than 3*m*. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance.
You considered all the criteria and made the plan for the *m* dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the *n* dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
|
```python
n,m=map(int,input().split())
lst=[0 for i in range(n+1)]
for j in range(m):
dancers=list(map(int,input().split()))
color=[lst[dancers[0]],lst[dancers[1]],lst[dancers[2]]]
for i in range(3):
if(lst[dancers[i]]!=0):
continue
else:
if(1 not in color):
lst[dancers[i]]=1
color[i]=1
continue
if(2 not in color):
lst[dancers[i]]=2
color[i]=2
continue
if(3 not in color):
lst[dancers[i]]=3
color[i]=3
for k in range(1,n+1):
print(lst[k],end=' ')
```
|
|
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
def check(w):
dirw = {}
dirh = {}
hello = "hello"
for i in w:
if i not in dirw:
dirw[i] = 0
dirw[i] += 1
for i in hello:
if i not in dirh:
dirh[i] = 0
dirh[i] += 1
l = []
for k,v in dirh.items():
if k in dirw:
l.append(v == dirw[k])
if len(l)!=4:
return "NO"
for a in l:
if not a:
return "YES"
return "NO"
word = input()
print(check(word))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed *k* hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.
Vasya has a train lighting schedule for all *n* hours of the trip — *n* numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose *k* hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.
|
```python
f = open("input.txt", "r")
n, k = map(int, f.readline().split())
a, b = list(zip(*sorted(zip(map(int, f.readline().split()), range(1,n+1)))))
f = open("output.txt", "w")
print(a[n-k], file=f)
print(' '.join(map(str, b[n-k:])), file=f)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
|
```python
n=int(input())
d={}
t={}
turn=0
while(n):
a=input().split()
if(a[0] not in d):
d[a[0]]=[]
t[a[0]]=[]
d[a[0]].append(int(a[1]))
turn+=1
t[a[0]].append(turn)
n-=1
maxm=-1
for i in d:
maxm=max(maxm, sum(d[i]))
c={}
for i in d:
if(sum(d[i])==maxm):
c[i]=d[i]
e={}
for i in c:
sums=0
for j in range(len(c[i])):
sums+=c[i][j]
if(sums>=maxm):
# e[i]=j
e[i]=t[i][j]
break
# print(e)
minm=min(e.values())
for k in e:
if(e[k]==minm):
print(k)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
def f(a, b):
if a % b == 0:return a // b
else:return a // b + 1
n, m, k = map(int, input().split())
first = f(n, k)
scond = f(m, k)
print(first * scond)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.
The park consists of 2*n*<=+<=1<=-<=1 squares connected by roads so that the scheme of the park is a full binary tree of depth *n*. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2*n*,<=2*n*<=+<=1,<=...,<=2*n*<=+<=1<=-<=1 and these exits lead straight to the Om Nom friends' houses. From each square *i* (2<=≤<=*i*<=<<=2*n*<=+<=1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly *n* roads.
Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.
He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
|
```python
n = int(input())
edge = 0
depth = 1
for _ in range(n):
depth *= 2
edge += depth
lights = list(map(int, input().split()))
total = 0
while depth > 1:
size = len(lights)
for i in range(depth // 2):
a = lights.pop()
b = lights.pop()
MAX = max(a, b)
MIN = min(a, b)
total += (MAX - MIN)
if depth > 2:
lights[size - 1 - depth - i] += MAX
depth //= 2
print(total)# 1690902702.5500932
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have *a* nuts and lots of boxes. The boxes have a wonderful feature: if you put *x* (*x*<=≥<=0) divisors (the spacial bars that can divide a box) to it, you get a box, divided into *x*<=+<=1 sections.
You are minimalist. Therefore, on the one hand, you are against dividing some box into more than *k* sections. On the other hand, you are against putting more than *v* nuts into some section of the box. What is the minimum number of boxes you have to use if you want to put all the nuts in boxes, and you have *b* divisors?
Please note that you need to minimize the number of used boxes, not sections. You do not have to minimize the number of used divisors.
|
```python
k,a,d,v=map(int,input().split())
s=0
m=round(d/k)
s+=m
a-=v*m*k
d-=(k-1)*m
if d:
s+=1
a-=(d+1)*v
if a>0 and a%v==0:s+=a//v
elif a>0 and a%v!=0:s+=a//v+1
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mike has a string *s* consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.
|
```python
s = list(input())
f = s[0:len(s)//2]
ss = s.copy()
ss.reverse()
s.reverse()
f1 = s[0:len(s)//2]
c = 0
for i in range(len(f)):
if f[i] != f1[i]:
c += 1
print("YES" if c == 1 or ss == s else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the *Ox* axis is directed rightwards in the city's direction, the *Oy* axis is directed upwards (to the sky). The cannon will make *n* more shots. The cannon balls' initial speeds are the same in all the shots and are equal to *V*, so that every shot is characterized by only one number *alpha**i* which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (π<=/<=4). We disregard the cannon sizes and consider the firing made from the point (0,<=0).
The balls fly according to the known physical laws of a body thrown towards the horizon at an angle:
Think of the acceleration of gravity *g* as equal to 9.8.
Bertown defends *m* walls. The *i*-th wall is represented as a vertical segment (*x**i*,<=0)<=-<=(*x**i*,<=*y**i*). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (*y*<==<=0) and stops. If the ball exactly hits the point (*x**i*,<=*y**i*), it is considered stuck.
Your task is to find for each ball the coordinates of the point where it will be located in the end.
|
```python
print("_RANDOM_GUESS_1689432413.4650924")# 1689432413.4651115
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
|
```python
n1, n2 = [int(x) for x in input().split()]
k, m = [int(x) for x in input().split()]
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]
max_in_l1 = sorted(l1)[k-1]
min_in_l2 = sorted(l2)[0]
if max_in_l1 < min_in_l2:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive.
|
```python
n = int(input())
count = 0
final_count = 0
prime_count = 0
for i in range(1, n+1):
for j in range(1, i + 1):
prime_count = 0
for k in range(1, j+1):
if j % k == 0:
prime_count += 1
if prime_count == 2:
if i % j == 0:
count += 1
if count == 2:
final_count += 1
count = 0
print(final_count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The prison of your city has *n* prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer *c* of the prisoners to a prison located in another city.
For this reason, he made the *n* prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.
Then, the mayor told you to choose the *c* prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,
- The chosen *c* prisoners has to form a contiguous segment of prisoners. - Any of the chosen prisoner's crime level should not be greater then *t*. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.
Find the number of ways you can choose the *c* prisoners.
|
```python
n, t, c = map(int, input().split())
count = 0
current_count = 0
for i in range(n):
x = int(input())
if x <= t:
current_count += 1
else:
if current_count >= c:
count += current_count - (c-1)
current_count = 0
if current_count >= c:
count += current_count - (c-1)
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
- There are *n* knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won — the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*.
Write the code that calculates for each knight, the name of the knight that beat him.
|
```python
n,m = [int(i) for i in input().split(' ')]
result = [0]*n
for _ in range(m):
l,r,x = [int(i) for i in input().split(' ')]
participantes = list(range(l-1,r))
participantes.remove(x-1)
for i in participantes:
if result[i] == 0:
result[i] = x
print(" ".join([str(i) for i in result]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n=int(input())
a=list(map(int,input().split()))
e=o=0
for i in range(n):
if a[i]%2==0:
e+=1
res1=i+1
else:
o+=1
res2=i+1
if e>o:
print(res2)
else:
print(res1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly *n* houses in Ultimate Thule, Vova wants the city to have exactly *n* pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters.
A splitter is a construction that consists of one input (it can be connected to a water pipe) and *x* output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe.
Vova has one splitter of each kind: with 2, 3, 4, ..., *k* outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible.
Vova needs the pipeline to have exactly *n* pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.
|
```python
n, k = [int(i) for i in input().split(' ')]
if n <= k:
print(1)
exit()
t = 1
s = k
count = 0
while t < n and s >= 2:
#print(t, s)
t = t - 1 + s
s -= 1
if n - t < s:
s = n - t + 1
count += 1
#print(t, s, count)
if t != n:
print(-1)
exit()
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of *s*.
|
```python
n = int(input())
s = input()
s = [int(i) if int(i) > 0 else -1 for i in s]
cnt = 0
for length in range(2, n):
for pos in range(0, n-1-length):
if sum(s[pos:pos+length]) == 0 :
cnt = length
else :
continue
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasily has a number *a*, which he wants to turn into a number *b*. For this purpose, he can do two types of operations:
- multiply the current number by 2 (that is, replace the number *x* by 2·*x*); - append the digit 1 to the right of current number (that is, replace the number *x* by 10·*x*<=+<=1).
You need to help Vasily to transform the number *a* into the number *b* using only the operations described above, or find that it is impossible.
Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform *a* into *b*.
|
```python
a,b=map(int,input().split())
l=[b]
while(a<b):
if b%2:
if b%10==1:
b//=10
l.append(b)
else:
break
else:
b//=2
l.append(b)
if a==b:print("YES");print(len(l));print(*l[::-1])
else:print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
|
```python
s1=0
s2=0
o1=0
o2=0
for _ in range (int(input())):
n1,n2=map(int,input().split())
s1+=n1
s2+=n2
if(n1%2!=0 and n2%2==0):
o1+=1
if(n1%2!=0 and n2%2==0):
o2+=1
if(s1%2==0 and s2%2==0):
print(0)
elif(s1%2!=0 and s2%2==0):
print(-1)
elif(s1%2==0 and s2%2!=0):
print(-1)
elif(s1%2!=0 and s2%2!=0):
if(o1>0 or o2>0):
print(1)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
|
```python
a = input()
c = ["a","e","o","y","u","i"]
a = a.lower()
for i in a:
if i in c:
a = a.replace(i,"")
else:
a= a.replace(i,f".{i}")
print(a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
s=input()
t=input()
s_r=""
for i in s:
s_r=i+s_r
if(s_r==t):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* boys and *m* girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to *n*<=+<=*m*. Then the number of integers *i* (1<=≤<=*i*<=<<=*n*<=+<=*m*) such that positions with indexes *i* and *i*<=+<=1 contain children of different genders (position *i* has a girl and position *i*<=+<=1 has a boy or vice versa) must be as large as possible.
Help the children and tell them how to form the line.
|
```python
b, g = input().split()
b = int(b)
g = int(g)
result = []
numB = 0
numG = 0
x = 0
if b > g:
while numG < g:
if x % 2 == 0:
result.append("B")
numB += 1
else:
result.append('G')
numG += 1
x += 1
print(numG)
for y in range(b - numB):
result.append('B')
else:
while numB < b:
if x % 2 == 0:
result.append('G')
numG+= 1
else:
result.append('B')
numB += 1
x+=1
print(numB)
for y in range(g - numG):
result.append('G')
for i in result:
print(i, end = "")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
|
```python
# juntar em grupos onde é possível chegar de algum deles
# um grupo são elementos que um pode chegar em outro sem gastar snow drifts extras, ou seja, possui x ou y igual
# o valor final vai ser qtdGrupos - 1
n = int(input())
groups = []
for _ in range(n):
i, j = [int(k) for k in input().split(' ')]
hasGroup = False
for group in groups:
groupsX = group["x"]
groupsY = group["y"]
if groupsX.get(i) or groupsY.get(j):
groupsX[i] = True
groupsY[j] = True
hasGroup = True
if not hasGroup:
group = {}
group["x"] = {}
group["x"][i] = True
group["y"] = {}
group["y"][j] = True
groups.append(group)
print(len(groups) - 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
a, b = (int(s) for s in input().split())
if a == b:
print(0, 6, 0)
else:
m = a if a < b else b
n = b if b > a else a
if (m+n) % 2 == 0:
tie = (m + n) // 2
m_win = len(range(1, tie))
n_win = len(range(tie + 1, 7))
n_tie = 1
else:
l_tie = (m + n) // 2
m_win = len(range(1, l_tie + 1))
n_win = len(range(l_tie + 1, 7))
n_tie = 0
if a < b:
print (m_win, n_tie, n_win)
else:
print (n_win, n_tie, m_win)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a *n*<=×<=*n* checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
|
```python
n=int(input())
l1=[]
flag=0
for i in range(n):
l2=list(input())
l1.append(l2)
flag=0
for i in range(n):
for j in range(n):
c=0
if (i+1)<n:
if l1[i+1][j]=='o':
c+=1
if (i-1)>-1:
if l1[i-1][j]=='o':
c+=1
if (j+1)<n:
if l1[i][j+1]=='o':
c+=1
if (j-1)>-1:
if l1[i][j-1]=='o':
c+=1
if c%2==1:
flag=1
break
if flag==1:
break
if flag==1:
print("NO")
else :
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this.
In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
|
```python
# for _ in range(int(input())):
# n=int(input())
# x,y=map(int,input().split())
# a=list(map(int,input().split()))
s=input()
t=input()
s=[ord(s[0])-96,int(s[1])]
t=[ord(t[0])-96,int(t[1])]
ans=[]
# print(s,t)
if(s[0]==t[0] and s[1]==t[1]):
ans=[]
elif(s[0]==t[0]):
if(s[1]>t[1]):
ans=["L"]*(s[1]-t[1])
else:
ans=["U"]*(t[1]-s[1])
elif(t[1]==s[1]):
if(s[0]>t[0]):
ans=["R"]*(s[0]-t[0])
else:
ans=["L"]*(t[0]-s[0])
elif(s[0]<t[0]):
r=t[0]-s[0]
if(s[1]<t[1]):
u=t[1]-s[1]
m=min(r,u)
r-=m
u-=m
ans=["RU"]*m
if(r==0):
ans+=u*["U"]
else:
ans+=r*["R"]
else:
d=s[1]-t[1]
m=min(r,d)
r-=m
d-=m
ans=["RD"]*m
if(r==0):
ans+=d*["D"]
else:
ans+=r*["R"]
else:
r=s[0]-t[0]
if(s[1]<t[1]):
u=t[1]-s[1]
m=min(r,u)
r-=m
u-=m
ans=["LU"]*m
if(r==0):
ans+=u*["U"]
else:
ans+=r*["L"]
else:
d=s[1]-t[1]
m=min(r,d)
r-=m
d-=m
ans=["LD"]*m
if(r==0):
ans+=d*["D"]
else:
ans+=r*["L"]
print(len(ans))
for i in ans:
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if *n*<==<=3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
|
```python
n = int(input())
she = sorted([int(x) for x in list(input())])
mor = sorted([int(x) for x in list(input())])
i = j = 0
ans1 = n
while i < n:
while mor[j] < she[i] and j < n - 1:
j += 1
if mor[j] >= she[i]:
#print(j, i)
ans1 -= 1
if j == n - 1:
break
i += 1
i = j = ans2 = 0
while i < n:
while mor[j] <= she[i] and j < n - 1:
j += 1
if mor[j] > she[i]:
ans2 += 1
if j == n - 1:
break
i += 1
print(ans1, ans2, sep="\n")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it.
What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
|
```python
n, A, B = map(int, input().split())
x, *holes = (map(int, input().split()))
S = x + sum(holes)
holes.sort(reverse=True)
for i in range(n):
if x*A >= B*S:
break
else:
S -= holes[i]
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find the maximum possible least common multiple of these three integers?
|
```python
from math import *
def lcm(arr,idx):
if idx==len(arr)-1:
return arr[idx]
a=arr[idx]
b=lcm(arr,idx+1)
return ((a*b)//gcd(a,b))
n=int(input())
if n==1:
print(1)
elif n==2:
print(2)
else:
ans=n*(n-1)
for i in range(n-2,0,-1):
curr=lcm([n,n-1,i],0)
ans=max(ans,curr)
ans2=(n-1)*(n-2)
for i in range(n-3,0,-1):
curr=lcm([n-1,n-2,i],0)
ans2=max(ans2,curr)
print(max(ans,ans2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya likes to play very much. And most of all he likes to play the following game:
He is given a sequence of *N* integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.
The sequence *a* is called non-decreasing if *a*1<=≤<=*a*2<=≤<=...<=≤<=*a**N* holds, where *N* is the length of the sequence.
|
```python
# http://codeforces.com/problemset/problem/13/C
def min_steps(arr):
L = len(arr)
sorted_arr = sorted(arr)
dp = [[0] * L for _ in range(L)]
for i in range(L):
for j in range(L):
if i == j == 0:
dp[i][j] = abs(arr[0] - sorted_arr[0])
elif i == 0:
dp[i][j] = min(arr[i] - sorted_arr[j], dp[i][j - 1])
elif j == 0:
dp[i][j] = abs(arr[i] - sorted_arr[j]) + dp[i - 1][j]
else:
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j] + abs(arr[i] - sorted_arr[j]))
return min(dp[-1])
if __name__ == '__main__':
N = input()
arr = input().split(' ')
arr = [int(e) for e in arr]
print(min_steps(arr))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* people living in it and the room can accommodate *q**i* people in total (*p**i*<=≤<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.
|
```python
n = int(input())
c=0
for i in range(n):
p,q=map(int, input().split())
if((q-p)>=2):
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are *n* people in the queue. For each person we know time *t**i* needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
|
```python
n=int(input())
queue=list(map(int,input().split()))
queue.sort()
people=2
time=queue[0]+queue[1]
i=2
while i < n-1:
if time<=queue[i]:
people+=1
time+=queue[i]
i+=1
else:
j=i+1
while j<n:
if time<=queue[j]:
people+=1
for k in range(i,j+1):
time+=queue[k]
i=j+1
break
print(people)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals *d* centimeters. Initial level of water in cup equals *h* centimeters from the bottom.
You drink a water with a speed equals *v* milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on *e* centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
|
```python
import math
d, h, v, e = list(map(int, input().split()))
area = math.pi * d * d / 4
net = v / area - e
t = h / net
if t > 0.0001 and t < 10000:
print("YES")
print(t)
else:
print("NO")
```
|
|
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
# Read the user name
user_name = input()
# Count the number of distinct characters in the user name
distinct_characters = len(set(user_name))
# Check if the number of distinct characters is even
if distinct_characters % 2 == 0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
|
```python
from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
sum_a = sum(a)
if sum_a % 3 != 0:
print(0)
exit()
cnt = defaultdict(int)
p = [0] * n
p[0] = a[0]
cnt[p[0]] += 1
for i in range(1, n):
p[i] = p[i - 1] + a[i]
cnt[p[i]] += 1
print(cnt[sum_a // 3] * cnt[sum_a // 3 * 2])
```
|
|
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
def is_almost_lucky(n):
if n % 4 == 0 or n % 7 == 0:
return True
for i in range(1, n):
if (n - 4 * i) % 7 == 0:
return True
return False
n = int(input().strip())
if is_almost_lucky(n):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n* segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
|
```python
# Problem: D. Nested Segments
# Contest: Codeforces - Educational Codeforces Round 10
# URL: https://codeforces.com/problemset/problem/652/D
# Memory Limit: 256 MB
# Time Limit: 2000 ms
import sys
import bisect
import random
import io, os
from bisect import *
from collections import *
from contextlib import redirect_stdout
from itertools import *
from array import *
from functools import lru_cache
from types import GeneratorType
from heapq import *
from math import sqrt, gcd, inf
if sys.version >= '3.8': # ACW没有comb
from math import comb
RI = lambda: map(int, sys.stdin.buffer.readline().split())
RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())
RILST = lambda: list(RI())
DEBUG = lambda *x: sys.stderr.write(f'{str(x)}\n')
MOD = 10 ** 9 + 7
PROBLEM = """https://codeforces.com/problemset/problem/652/D
输入 n(≤2e5) 和 n 个闭区间,区间左右端点范围在 [-1e9,1e9],所有端点互不相同。
对每个区间,输出它包含多少个其它的区间。
输入
4
1 8
2 3
4 7
5 6
输出
3
0
1
0
输入
3
3 4
1 5
2 6
输出
0
1
1
"""
class SortedList:
def __init__(self, a=None):
self.small = []
self.big = [] if not a else a
def add(self, v):
if len(self.small) > 1000:
self.big += self.small
self.big.sort()
self.small.clear()
insort(self.small, v)
def __len__(self):
return len(self.small) + len(self.big)
def bisect_left(self, v):
return bisect_left(self.small, v) + bisect_left(self.big, v)
# ms
def solve():
n, = RI()
a = []
for i in range(n):
l, r = RI()
a.append((r, l, i))
a.sort()
p = SortedList()
ans = [0] * n
for r, l, i in a:
ans[i] = len(p) - p.bisect_left(l)
p.add(l)
print(*ans, sep='\n')
# ms
def solve1():
n, = RI()
a = []
hs = []
for _ in range(n):
l, r = RI()
hs.extend([l, r])
a.append((l, r))
a.sort(key=lambda x: x[1])
hs.sort()
if __name__ == '__main__':
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
|
```python
number = input()
T = 0
while len(number) > 1:
number = [int(i) for i in number]
number = str(sum(number))
T+=1
print(T)
```
|
|
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
#!/usr/bin/env python
# coding: utf-8
# In[18]:
#1A
numbers = "664"
square = (int(numbers[2]))
first = int(numbers[0])//square + 1
second = int(numbers[1])//square + 1
print(first*second)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* shovels in Polycarp's shop. The *i*-th shovel costs *i* burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.
Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines.
You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.
|
```python
s = input()
n = int(s)
num = '9'*len(s)
num = int(num)
if(2*n < num):
num = num // 10
ret = 0;
for i in range (9):
tmp = str(i) + str(num)
tmp = int(tmp);
if (2 * n <= tmp):
break;
biggest = min(tmp - 1, n);
smallest = tmp - biggest
ret += (biggest - smallest + 1) // 2
print(ret)
# else :
# biggest = min(num - 1, n);
# smallest = num - biggest
# print((biggest - smallest + 1) // 2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a *n*<=×<=*n* square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?
Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
|
```python
from math import comb
s = 0
a = []
for i in range(int(input())):
st = [c for c in input()]
s += comb(st.count('C'), 2)
a.append(st)
for t in zip(*a):
s += comb(t.count('C'), 2)
print(s)
##########################################
## ##
## Implemented by brownfox2k6 ##
## ##
##########################################
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Elephant loves magic squares very much.
A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15.
The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 105.
Help the Little Elephant, restore the original magic square, given the Elephant's notes.
|
```python
from math import *
from collections import *
from bisect import *
import math
def is_prime(n):
for i in range(2,math.ceil(math.sqrt(n))):
if(n%i==0):
return False
return True
def sieve(n):
arr=[True for _ in range(n+1)]
for i in range(2,math.ceil(math.sqrt(n))):
if(arr[i]==True):
for j in range(i*i,n+1,i):
arr[j]=False
return arr
def euclidean_distance(x1,y1,x2,y2):
return sqrt(abs(x1-x2)**2+abs(y1-y2)**2)
def solve():
# s=input()
# n=int(input())
# n,a,b=list(map(int,input().split()))
# k=int(input())-1
lis=[]
for _ in range(3):
lis.append(list(map(int,input().split())))
x=sum(lis[1])+sum(lis[2])-sum(lis[0])
y=sum(lis[0])+sum(lis[2])-sum(lis[1])
z=sum(lis[1])+sum(lis[0])-sum(lis[2])
lis[0][0]=x//2
lis[1][1]=y//2
lis[2][2]=z//2
for ele in lis:
print(*ele)
if __name__ == '__main__':
n=1
# n=int(input())
while(n):
n-=1
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of *n* intersections numbered from 1 to *n*. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number *i* to intersection *j* requires |*i*<=-<=*j*| units of energy. The total energy spent by Mike to visit a sequence of intersections *p*1<==<=1,<=*p*2,<=...,<=*p**k* is equal to units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly *n* shortcuts in Mike's city, the *i**th* of them allows walking from intersection *i* to intersection *a**i* (*i*<=≤<=*a**i*<=≤<=*a**i*<=+<=1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence *p*1<==<=1,<=*p*2,<=...,<=*p**k* then for each 1<=≤<=*i*<=<<=*k* satisfying *p**i*<=+<=1<==<=*a**p**i* and *a**p**i*<=≠<=*p**i* Mike will spend only 1 unit of energy instead of |*p**i*<=-<=*p**i*<=+<=1| walking from the intersection *p**i* to intersection *p**i*<=+<=1. For example, if Mike chooses a sequence *p*1<==<=1,<=*p*2<==<=*a**p*1,<=*p*3<==<=*a**p*2,<=...,<=*p**k*<==<=*a**p**k*<=-<=1, he spends exactly *k*<=-<=1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1<=≤<=*i*<=≤<=*n* Mike is interested in finding minimum possible total energy of some sequence *p*1<==<=1,<=*p*2,<=...,<=*p**k*<==<=*i*.
|
```python
def bfs(nCruzamentos, cruzamentos, aux, fila):
while len(fila) > 0:
atual = fila.pop(0)
if(atual < nCruzamentos and aux[atual + 1] > aux[atual] + 1):
aux[atual+1]=aux[atual]+1
fila.append(atual + 1)
if(atual > 1 and aux[atual - 1] > aux[atual]+1):
aux[atual - 1] = aux[atual] + 1
fila.append(atual - 1)
if(aux[ cruzamentos[atual] ] > aux[atual] + 1):
aux[cruzamentos[atual]] = aux[atual]+1
fila.append(cruzamentos[atual])
def mikeAndShortcuts(nCruzamentos, atalhos):
cruzamentos = [0] + [int(x) for x in atalhos]
aux = [float('inf') for x in range( nCruzamentos + 1 )]
aux[1] = 0
fila=[1]
bfs(nCruzamentos, cruzamentos, aux, fila)
print(' '.join(str(i) for i in aux[1:]))
nCruzamentos = int(input())
atalhos = input().split()
mikeAndShortcuts(nCruzamentos, atalhos)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
|
```python
x=int(input())
y=input()
z=input()
sum=0
for i in range(len(y)):
sum+=min(abs(int(y[i])-int(z[i])),10-abs(int(y[i])-int(z[i])))
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.
There are *n* video cards in the shop, the power of the *i*-th video card is equal to integer value *a**i*. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.
Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.
|
```python
n = int(input())
mas = [int(i) for i in input().split()]
nmax = 200001
p = [0] * (nmax + 1)
for i in range(n):
p[mas[i]] += 1
for i in range(1, nmax):
p[i] += p[i - 1]
ans = 0
for i in range(1, nmax + 1):
ma = 0
if p[i] - p[i - 1] == 0:
continue
for j in range(i, nmax - i + 1, i):
ma += j * (p[j + i - 1] - p[j - 1])
ans = max(ans, ma)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
|
```python
read=input()
counter=0
maxI=0
#print( read[i],read[i-1],maxI,i)
for i in range(len(read)-1):
if maxI==0:
counter+=1
if maxI==4 or read[i]!=read[i+1]:
maxI=0
else:
maxI+=1
i=len(read)-1
if read[i]!=read[i-1]:
counter+=1
elif maxI==0:
counter+=1
print(counter)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into *a* pieces, and the second one — into *b* pieces.
Ivan knows that there will be *n* people at the celebration (including himself), so Ivan has set *n* plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met:
1. Each piece of each cake is put on some plate; 1. Each plate contains at least one piece of cake; 1. No plate contains pieces of both cakes.
To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number *x* such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least *x* pieces of cake.
Help Ivan to calculate this number *x*!
|
```python
n, a , b = map ( int, input(). split())
for i in range(1, max ( a, b )):
if (a//i+b//i>=n):
continue
else:
break
print(i-1)
```
|
|
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
from math import ceil
lis = ["Sheldon", "Leonard", "Rajesh", "Howard", "Penny"]
nth = int(input())
nbf = nth/5
i = 0
j = 1
n = 0
while n<nbf:
n += j
j *= 2
i += 1
divisor = j/2
x = nth-((n-divisor)*5)
pos = x/divisor
print(lis[ceil(pos)-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least *k* walks for any two consecutive days in order to feel good. For example, if *k*<==<=5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next *n* days and made a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the number of times Polycarp will walk with the dog on the *i*-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next *n* days so that Cormen will feel good during all the *n* days. You can assume that on the day before the first day and on the day after the *n*-th day Polycarp will go for a walk with Cormen exactly *k* times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers *b*1,<=*b*2,<=...,<=*b**n* (*b**i*<=≥<=*a**i*), where *b**i* means the total number of walks with the dog on the *i*-th day.
|
```python
n,k=map(int,input().split())
l1=list(map(int,input().split()))
l2=[]
c=0
if(n%2==0):
i=0
while i<n:
if((l1[i]+l1[i+1])<k):
l2.append(l1[i])
l2.append(abs(l1[i]-k))
c=c+(abs((l1[i]+l1[i+1])-k))
i+=2
else:
l2.append(l1[i])
l2.append(l1[i+1])
i+=2
else:
i=0
while i<n-1:
if((l1[i]+l1[i+1])<k):
l2.append(l1[i])
l2.append(abs(l1[i]-k))
c=c+(abs((l1[i]+l1[i+1])-k))
i+=2
else:
l2.append(l1[i])
l2.append(l1[i+1])
i+=2
l2.append(l2[0])
c=c+abs(l1[-1]-l2[-1])
print(c)
print(*l2)
```
|
|
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 itertools as it
n = int(input())
l = [int(x) for x in input().split()]
l = [x for x in zip(l, range(n))]
odd = [x for x in l if x[0] % 2]
even = [x for x in l if x[0] % 2 == 0]
if len(odd) == 1:
print(odd[0][1] + 1)
else:
print(even[0][1] + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
|
```python
#!/usr/bin/python3
n = input()
a = sorted(map(int, input().split()))
for i in range(1, len(a)):
if a[i] != a[i - 1]:
print(a[i])
exit()
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Igor found out discounts in a shop and decided to buy *n* items. Discounts at the store will last for a week and Igor knows about each item that its price now is *a**i*, and after a week of discounts its price will be *b**i*.
Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.
Igor decided that buy at least *k* of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all *n* items.
|
```python
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
wynik = 0
lista = []
for x in range(n):
roznica = a[x] - b[x]
if roznica <= 0:
wynik = wynik + a[x]
k = k - 1
else:
lista.append(roznica)
lista.sort()
if k > 0:
for x in range(k):
lista.pop(0)
for x in range(n):
if a[x] - b[x] in lista:
wynik = wynik + b[x]
else:
wynik = wynik + a[x]
else:
for x in range(n):
if a[x] - b[x] in lista:
wynik = wynik + b[x]
print(wynik)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp studies at the university in the group which consists of *n* students (including himself). All they are registrated in the social net "TheContacnt!".
Not all students are equally sociable. About each student you know the value *a**i* — the maximum number of messages which the *i*-th student is agree to send per day. The student can't send messages to himself.
In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages.
Your task is to make a plan of using private messages, so that:
- the student *i* sends no more than *a**i* messages (for all *i* from 1 to *n*); - all students knew the news about the credit (initially only Polycarp knew it); - the student can inform the other student only if he knows it himself.
Let's consider that all students are numerated by distinct numbers from 1 to *n*, and Polycarp always has the number 1.
In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.
|
```python
n = int(input())
a = [[],[]]
a[0] = input()
a[0] = a[0].split(' ')
a[0] = list(map(int, a[0]))
count = 0
if a[0][0] != 0:
for i in range(len(a[0])):
a[1].append(0)
for i in range(len(a[0])):
user = i
for j in range(a[0][i]):
user+=1
if(user < len(a[1]) and a[1][user] != -1):
a[1][user] = -1
count +=1
print(' ', i + 1, user + 1)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals *n*. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position *a*1 to position *b*1, the second — from *a*2 to *b*2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
|
```python
# -*- coding: utf-8 -*-
n,x = map(int,input().split())
cont = []
for i in range(n):
a,b = map(int,input().split())
if x < min(a,b): cont.append(min(a,b) - x)
elif x > max(a,b): cont.append(x - max(a,b))
print(max(cont))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
|
```python
a, b = map(int, input().split())
max_diff_days = min(a, b)
remaining_socks = max(a, b) - max_diff_days
same_days = remaining_socks // 2
print(max_diff_days, same_days)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every *a*! years. Here *a*! denotes the factorial of integer *a*, that is, *a*!<==<=1<=×<=2<=×<=...<=×<=*a*. Specifically, 0!<==<=1.
Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of *b*! years, that is, . Note that when *b*<=≥<=*a* this value is always integer.
As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge.
|
```python
a,b=map(int,input().split())
f=1
r=0
if a==b:
print('1')
for i in range(a+1,b+1):
f*=i
r=f%10
if r==0:
print(0)
break;
if r!=0:
print(r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
|
```python
def check(n, m):
for i in range(n):
a = input()
if a.count('W') + a.count('G') + a.count('B') != m:
return '#Color'
return '#Black&White'
n, m = map(int, input().split())
print(check(n, m))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
|
```python
n=input().split(" ")
l=[]
c=0
for i in n:
if (int(i)) in l:
c=c+1
elif int(i) not in l:
l.append(int(i))
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer *x* and wants to get a number one from it. While *x* is not equal to 1, Fangy repeats the following action: if *x* is odd, then he adds 1 to it, otherwise he divides *x* by 2. Fangy knows that for any positive integer number the process ends in finite time.
How many actions should Fangy perform to get a number one from number *x*?
|
```python
import fileinput,sys
binary_int = int(fileinput.input().readline(),2)
num = 0
while binary_int != 1:
if binary_int%2==0:
binary_int = binary_int // 2
else:
binary_int = binary_int + 1
num += 1
print(num)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
|
```python
x = input()
print(len(x) * 25 + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains *n* sweet candies from the good ol' bakery, each labeled from 1 to *n* corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest ones — but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!
A xor-sum of a sequence of integers *a*1,<=*a*2,<=...,<=*a**m* is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found [here.](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)
Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than *k* candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.
|
```python
a,b=map(int,input().split());s=0;from math import*;k=floor(log2(a));print(a if b==1 else (1<<k)-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
import math
input = input().split(" ")
print(int(math.floor(int(input[0]) * int(input[1])) / 2))
```
|
|
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()
zeros = s.count('0')
ones = s.count('1')
print(abs(zeros - ones))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline *A*1*A*2... *A**n*. Scrooge signs like that: first it places a pen at the point *A*1, then draws a segment from point *A*1 to point *A*2, then he draws a segment from point *A*2 to point *A*3 and so on to point *A**n*, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.
Scrooge signed exactly *k* papers throughout his life and all those signatures look the same.
Find the total time Scrooge wasted signing the papers.
|
```python
n, k = map(int, input().split())
s = 0
x0, y0 = map(int, input().split())
for i in range(n - 1):
x, y = map(int, input().split())
s += ((x - x0) ** 2 + (y - y0) ** 2) ** (1 / 2)
x0, y0 = x, y
print(k * s / 50)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing *n* balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.
Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?
|
```python
n = int(input())
a = list(map(int, input().split()))
a.sort()
diff = [0 for i in range(0, 5001)]
dsm = [0 for i in range(0, 10001)]
for i in range(0, n):
for j in range(0, i):
diff[a[i] - a[j]] += 1
for i in range(1, 5001):
for j in range(1, 5001):
dsm[i + j] += diff[i]*diff[j]
for i in range(1, 10001):
dsm[i] += dsm[i - 1]
dp = [0 for i in range(0, n)]
ans = 0
for i in range(2, n):
for j in range(0, i):
dp[i] += dsm[a[i] - a[j] - 1]
ans += dp[i]
ans = 8*ans/(n*n*n*(n - 1)*(n - 1)*(n - 1))
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
```python
def bored(nums: list) -> int:
for i in range(1, len(nums)):
if i != 1:
nums[i] += nums[i-2]
nums[i] = max(nums[i], nums[i-1])
print(nums)
return nums[-1]
input()
print(bored(list(int(i) for i in input().split())))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record 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 mask of a positive integer *n* the number that is obtained after successive writing of all lucky digits of number *n* from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number.
Petya has two numbers — an arbitrary integer *a* and a lucky number *b*. Help him find the minimum number *c* (*c*<=><=*a*) such that the mask of number *c* equals *b*.
|
```python
a,b=map(str,input().split())
def mask(x):
st=''
for i in str(x):
if i=='7' or i=='4':
st+=i
return(st)
for i in range(int(a)+1,177778):
if mask(i)!=b:
pass
else:
print(i)
quit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
|
```python
ll=(list(map(int,input().split(' '))))
print(min(ll),abs(ll[1]-ll[0])//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
|
```python
import math, os, sys
import string, re
import itertools, functools, operator
from collections import Counter
def inputint():
return int(input())
def inputarray(func=int):
return map(func, input().split())
def ans(A, i, j):
if j - i == 1:
return A[i]
elif j - i == 2:
return 2*(A[i] + A[i + 1])
else:
m = i + (j - i)//2
return sum(A[i:j]) + ans(A, i, m) \
+ ans(A, m, j)
n = inputint()
A = sorted(inputarray())
print(ans(A, 0, len(A)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to *n*, - the password should consist only of lowercase Latin letters, - the number of distinct symbols in the password must be equal to *k*, - any two consecutive symbols in the password must be distinct.
Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.
|
```python
n, k = map(int, input().split())
abc = "abcdefghijklmnopqrstuvwxyz"
s = abc[:k]
s1 = s
while len(s1) < n:
s1 += s
s1 = s1[:n]
print(s1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points *a*,<=*b*,<=*c*.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of *a* is the same as the old position of *b*, and the new position of *b* is the same as the old position of *c*.
Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.
|
```python
import math
ax, ay, bx, by, cx, cy = map(int, input().split())
area = 0.5*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by))
if area==0:
print("No")
else:
print("Yes")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jzzhu is the president of country A. There are *n* cities numbered from 1 to *n* in his country. City 1 is the capital of A. Also there are *m* roads connecting the cities. One can go from city *u**i* to *v**i* (and vise versa) using the *i*-th road, the length of this road is *x**i*. Finally, there are *k* train routes in the country. One can use the *i*-th train route to go from capital of the country to city *s**i* (and vise versa), the length of this route is *y**i*.
Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
|
```python
import bisect
import collections
import copy
import enum
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(3001)
input = sys.stdin.readline
n,m,k = map(int,input().split())
g = collections.defaultdict(list)
for _ in range(m):
u,v,x = map(int,input().split())
g[u].append([v,x,0])
g[v].append([u,x,0])
for _ in range(k):
s, y = map(int, input().split())
g[1].append([s,y,1])
dist = [float("inf")]*(n+1)
r = 0
def dijkstra(start):
global r
q = [(0, start,0)]
while q:
dis, f,node = heapq.heappop(q)
if dist[node] <= dis:
continue
r+=f
dist[node] = dis
for next_node, w,f in g[node]:
if dist[next_node] == float("inf"):
heapq.heappush(q, (dis+w,f,next_node))
return dist
dijkstra(1)
print(k-r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
|
```python
s = input()
flag = True
i = 0
while(i < len(s)):
if s[i:i+3] == "WUB":
i += 3
if not flag:
print(" ",end='')
else:
flag = False
print(s[i],end='')
i += 1
print()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.
You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where:
- <hostname> — server name (consists of words and maybe some dots separating them), - /<path> — optional part, where <path> consists of words separated by slashes.
We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.
Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.
Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.
|
```python
n=int(input())
d={}
D={}
ans=[]
for i in range(n):
h,*p=(input()[7:]+'/').split('/')
d[h]=d.get(h,set())|{'/'.join(p)}
for x in d:
t=tuple(sorted(d[x]))
D[t]=D.get(t,[])+[x]
for x in D:
if len(D[x])>1:
ans+=['http://'+' http://'.join(D[x])]
print(len(ans))
print('\n'.join(ans))
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.