source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions | You are given *n* switches and *m* lamps. The *i*-th switch turns on some subset of the lamps. This information is given as the matrix *a* consisting of *n* rows and *m* columns where *a**i*,<=*j*<==<=1 if the *i*-th switch turns on the *j*-th lamp and *a**i*,<=*j*<==<=0 if the *i*-th switch is not connected to the *j*... | ```python
def dfs(v,graph,flag,vnt):
vnt[v] = 1
flag[v] = True
for i in range(len(graph[v])):
if(flag[graph[v][i]] == False):
dfs(graph[v][i],graph,flag,vnt)
vnt[v] += vnt[graph[v][i]]
n = int(input())
graph = [[] for _ in range(n+1)]
flag = [False]*(n+1)
vnt = [0]*(n+1)
for _ in range(n-1... | |
MatrixStudio/Codeforces-Python-Submissions | One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of *n* floors and 2·*m* windows on each floor. On each floor there are *m* flats num... | ```python
f = 0
v = []
n,m = map(int,input().split())
for i in range(n):
l = list(map(int,input().split()))
for j in range(len(l)):
v.append(l[j])
for i in range(0,len(v)-1,2):
if v[i] == 1 or v[i+1] == 1:
f+=1
print(f)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are *m* types of discounts. We assume that the discounts are indexed from 1 to *m*. To use the discount number *i*, the customer takes a special basket, where he puts exactly *q**i* items he buys. Unde... | ```python
m = int(input())
q = [int(i) for i in input().split()]
n = int(input())
a = [int(i) for i in input().split()]
c = min(q)
a.sort()
price = 0
for i in range(n):
if i % (c+2) < c:
price += a[n-1-i]
print(price)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and ... | ```python
x = input().split()
l = int(x[0])
r = int(x[1])
a = int(x[2])
min1 = min(l,r)
max1 = max(l,r)
diff = max1 - min1
if diff > 0:
if diff > a:
print((min1+a)*2)
else:
a-=diff
divide = int(a/2)
print((max1+divide)*2)
else:
print((min1+int(a/2))*2)
... | |
MatrixStudio/Codeforces-Python-Submissions | We'll define *S*(*n*) for positive integer *n* as follows: the number of the *n*'s digits in the decimal base. For example, *S*(893)<==<=3, *S*(114514)<==<=6.
You want to make a consecutive integer sequence starting from number *m* (*m*,<=*m*<=+<=1,<=...). But you need to pay *S*(*n*)·*k* to add the number *n* to the ... | ```python
w, m, k = [int(i) for i in input().split()]
s = lambda n: len(str(n))
cost = s(m)*k
seqLen = 0
while cost <= w:
m += 1
cost += s(m)*k
seqLen += 1
#print('cost: ',cost,' m: ',m,' w: ',w)
print(seqLen)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and ... | ```python
l,r,a = map(int,input().split())
total = 0
if min(l,r)+a<=l or min(l,r)+a<=r:
minemum = min(l,r)+a
total=minemum*2
else:
minemum = min(l,r)+a
a = minemum-max(l,r)
minemum = max(l,r)
total=(minemum*2)+(a)
if total%2==0:
print(total)
else:
print(total-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | ```python
n = int(input())
sum_coordinates = []
new_list = []
for i in range(n):
sum_coordinates.append(list(map(int, input().split())))
new_list = [sum(x) for x in zip(*sum_coordinates)]
if sum(new_list) == 0 or new_list[0] == 0 and new_list[1] == 0 and new_list[2] == 0:
print("YES")
elif new_list[0] !... | |
MatrixStudio/Codeforces-Python-Submissions | Vladik had started reading a complicated book about algorithms containing *n* pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation *P*<==<=[*p*1,<=*p*2,<=...,<=*p**n*], where *p**i* denotes the number of page that should be read *i*-th in turn.
So... | ```python
n, m = list(map(int, input().split()))
pages = list(map(int, input().split()))
res = []
inputs = [list(map(int, input().split())) for _ in range(m)]
for row in inputs:
l, r, x = row
not_changed = "Yes"
if l <= x <= r:
el = pages[x - 1]
seg = pages[l - 1:r]
seg.s... | |
MatrixStudio/Codeforces-Python-Submissions | Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at *a*1 percent and second one is charged at *a*2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if n... | ```python
energy1, energy2 = map(int, input().split())
i = 0
connected = 1
while True:
if connected == 1:
if energy2 < energy1:
connected = 2
energy1 -= 2
energy2 += 1
else:
energy1 += 1
energy2 -= 2
else:
if energy... | |
MatrixStudio/Codeforces-Python-Submissions | «Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | ```python
n = int(input())
a = sorted([int(i) for i in input().split()])
for i in a:
if i+1 not in a:
print(i+1)
exit()
``` | |
MatrixStudio/Codeforces-Python-Submissions | Right now she actually isn't. But she will be, if you don't solve this problem.
You are given integers *n*, *k*, *A* and *B*. There is a number *x*, which is initially equal to *n*. You are allowed to perform two types of operations:
1. Subtract 1 from *x*. This operation costs you *A* coins. 1. Divide *x* by *k*.... | ```python
n=int(input())
k=int(input())
A=int(input())
B=int(input())
s=0
while n>1:
#print('n='+str(n))
#print('s='+str(s))
if n<k:
s+=A*(n-1)
break
r=n%k
if r>0:
s+=r*A
n-=r
else:
m=n//k
s+=min((n-m)*A,B)
n=m
print(s)
`... | |
MatrixStudio/Codeforces-Python-Submissions | Evlampiy has found one more cool application to process photos. However the application has certain limitations.
Each photo *i* has a contrast *v**i*. In order for the processing to be truly of high quality, the application must receive at least *k* photos with contrasts which differ as little as possible.
Evlampiy a... | ```python
# n , k = 5,2
s1 = input()
arr1 = s1.split(' ')
n,k = int(arr1[0]),int(arr1[1])
s2 = input()
# s = '50 110 130 40 120'
array = s2.split(' ')
for i in range(n):
array[i] = int(array[i])
array.sort(reverse=True)
left = 0
right = array[0] - array[-1]
def check(x)->bool:
l = 0
r = k - 1... | |
MatrixStudio/Codeforces-Python-Submissions | A restaurant received *n* orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the *i*-th order is characterized by two time values — the start time *l**i* and the finish time *r**i* (*l**i*<=≤<=*r**i*).
Restaurant management can accept and reject orders. What is the maximal... | ```python
from collections import defaultdict
n=int(input())
x=[]
z=defaultdict(list)
for j in range(n):
a,b= map(int,input().split())
x.append([a,b])
z[b].append(a)
x.sort(key = lambda xx: xx[1])
dp = [0 for i in range(n+1)]
dp[1] = len(z[1])
for i in range(2,n+1):
for j in z[i-1]... | |
MatrixStudio/Codeforces-Python-Submissions | You are given an array consisting of *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to *n* defining the order elements of the array are destroyed.
After each element is destroyed you have to find o... | ```python
n = int(input())
a = list(map(int, input().split()))
p = list(map(int, input().split()))
valid = [False for i in range(n)]
parent = [0] * n
size = [0] * n
stat = [0] * n
def find(x):
while parent[x] != x:
x = parent[x]
return x
def union(a, b):
x = find(a)
y = find(b... | |
MatrixStudio/Codeforces-Python-Submissions | Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each ... | ```python
l = [2, 7, 2, 3, 3, 4, 2, 5, 1, 2]
s = input()
k = 1
for i in s:
k *= l[int(i)]
print(k)
``` | |
MatrixStudio/Codeforces-Python-Submissions | One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number *n* to Bob and said:
—Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroe... | ```python
a=str(input())
b=str(input())
d={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
for i in range(len(a)):
d[int(a[i])]+=1
#print(d)
ans=""
keep=0
for i in range(1,10):
if d[i]>0 :
ans+=str(i)
keep=i
d[i]-=1
break
#print(ans)
for i in range(1,len(a)):
for j in range(1... | |
MatrixStudio/Codeforces-Python-Submissions | Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases:
1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size ... | ```python
sa = input().strip()
sb = input().strip()
def check(p1, p2, ln):
global sa, sb
for i, j in zip(range(p1, p1 + ln), range(p2, p2 + ln)):
if sa[i] != sb[j]:
break
else:
return True
if ln % 2:
return False
nln = ln // 2
return (check(p1,... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans... | ```python
s=input()
i=-1
while(not((s[i]>='a' and s[i]<='z') or (s[i]>='A' and s[i]<='Z'))):
i-=1
if(s[i]=='A' or s[i]=='E' or s[i]=='I' or s[i]=='O' or s[i]=='Y' or s[i]=='a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='y'):
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the h... | ```python
n,k = list(map(int,input().split(" ")))
arr=list(map(int,input().split(" ")))
sumi=0
for i in range(k):
sumi=sumi+arr[i]
mini = sumi
index=0
l=0
r=k-1
while(r<=n-2):
r=r+1
sumi=sumi+arr[r]
sumi=sumi-arr[l]
l=l+1
if(sumi<mini):
mini=sumi
index=j
print(j)... | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for w... | ```python
n=int(input())
s=[]
for i in range(0,n):
s.append(str(input()))
for i in range(0,n):
b=0;
for j in range(1,10):
if(b==1):
break;
for t in range(9-j,-1,-1):
flag=1;
for m in range(0,n):
if(m==i):
continue;
... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has an array *a* consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element ... | ```python
n=int(input())
ls=list(map(int,input().split()))
s=sum(ls)/2
if sum(ls)%2!=0:
print('No')
exit()
lz=ls.copy()
for i in range(1,n):
lz[i]+=lz[i-1]
if lz[i]==s or ((lz[i]-s) in ls[:i+1]):
print('Yes')
break
else:
lc=ls.copy()
lc.reverse()
for i in range... | |
MatrixStudio/Codeforces-Python-Submissions | You've got an array *a*, consisting of *n* integers. The array elements are indexed from 1 to *n*. Let's determine a two step operation like that:
1. First we build by the array *a* an array *s* of partial sums, consisting of *n* elements. Element number *i* (1<=≤<=*i*<=≤<=*n*) of array *s* equals . The operation *x*... | ```python
mod=1000000007
n,k=map(int,input().split())
arr=list(map(int,input().split()))
arrx=[]
arr1=[]
for i in range(n):
arr1.append(arr[i])
sum1=0
if(k==0):
print(*arr)
else:
j=1
sumx=0
for i in range(n):
sumx=(j*(j+1))//2
arrx.append(sumx)
j+=1
#print(*arrx)
for i in range(n):
sum... | |
MatrixStudio/Codeforces-Python-Submissions | Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — ... | ```python
a = int(input())
b = int(input())
c = int(input())
s = min(a//1, b//2, c//4)
ans = s*7
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had ... | ```python
if __name__ == "__main__":
passw = input()
line0 =input()
line1 =input()
line2 =input()
line3 =input()
line4 =input()
line5 =input()
line6 =input()
line7 =input()
line8 =input()
line9 =input()
#passw = list(passw)
passws = [str(passw[0:10]), str... | |
MatrixStudio/Codeforces-Python-Submissions | You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*. | ```python
a=input()
b=input().split()
c=input().split()
d=[]
def p(i,x):
for j in b:
if int(j)<=i:
x+=1
return x
print(*list(map(lambda i:p(int(i),0),c)))
``` | |
MatrixStudio/Codeforces-Python-Submissions | The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a ... | ```python
def main():
path = input()
coordinate = [[0 for i in range(2)] for j in range(len(path)+1)]
coordinate[0] = [0,0]
left = 0
right = 0
up = 0
down = 0
for direction in path:
if direction == 'U':
up += 1
elif direction == 'R':
right += 1
elif direction == 'D'... | |
MatrixStudio/Codeforces-Python-Submissions | Berland Football Cup starts really soon! Commentators from all over the world come to the event.
Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations wil... | ```python
n,m,a,b=map(int,input().split())
k=n%m
print(min(k*b,(m-k)*a))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon piece... | ```python
def rec(m, arr):
if(m in arr):
return 1
if(len(arr) == 2):
return 1 + max(rec(m-arr[0], arr), rec(m-arr[1], arr))
return 1 + max(rec(m-arr[0], arr), rec(m-arr[1], arr), rec(m-arr[-1], arr))
nums = list(map(int, input().split()))
n = nums[0]
nums = nums[1:]
nums.sort()
i... | |
MatrixStudio/Codeforces-Python-Submissions | One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | ```python
Number = int(input())
counter = 0;
for i in range(Number):
Lists = str(input())
if Lists == "1 1 1" or Lists == "0 1 1" or Lists == "1 1 0":
counter = counter + 1
print(counter)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The polar bears are going fishing. They plan to sail from (*s**x*,<=*s**y*) to (*e**x*,<=*e**y*). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (*x*,<=*y*).
- If the wind blows to the east, the boat will ... | ```python
from collections import Counter
def main():
dirs = {
'S': -1,
'N': 1,
'W': -1,
'E': 1,
}
t, sx, sy, ex, ey = map(int, input().split())
for i, dir in enumerate(input(), 1):
if dir in 'SN':
if abs(ey - sy - dirs[dir])< abs(ey - sy):
... | |
MatrixStudio/Codeforces-Python-Submissions | Find the number of *k*-divisible numbers on the segment [*a*,<=*b*]. In other words you need to find the number of such integer values *x* that *a*<=≤<=*x*<=≤<=*b* and *x* is divisible by *k*. | ```python
s=[int(i) for i in input().split()]
k=s[0]
a=s[1]
b=s[2]
s.clear()
if a<=0 and b>=0:
a=-a
print((a+b)//k+1)
continue
else:
if a<=0 and b<=0:
a=-a
b=-b
a,b=b,a
ans=(b-a+1)//k
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
- Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahed... | ```python
x = input()
cnt=0
for i in range(1,x):
s = input()
if s=="Tetrahedron":
cnt+=4
elif s=="Cube":
cnt+=6
elif s=="Octahedron":
cnt+=8
elif s=="Dodecahedron":
cnt+=12
elif s=="Icosahedron":
cnt+=20
print(cnt)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.
To settle this problem, they've decided to play a game. The company name will consist of *n* letters. Oleg and Igor ... | ```python
A = [0 for _ in range(26)]
B = [0 for _ in range(26)]
ptr_a = 30
ptr_b = -1
s1 = input()
length = len(s1)
for c in s1:
x = ord(c)-ord("a")
A[x] += 1
if A[x] == 1 and x < ptr_a:
ptr_a = x
s2 = input()
for c in s2:
x = ord(c) - ord("a")
B[x] += 1
if B[x] == 1... | |
MatrixStudio/Codeforces-Python-Submissions | A permutation of size *n* is an array of size *n* such that each integer from 1 to *n* occurs exactly once in this array. An inversion in a permutation *p* is a pair of indices (*i*,<=*j*) such that *i*<=><=*j* and *a**i*<=<<=*a**j*. For example, a permutation [4,<=1,<=3,<=2] contains 4 inversions: (2,<=1), (3,<=... | ```python
n = int(input())
lst = []
for x in input().split():
lst.append(int(x))
m = int(input())
pair = []
for x in range(m):
(l, r) = map(int, input().split())
pair.append((l, r))
k = 0
for x in range(0, len(lst) - 1):
for y in range(x + 1, len(lst)):
if lst[y] < lst[x]:
... | |
MatrixStudio/Codeforces-Python-Submissions | You are given an equation:
Your task is to find the number of distinct roots of the equation and print all of them in ascending order. | ```python
import sys, io, os
from collections import Counter
input = sys.stdin.readline # for strings
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # for non-strings
def solve():
a, b, c = map(int, input().split())
if a == 0:
if b == 0:
if c == 0:
print(... | |
MatrixStudio/Codeforces-Python-Submissions | Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm.
Formally, find the biggest in... | ```python
a, b = map(int, input().split())
if a == b:
print(a)
else:
print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most *k* pebbles in each pocket at the same tim... | ```python
import math
c=0
n,k=map(int,input().split())
arr=list(map(int,input().strip().split()))
for i in arr:c+=math.ceil(i/k)
print(math.ceil(c/2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | ```python
s=input()
r=input()
print(s^r)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's ... | ```python
n = int(input())
a = int(input())
b = int(input())
c = int(input())
no_move = False
_min = min(a, b)
if n == 1:
no_move = True
if no_move:
print(0)
else:
if c >= _min:
dist = (n-1)*_min
else:
dist = _min+(n-2)*c
print(dist)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | ```python
t = input()
events = list(map(int , input().split()))
police = 0
count = 0
for event in events:
police += event
if police < 0:
count +=1
police = 0
print(count)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height ... | ```python
n,k =input().split()
n =int(n)
k=int(k)
a=input()
x=a.split()
c=0
for i in range(n):
x[i]=int(x[i])
if x[i]>k:
c+=2
else:
c+=1
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is ... | ```python
n = int(input())
h = *map(int, input().split()),
cost = 0
cost += h[1]
e = h[1]
i = 2
while i < n:
if h[i] > e:
cost += h[i] - e
e += h[i] - e
else:
e += e - h[i]
i += 1
print(cost)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha... | ```python
from statistics import mode
import re
lst = []
str = input()
S = str
while len(S):
m = re.search(r'([0-2][0-9]|[3][01])[-]([0][13578]|[1][02])[-]([2][0][1][3-5])',S)
if m:
lst.append(m.group())
S = S[m.start() + 1:]
else:
break
S = str
while len(S):
m = re... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1<=×<=*n* square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya... | ```python
n=int(input())
s=input()
c=0
for i in range(n):
if (i+1)%2==0 and s[i]=="1" or (i+1)%2==1 and s[i]=="0":
c+=1
print(min(n-c,c))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0. | ```python
n=int(input())
l=list(map(int,input().split()))
s=0
ol=[]
for i in l:
if i%2==0:
s=s+i
else:
ol.append(i)
if len(ol)%2==0:
s=s+sum(ol)
else:
s=s+sum(ol)-min(ol)
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You have a positive integer *m* and a non-negative integer *s*. Your task is to find the smallest and the largest of the numbers that have length *m* and sum of digits *s*. The required numbers should be non-negative integers written in the decimal base without leading zeroes. | ```python
m,s=[int(i) for i in input().split()]
def convert(lis):
max_val=0
min_val=0
s=''
for i in lis:
s=s+str(i)
max_val=int(s)
lis.reverse()
s=''
for i in lis:
s=s+str(i)
min_val=int(s)
return (min_val,max_val)
if s<1 or s>m*9:print(-1,-1)
else:... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | ```python
x=input("")
y=x.lower()
z=x.upper()
y1=0
x1=0
for i in x:
if i in y:
y1+=1
else:
x1+=1
if y1>x1:
print(y)
else:
print(z)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | ```python
def qpow(x,y):
z=1
while (y):
if (y&1):
z=z*x
x=x*x
y>>=1
return z
x,y=map(int,input().strip().split())
a=x**y
b=y**x
if (a==b):
print('=')
elif (a>b):
print('>')
else:
print('<')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has *m* faces: the first face of the dice contains a dot, the second one contains two dots... | ```python
def miis():
return map(int, input().split())
m, n = miis()
ans = 0
for i in range(1, m+1):
ans += i*((i/m)**n-((i-1)/m)**n)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells *n*<=×<=*m* in size (containing *n* rows, *m* columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a simple path between those two cells as a sequence of distinct ce... | ```python
m,n=map(int,input().split())
a1,b1=map(int,input().split())
a2,b2=map(int,input().split())
print((m*n)-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently ... | ```python
q = int(input())
pot = []
b = 1
while (42):
a = b**2
if(a <= q):
pot.append((a))
b += 1
else:
break
pot.sort(reverse = True)
b = 0
aux = -1
res = ""
q = list(str(q))
while b < len(pot):
pot_aux = list(str(pot[b]))
flag = 0
aux = -1
for i in range(len(po... | |
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 ... | ```python
m, n = map(int, input().split())
area = m*n
count = area//2
print(count)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A colored stripe is represented by a horizontal row of *n* square cells, each cell is pained one of *k* colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to *k* to repaint the cells. | ```python
print("_RANDOM_GUESS_1689366534.3880188")# 1689366534.388033
``` | |
MatrixStudio/Codeforces-Python-Submissions | A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert *a* grams of sand into *b* grams of lead, the second one allows you to convert *c* grams of lead into *d* grams o... | ```python
# LUOGU_RID: 112089745
a, b, c, d, e, f = map(int, input().split());
if a * c * e < b * d * f or a == 0 and b * d > 0 or c == 0 and d > 0:
print("Ron");
else:
print("Hermione");
``` | |
MatrixStudio/Codeforces-Python-Submissions | *n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that coul... | ```python
import math
def comb(n, k):
if(n >= k):
return math.comb(n, 2)
else:
return 0
def take_min(n, t):
l = int(n/t) + 1
dif = t*l - n
friends = (t-dif)*comb(l, 2) + (dif)*comb(l-1, 2)
return int(friends)
def take_max(n, t):
return int(comb(n-(t-1), 2))
n, t = list(map(int, input().split()))... | |
MatrixStudio/Codeforces-Python-Submissions | A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immedi... | ```python
n=int(input())
l=[int(input()) for i in range(n)]
g=0
for i in range(n):
cnt=0
while i>=0:
i=l[i]-1
cnt+=1
g=max(g,cnt)
print(g)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the *expose* procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agre... | ```python
import math
import cmath
import string
import sys
import bisect
import ctypes
from queue import Queue,LifoQueue,PriorityQueue
from itertools import permutations,combinations
from collections import deque,Counter
l,r,k=list(map(int,input().split()))
i=0
a=[]
while 1:
temp=pow(k,i)
i+=1
if temp<=r:... | |
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*. ... | ```python
def solution(peeps):
s = sum(peeps)
for i in range(len(peeps)):
for j in range(i + 1, len(peeps)):
for k in range(j + 1, len(peeps)):
total = i + j + k
if total == s - total:
return "YES"
return "NO"
peeps = list(map(int, input().split()))
print(solution(peeps))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be sw... | ```python
ons = [[1,1,1], [1,1,1], [1,1,1]]
for i in range(3):
rr = map(int, input().split())
for j, togs in enumerate(rr):
for _ in range(togs):
for ii in range(i-(i>0), min(i+2, 3)):
for jj in range(j-(j>0), min(j+2,3)):
ons[ii][jj] ^= 1
for g in ons:
... | |
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 route... | ```python
# ﷽
from collections import defaultdict
from heapq import heappop, heappush
import sys
input = lambda: sys.stdin.readline().strip()
def inlst():return [int(i) for i in input().split()]
class Graph:
def __init__(self,n):
self.graph=defaultdict(list)
self.graph2=set()
self.... | |
MatrixStudio/Codeforces-Python-Submissions | The "BerCorp" company has got *n* employees. These employees can use *m* approved official languages for the formal correspondence. The languages are numbered with integers from 1 to *m*. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official la... | ```python
def find_min_cost_to_connect_employees(n, m, employees):
graph = [[] for _ in range(n)]
for i in range(n):
_, *languages = employees[i]
for lang in languages:
graph[i].append(lang)
visited = [False] * n
total_cost = 0
def dfs(node):
visite... | |
MatrixStudio/Codeforces-Python-Submissions | Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked. | ```python
d = {}
for i in range(int(input())):
s = list(map(str, input().split()))
if s[0] not in d:
d[s[0]] = [s[1]]
else:
if (s[1] not in d[s[0]]):
d[s[0]].append(s[1])
ans = 0
# print(d)
for key in d:
for value in d[key]:
ans += 1
print(ans)
``` | |
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... | ```python
n = int(input())
snowpatch = [input().split() for i in range(n)]
newnode = 0
visited = [ False for i in range(n)]
for i in range(n):
if visited[i] == True:
continue
visited[i] = True
newnode += 1
stack = [i]
while stack:
x = stack[-1]
stack.pop()
for j ... | |
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, ... | ```python
s = input()
hello = "hello"
counter = 0
j = 0
for i in range(len(hello)):
while j < len(s):
if hello[i] == s[j]:
counter += 1
j += 1
break
j += 1
if counter == 5:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver... | ```python
n = int (input())
a = list(map(int,input().split()))
check = 0
i = 0
ans = 2
mn = min(a[0],a[1])
mx = max(a[0],a[1])
check =0
while(i<n-1):
l = 1
if check:
break
for j in range(i+1,n):
next = a[j]
# print('I:',i,'J',j)
# print('mx', mx, 'mn', mn, 'nex... | |
MatrixStudio/Codeforces-Python-Submissions | Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.
Bottle with potion has two values *x* and *y* written on it. These values define four moves which can be perfo... | ```python
positions = [int(a) for a in input().split()]
potion = [int(a) for a in input().split()]
x_dist = abs(positions[2] - positions[0])
y_dist = abs(positions[3] - positions[1])
if (x_dist%potion[0]==0 and y_dist%potion[1]==0):
x_div = x_dist//potion[0]
y_div = y_dist//potion[1]
if (abs(x_div -... | |
MatrixStudio/Codeforces-Python-Submissions | Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are *n* days, at the *i*-th day, Arya finds *a**i* candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of ... | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
got = 0
for i in range(n):
got += a[i]
k -= min(got, 8)
got -= min(got, 8)
if k <= 0:
print(i+1)
break
if k > 0:
print(-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If... | ```python
n=int(input())
a=[int(x) for x in input().split()]
d=[0]*n
for i in range(n):
d[a[i]-1]=str(i+1)
m=" ".join(d)
print(m)
``` | |
MatrixStudio/Codeforces-Python-Submissions | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are... | ```python
s=input()
l=list(s)
n=len(s)
c=0
for i in range(n):
if l[i]=='A':
a=0
b=0
for j in range(i):
if l[j]=='Q':
a+=1
for j in range(i,n):
if l[j]=='Q':
b+=1
c+=a*b
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an... | ```python
n = int(input)
text = input()
new_text1 = text.replace('RU', 'D')
new_text2 = text.replace('UR', 'D')
x = len(new_text2)
print(x)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and *L*, and they move towards each other ... | ```python
d,L,v1,v2 = map(int,input().split())
t = (L-d)/(v1+v2)
print(t)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with... | ```python
k=int(input())
m=[int(c) for c in input() if c!='.' for row in range(4)]
print("YES" if all(m.count(t)<=2*k for t in set(m)) else "NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | In Aramic language words can only represent objects.
Words in Aramic have special properties:
- A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$... | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
s = list(input().rstrip().decode().split())
u = set()
for s0 in s:
v = list(set(s0))
v.sort()
u.add(tuple(v))
ans = len(u)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | People in the Tomskaya region like magic formulas very much. You can see some of them below.
Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas:
Here, "mod" means the operation of taking the residue after dividing.
The expression means applying ... | ```python
n=int(input())
a=list(map(int,input().split()))
dp=[0 for i in range(n+1)]
for i in range(1,n+1):
dp[i]=dp[i-1]^i
ans=0
for i in a:
ans=ans^i
for i in range(2,n+1):
x=n//i
if x&1:
ans=ans^dp[i-1]
rem=n%i
ans=ans^dp[rem]
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded.
For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct.
For given *n* find out to which int... | ```python
n=int(input())
if n>=1 and n<=1000000000:
a=n%10
if a <=5:
print(n-a)
else:
print(n+(10-a))
``` | |
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 i... | ```python
n=int(input())
number=[int(x) for x in input().split()]
odd=0
even=0
for i in range(n):
if number[i]%2==0:
evennum=number[i]
even+=1
else:
oddnum=number[i]
odd+=1
if odd>even:
print((number.index(evennum))+1)
else:
print((number.index(oddnum))+1)
`... | |
MatrixStudio/Codeforces-Python-Submissions | The Little Elephant loves chess very much.
One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8<=×<=8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard d... | ```python
a=input()
b=input()
c=input()
d=input()
e=input()
f=input()
g=input()
h=input()
s="WBWBWBWB"
s1="BWBWBWBW"
l=[a,b,c,d,e,f,g,h]
ok=0
if l.count(s)==4 and l.count(s1)==4:
ok+=1
else:
ok=0
# else:
# ok=0
if ok==1:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the pic... | ```python
n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
a.sort()
l,p,k = a[n-1],0,0
for i in range(n-1):
if p<l:
if a[i]>p:
k+=(a[i]-1)
p+=1
else:
k+=(a[i]-1)
else:
k+=(a[i]-1)
if p>=l:
print(k+(a[n-1]-1))
e... | |
MatrixStudio/Codeforces-Python-Submissions | A continued fraction of height *n* is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height *n*. Check if they are equal. | ```python
p, q = [int(x) for x in input().split()]
n = int(input())
a = [int(x) for x in input().split()]
for x in a:
p -= q*x
p,q = q,p
if(q==0):
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Dreamoon wants to climb up a stair of *n* steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer *m*.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? | ```python
n,m=map(int,input().split())
if n<m:
print(-1)
else:
print((((n+1)//2-1)//m+1)*m)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | ```python
if __name__ == "__main__":
s = input()
count_up = 0
count_low = 0
for ch in s:
if ch.isupper():
count_up += 1
else:
count_low += 1
if count_up > count_low:
for ch in s:
print(ch.upper(), end="")
else:
... | |
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 ... | ```python
x, y = map(int, input().split())
min = min(x, y)
max = max(x, y)
different_days = min
same_days = (max - min) // 2
print(different_days, same_days)
``` | |
MatrixStudio/Codeforces-Python-Submissions | On the way to school, Karen became fixated on the puzzle game on her phone!
The game is played as follows. In each level, you have a grid with *n* rows and *m* columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.
... | ```python
import math as mt
import sys,string
input=sys.stdin.readline
import random
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
n,m=M()
l=[]
x=[]
req=[]
req2=[]
ans=[]
ans2=[]
c=0
f=0
c... | |
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-... | ```python
def sum_digits(num):
tot = 0
while num:
tot += (num % 10)
num //= 10
return tot
if __name__ == "__main__":
n = int(input())
ans = 0
while n >= 10:
ans += 1
n = sum_digits(n)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of... | ```python
n=[i for i in input()]
flag=True
bravo=-1
for i in range(len(n)):
if int(n[i])%2==0 and int(n[i])<int(n[-1]):
count_=i
flag=False
break
elif int(n[i])%2==0:
bravo=i
if flag:
if bravo==-1:
print(-1)
else:
tre=n[bravo]
n[brav... | |
MatrixStudio/Codeforces-Python-Submissions | Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th... | ```python
t=input()
if int(t[:2])==23 and int(t[3:5])>32:
print('00:00')
elif(6<=int(t[:2])<=9):
print('10:01')
elif(16<=int(t[:2])<=19):
print('20:02')
elif(int(t[:2][::-1]) <= int(t[3:5])):
print(t[:2]+':'+t[:2][::-1])
else:
print(str(int(t[:2])+1)+':'+str(int(t[:2])[::-1]))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | ```python
s1 = input().lower()
s2 = input().lower()
f = 0
for i in range(len(s1)):
if ord(s1[i]) > ord(s2[i]):
f = 1
break
elif ord(s1[i]) < ord(s2[i]):
f = -1
break
print(f)
``` | |
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 Vasy... | ```python
n = int(input())
arr = [[]]
for i in range(n):
for j in range(n):
arr[i][j] = int(input())
som = 0
for i in range(n):
for j in range(n):
som += arr[i][j]
if som == 0:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has *n* burles. One bottle of Ber-Cola costs *a* burles and one Bars bar costs *b* burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.
Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly *n* bu... | ```python
n = int(input())
a = int(input())
b = int(input())
def main():
total = n
if total%a == 0:
print("YES")
print(total//a,0)
return
if total%b == 0:
print("YES")
print(0,total//b)
return
counter = 0
while total>0:
if total%b == 0:
... | |
MatrixStudio/Codeforces-Python-Submissions | A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to *n* clockwise and the child number 1 is... | ```python
n = int(input())
id = 1
for i in range(n - 1):
id += i + 1
id %= n
if id == 0:
print(n, end=' ')
else:
print(id, end=' ')
``` | |
MatrixStudio/Codeforces-Python-Submissions | The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.
At some points on the road there are *n* friends, and *i*-th of them is standing at the point *x**i* meters and can move with any speed no greater ... | ```python
n = int(input())
x = [int(i) for i in input().split()]
v = [int(i) for i in input().split()]
def search(n,x,v,t):
lmax = max([x[i]-t*v[i] for i in range(n)])
rmin = min([x[i]+t*v[i] for i in range(n)])
if lmax<=rmin:
return True
return False
def binary(n,x,v):
l,r = 0... | |
MatrixStudio/Codeforces-Python-Submissions | A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | ```python
def register_users(n, requests):
registered_users = set() # Set to store registered user names
responses = [] # List to store system responses
for request in requests:
if request not in registered_users:
registered_users.add(request)
responses.append("OK")
... | |
MatrixStudio/Codeforces-Python-Submissions | «One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | ```python
num=[]
count=0
for i in range(5):
num.append(int(input()))
if num[0]==1 or num[1]==1 or num[2]==1 or num[3]==1:
print(num[4])
else:
for i in range(1,num[4]+1):
if i%num[0]==0 or i%num[1]==0 or i%num[2]==0 or i%num[3]==0:
count+=1
print(count)
... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarpus has an array, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:
- he chooses two elements of the array *a**i... | ```python
import collections
n=int(input())
A=[int(x) for x in input().split()]
while True:
A.sort()
B=A[:]
flag=1
for i in range(n//2):
while(A[n-i-1]-1>A[i]):
A[n-i-1]-=1
A[i]+=1
flag=0
if flag:
break
D=collections.Counter(A)
pri... | |
MatrixStudio/Codeforces-Python-Submissions | Tattah's youngest brother, Tuftuf, is new to programming.
Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava.
Today, Tuftuf was introduced to Gava's unsigned integer datatypes. G... | ```python
n = int(input())
A = list(map(int, input().split()))
A.sort()
per = 0
per2 = True
while per < n-1:
if A[per] < A[per+1]:
if A[per+1] < A[per] * 2:
per2 = False
print(A[per],A[per+1])
break
else:
per+=1
else:
per+=1
... | |
MatrixStudio/Codeforces-Python-Submissions | Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercise... | ```python
import sys
t = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
chest = biceps = back = 0
for i in range(len(arr)):
if i % 3 == 0:
chest += arr[i]
elif i % 3 == 1:
biceps += arr[i]
else:
back += arr[i]
if chest > biceps and chest > bac... | |
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 "codefo... | ```python
def iter(s):
rev = s[::-1]
count = 0
length_string = len(s)
for i in range(length_string):
if(s[i]!=rev[i]):
count+=1
if count==2:
print("YES")
else:
print("NO")
s = input()
iter(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | ```python
a=(input())
b=lift(map(int,input().split()))
c=0
d=e=b[0]
for i in b:
if d>i:
d=i
c+=1
if d<i:
e=i
c+=1
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of *n* vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex *x* (*x*<=≠<=1). The moves are made in turns, Bob go... | ```python
n, x = map(int, input().split())
mas = [[] * (1) for i in range(n + 2)]
for i in range(n - 1):
a, b = map(int, input().split())
mas[a].append(b)
mas[b].append(a)
queue = []
queue.append(1)
dist = [100002] * (n + 1)
dist[0] = 0
dist[1] = 0
visit = [-1] * (n + 1)
visit[1] = 0
while len(... | |
MatrixStudio/Codeforces-Python-Submissions | Anton has the integer *x*. He is interested what positive integer, which doesn't exceed *x*, has the maximum sum of digits.
Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. | ```python
import math
n=int(input())
x=math.log10(n)
v=int(x)
if(v==x):
print(n-1)
else:
num=n
s=0
c=0
while(num>10):
s=s+(num%10)
c=c+1
num=int(num/10)
k=num-1
if(num==10):
s=s+1
else:
s=s+num
s1=c*9 + k
if(s1>s):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.