problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend... | 3 | n, t = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
s = 0
d = 0
for i in a:
t = t - (86400 - i)
d += 1
if( t <= 0):
break;
print(d)
|
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
... | 3 | def euclid(x, y):
c0, c1 = x, y
a0, a1 = 1, 0
b0, b1 = 0, 1
while c1 != 0:
m = c0 % c1
q = c0 // c1
c0, c1 = c1, m
a0, a1 = a1, (a0 - q * a1)
b0, b1 = b1, (b0 - q * b1)
return a0, b0
n=int(input())
n=n*2
soinsu=[]
num=n
for i in range(2,max(20,n)):
... |
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values ... | 3 | H = int(input())
A = [None] + list(map(int, input().split()))
def max_heapify(A, i):
l = i * 2
r = i * 2 + 1
largest = i
if l <= H:
if A[l] > A[largest]:
largest = l
if r <= H:
if A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, largest)
def build... |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | def solve():
x = []
ans = []
l = list(input())
for i in range(len(l)):
x.append(l[i] + "0" * (len(l[i:]) - 1))
for i in range(len(x)):
if(x[i][0] != "0"):
ans.append(x[i])
print(len(ans))
print(*ans)
t = int(input())
for i in range(t):
solve()
|
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | 3 | n = int(input())
arr = list(map(int, input().split()))
arr.sort()
arr1 = arr[:n//2]
arr2 = arr[n//2:]
lst = [0]*n
for i in range(n//2):
arr2.insert(i + (i + 1), arr[i])
if n < 3:
print(0)
elif n%2 == 0:
print(int(n/2 - 1))
elif n%2 != 0:
print(n//2)
print(*arr2) |
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be ... | 3 | # import sys
# sys.stdin = open("test.in","r")
# sys.stdout = open("test.out","w")
n=int(input())
a=list(map(int,input().split()))
b=sum(a)/(n/2)
for i in range(n):
for j in range(i+1,n):
if a[i]+a[j]==b:
print(i+1,j+1)
a[j]=0
break
|
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.
The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog... | 1 | # coding=utf-8
rows, columns = map(int, raw_input().split())
pasture = []
wolfs = False
for i in range(rows):
row = raw_input()
pasture.append(row)
if wolfs == False:
if "W" in row:
wolfs = True
if not wolfs:
print "Yes"
for e in range(rows):
print str(pasture[e])
... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | w = int(input(""))
if (w % 2 != 0 or w == 2):
print("NO")
else:
print("YES") |
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
No... | 3 | n,m=map(int,input().split())
if m==0:
print("YES")
exit()
a=sorted(list(map(int,input().split())))
if a[0]==1 or a[-1]==n:
print("NO")
exit()
x=0
for i in range(m-1):
if a[i]+1==a[i+1]:
x+=1
if x==2:
print("NO")
exit()
else:
x=0
print("YES")
|
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite ... | 1 | T, S, q = map(int, raw_input().split())
a = S
count = 1
while a < T:
a = a * q
if a < T:
count += 1
print count
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 1 | st1 = raw_input()
if st1 == "{}":
print "0"
else:
st1 = st1[1:-1]
st1 = set(sorted(st1.split(', ')))
print len(st1)
|
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 plat... | 3 | n,a,b=map(int,input().split())
ans=0
for x in range(1,n):
#if a//x>0 and b//(n-x)>0:
ans=max(ans,min(a//x,b//(n-x)))
print(ans)
|
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | t = int(input())
for _ in range(t):
n,s,t = map(int,input().split())
if s == n and t == n:
print(1)
continue
min_val = min(s,t)
print(n - min_val+1)
|
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | 3 |
def genRemArray(li, n):
rem=[]
for i in li:
rem.append(i-n)
return rem
def main():
t= int(input())
for i in range(t):
gifts= int(input())
candies= list(map(int, input().split()))
oranges= list(map(int,input().split()))
min_c= min(candies)
min_o= min(... |
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... | 1 | s=raw_input()
low=0
for i in s:
if ord(i)>=ord('a') and ord(i)<=ord('z'):
low+=1
up=len(s)-low
if low>=up:
print str.lower(s)
else:
print str.upper(s) |
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1.
Polycarp wants to open a rectangular window of maximal size, which ... | 3 |
def get_result(length,height,x,y):
l1 = x-1
l2 = length-x
h1 = height-y
h2 = y-1
s1 = h1*l1
s2 = h1*l2
s3 = h2*l1
s4 = h2*l2
return max(s1+s2+h1,s1+s3+l1,s3+s4+h2,s2+s4+l2)
if __name__ == '__main__':
count = int(input())
results = []
for i in range(count):
a,b,... |
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all ... | 3 | n, m , p = input().split()
n, m = int(n), int(m)
lines = []
lines.append('.'*(m+2))
for i in range(n):
row = '.'+input()+'.'
lines.append(row)
lines.append('.'*(m+2))
neighbors = []
for i in range(1, n+1):
for j in range(1, m+1):
x = lines[i][j]
a = lines[i-1][j]
b = lines[i][j+1]
c = lines[i+1][j]
d = li... |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l ≤ x ≤ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 | a, b = map(int, input().split())
x = -1
for i in range(a, b + 1):
if len(list(str(i))) == len(list(set(list(str(i))))):
x = i
break
print(x) |
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 ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t... | 3 | num_pedal_axle_stars = int(input())
num_pedal_axle_stars_teeth = list(map(int, input().split()))
num_rear_wheel_axle_stars = int(input())
num_rear_wheel_axle_stars_teeth = list(map(int, input().split()))
max_int = 0
num_max_int = 0
for rear_teeth in num_rear_wheel_axle_stars_teeth:
for pedal_teeth in num_pedal_axle... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | import sys
l, b = map(int, input().split())
i = 0
while l <= b:
l = 3*l
b = 2*b
i += 1
print(i) |
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 burles.
I... | 3 | # B. Proper Nutrition
n=int(input())
a=int(input())
b=int(input())
for i in range(n//2+1):
if i%a==0 and (n-i)%b==0:
print("YES")
print(i//a,(n-i)//b)
break
elif i%b==0 and (n-i)%a==0:
print("YES")
print(((n-i)//a),i//b)
break
else:
print("NO")
|
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).
We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:
* Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates... | 3 | from collections import *
N = int(input())
xy = [tuple(map(int, input().split())) for _ in range(N)]
if N==1:
print(1)
exit()
cnt = defaultdict(int)
for i in range(N):
for j in range(N):
if i==j:
continue
cnt[(xy[i][0]-xy[j][0], xy[i][1]-xy[j][1])] += 1
M = max(... |
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead.
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" ... | 3 | s=input()
a=['ABC','ACB','BCA','BAC','CBA','CAB']
flag=0
for i in a:
if s.find(i) != -1 :
flag=1
if flag==1:
print("YES")
else:
print("NO") |
The Squareland national forest is divided into equal 1 × 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner.
Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C i... | 3 | def main():
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
c = tuple(map(int, input().split()))
a, b, c = sorted((a, b, c))
(x1, y1) = a
(x2, y2) = b
(x3, y3) = c
dy2 = y2 - y1
dy3 = y3 - y1
sy2 = 1 if dy2 >= 0 else -1
sy3 = 1 if dy3 >= 0 else -1... |
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 ... | 3 | n = int(input())
t = True
l = [4,7,44,77,47,74,444,777,447,477,474,744,774,747]
for i in range(len(l)):
if n%l[i] == 0:
print("YES")
t = False
break
if t == True:
print("NO") |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n = int(input())
words = []
for i in range(n):
word = input()
if len(word) <= 10:
words.append(word)
else:
words.append(word[0] + str(len(word) - 2) + word[len(word) - 1])
for i in range(n):
print(words[i]) |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n,t=map(int,input().split())
arrangment=list(input())
for j in range(t):
i=0
while i<n-1:
if arrangment[i]=='B' and arrangment[i+1]=="G":
arrangment[i],arrangment[i+1]='G','B'
if i != n-1:
i+=1
i+=1
print(''.join(arrangment)) |
Given is a positive integer N.
We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.
* Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.
In how many choices of K will N become 1 in the end?
Constraints
* 2 \leq N ... | 3 | def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
# divisors.sort()
return divisors
n = int(input())
ans1 = make_divisors(n-1)
ans2 = make_divisors(n)
for i in ans... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | input()
l=list(map(int,input().split()));l.sort()
print(*l) |
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.
Every contestant hopes that he can find a... | 3 | import heapq
n = int(input()) * 2
ans = [-1] * (n + 1)
h = []
for i in range(2, n + 1):
j = 1
for e in input().split():
x = int(e)
heapq.heappush(h, [-x, i, j])
j += 1
i = 1
while True:
cur = heapq.heappop(h)
if ans[cur[1]] == -1 and ans[cur[2]] == -1:
ans[cur[1]] = c... |
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th... | 1 | def GetNumChickens(n):
for i in range(n):
for j in range(n):
if 3*i+7*j == n:
return 'YES'
return 'NO'
def main():
n = int(raw_input())
for i in range(n):
x = int(raw_input())
print GetNumChickens(x)
main()
|
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'... | 3 | def maximum(num, a):
if num % a == 0:
return (num//a)
else:
return(num//a + 1)
if __name__ == "__main__":
m, n, a = map(int,input().strip().split())
m1 = maximum(m, a)
n1 = maximum(n, a)
print(n1*m1)
|
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in... | 1 | s = raw_input()
poses = [[(1, 1), (3, 1)], [(1, 3), (2, 3), (3, 3), (4, 3)]]
idx = [0, 0]
for c in s:
print ' '.join(map(str, poses[int(c)][idx[int(c)]]))
idx[int(c)] += 1
idx[int(c)] %= len(poses[int(c)])
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n= int(input())
for _ in range(n):
s1 = input()
if(len(s1)<=10):
print(s1)
else:
print(s1[0],len(s1)-2,s1[-1],sep="")
|
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | 3 | n = int(input())
m = int(input())
drives = []
for i in range(n):
drives.append(int(input()))
drives = sorted(drives, reverse=True)
total_capacity = 0
i = 0
while (total_capacity < m):
total_capacity += drives[i]
i += 1
print(i) |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n,k=map(int,input().split())
for _ in range(k): n=n-1\
if n% 10 \
else n // 10
print(n) |
Illumination
Illuminations are displayed in the corridors every year at the JOI High School Cultural Festival. The illuminations consist of N light bulbs, which are lined up in a row from the west side to the east side of the corridor. Each light bulb is either on or off.
A machine that operates a light bulb is sleep... | 3 | # AOJ0603
illu = []
n = 0
def findmax(begin, end):
flag = illu[begin]
l = 1
maxlen = 1
for i in range(begin + 1, end + 1):
if illu[i] + flag == 1:
l += 1
else:
if l > maxlen:
maxlen = l
l = 1
flag = illu[i]
return maxlen i... |
Snuke has two boards, each divided into a grid with N rows and N columns. For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).
There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i... | 3 | n = int(input())
s = [input() for i in range(n)]
st = [str().join(s_) for s_ in zip(*s)]
cnt = 0
for i in range(n):
i_ = (n+i)%n
for k in range(n):
if s[k] != st[k]:
break
else:
cnt += 1
s = [s_[-1]+s_[:-1] for s_ in s]
st = [st[-1]] + st[:-1]
print(cnt*n) |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a, b =input().split()
a = int(a)
b = int(b)
i = 0
while a<= b:
i +=1
a =a*3
b =b*2
print (i)
|
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... | 3 | def makeString( n, a, b ) :
# final answer arr
res = []
# fill the substring 'a', by 'b' distinct element
arr = []
A = a
while a > 0:
for i in range(97 , 97 + b ) :
arr.append(chr(i))
a = a - b
a = A
arr = arr[:a]
sN = n
# make 'n' length array ... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | s = int(input())
if s%5 != 0:
print(s//5+1)
else:
print(s//5+0) |
Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.
Mishka can put a box i into another box j if the following conditions are met:
* i-th box is not put into another box;
* j-th box doesn't contain any other boxes;
* box i is smaller than box j (ai < aj).
Mishka ... | 1 | from itertools import groupby as goat
input()
count=0
nums=sorted(map(int, raw_input().split()))
while nums:
for k, v in goat(nums[:]):
nums.remove(k)
count+=1
print count |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | for _ in range(int(input())):
arr = [int(i) for i in input().split()]
arr.sort()
x, y, z = arr
if x < 0:
print("NO")
elif x == y == z:
print("YES")
print(x, x, x)
elif x == y != z:
print("NO")
elif x != y == z:
print("YES")
print(1, x, z)
e... |
We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.
For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate ... | 3 | # 解説放送の方針
# 平面走査をし、各点について、左上、左下、右上、右下にある点を数え、計算する。
# 解説放送ではBITを2本使っていたが、座標圧縮の結果を利用してBIT1本で済むようにした
N = int(input())
xy = [tuple(map(int,input().split())) for _ in range(N)]
mod = 998244353
class BIT:
'''https://tjkendev.github.io/procon-library/python/range_query/bit.html'''
def __init__(self, n):
sel... |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | for _ in range(int(input())):
n,a,b,c,d=map(int,input().split())
if(n*(a+b)<(c-d)):
print("No")
elif(n*(a-b)>(c+d)):
print("No")
else:
print("Yes") |
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what... | 3 | from sys import stdin, stdout
n = int(stdin.readline())
challengers = []
for i in range(n):
challengers.append(stdin.readline().strip())
challengers[i] += challengers[i]
length = len(challengers[0]) // 2
ans = float('inf')
for i in range(n):
current = 0
for j in range(n):
for z i... |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 1 | n, d = map(int, raw_input().split())
songs = map(int, raw_input().split())
if sum(songs) + (n-1) * 10 > d:
print -1
else:
print (d - sum(songs)) / 5
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 3 | dir = input()
sequence = input()
keys = ['qwertyuiop', 'asdfghjkl;', 'zxcvbnm,./']
for x in range(len(keys)):
keys[x] = list(keys[x])
x = -1 if dir == 'R' else 1
for char in sequence:
for row in range(len(keys)):
if char in keys[row]:
break
print(keys[row][keys[row].index(char)+x], ... |
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same tim... | 3 | a, b = map(int, input().split())
c, d = map(int, input().split())
ans = -1
dic = {}
for i in range(200):
dic[b + a*i] = 1
for i in range(200):
if d + i*c in dic:
print(d + i*c)
break
else:
print(-1) |
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp.
You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it... | 3 | n,a,b,k = map(int,input().split())
arr = list(map(int,input().split()))
for i in range(n):
arr[i] = arr[i]%(a+b)
if arr[i]==0:
arr[i] += (a+b)
arr[i] = (arr[i]-1)//a
ans = 0
arr.sort()
for i in range(n):
if arr[i]>k:
break
k -= arr[i]
ans += 1
print (ans) |
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | 1 | n = input()
A = map(int, raw_input().split())
x = [0]
for ii in range(len(A)):
x.append(x[-1] + A[ii])
x.sort()
res = [1-x[0]]
for ii in A:
res.append(res[-1] + ii)
for ii in res:
if ii < 1 or ii > n:
print -1
exit(0)
test = res[:]
test.sort()
for ii in range(1, len(test)):
if test[... |
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ... | 3 | def read_data():
n = int(input().strip())
a = list(map(int, list(input().strip().split())))
return n, a
n, a = read_data()
if max(a)>sum(a)//(n-1)+1:
print(max(a))
else:
if sum(a) % (n-1) == 0:
print(sum(a)//(n-1))
else:
print(sum(a)//(n-1)+1) |
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turn... | 3 | __author__ = 'Lipen'
def main():
n,m = map(int, input().split())
b = list(map(int, input().split()))
answer = [0]*n
for x in b:
for w in range(x-1, n):
if answer[w]==0:
answer[w]=x
s = ''
for x in answer:
s += str(x) + ' '
print(s[:-1])
main() |
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 ai. Team s... | 3 | a = input().split()
s = 0
for i in range (len(a)):
s = s + int(a[i])
if (s % 2 == 1):
print('NO')
else:
for i in range(4):
for j in range(i + 1, 5):
for b in range(i + j + 1, 6):
if int(a[i]) + int(a[j]) + int(a[b]) == s / 2:
print('YES')
... |
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
<image>
He ate coffee mi... | 1 | n=input()
numerals={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',30:'thirty',40:'forty',50:'fifty',60:'sixty',70:'seventy',80:'eighty... |
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.
The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.
Input
The first line of the input ... | 3 | num = int(input())
if num % 4 == 0 or num % 4 == 3:
print(0)
else:
print(1) |
Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card. The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner ... | 1 | import sys
def judge(word1, word2):
lena = len(word1)
lenb = len(word2)
for i in range(min(lena,lenb)):
if word1[i] > word2[i]: return 1
elif word1[i] < word2[i]: return 2
if lena > lenb: return 1
elif lena < lenb: return 2
else: return 0
p = 0
s = [0, 0, 0]
for line in sys.std... |
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt... | 3 | import math
t=int(input())
def check(n,d):
if d<=n:
return('YES')
for i in range(1,n):
a=math.ceil(d/(i+1))
if a+i<=n:
return('YES')
else:
return('NO')
for _ in range(t):
n,d=map(int,input().split())
print(check(n,d))
|
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.
... | 3 | n = int(input())
name,d = {},[input() for i in range(n)]
for i in d:
if i not in name:
name[i] = 0
print('OK')
else:
name[i] += 1
print(i+str(name[i]))
|
Tsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer a_i.
Yui loves sweets, but she can eat at most m sweets each day for health reasons.
Days are 1-indexed (numbered 1, 2, 3, …). Eating the sweet i at the d-t... | 3 | # It's never too late to start!
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math
import heapq
def sin():
return input()
def ain():
return list(map(int, sin()... |
You are given an integer number n. The following algorithm is applied to it:
1. if n = 0, then end algorithm;
2. find the smallest prime divisor d of n;
3. subtract d from n and go to step 1.
Determine the number of subtrations the algorithm will make.
Input
The only line contains a single integer n (2 ≤... | 3 | from math import sqrt
n = int(input())
if n % 2 == 0:
print(n // 2)
else:
for i in range(3,int(sqrt(n)) + 1, 2):
if n % i == 0:
n = n - i
break
else:
n = 0
print((n//2) + 1) |
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec... | 3 | a = eval(input())
for i in range(a):
lst1 = input().split()
lst2 = input().split()
a = eval(lst1[0])
b = eval(lst1[1])
c = eval(lst2[0])
d = eval(lst2[1])
if a+c==b==d or b+d==a==c or a+d==b==c or b+c==a==d:
print("YES")
else:
print("NO")
|
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.... | 3 | n=int(input())
m=[]
for i in range (n):
a,b,c=map(int,input().split())
if (a+b+c)>=2:
m.insert(i,1)
print(sum(m)) |
As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.
Snuke, an employee, would like to play with this sequence.
Specifically, he would like to repeat the following operation as many times as possible:
For every i satisfy... | 3 | N = int(input())
a = list(map(int, input().split()))
cnt = 0
for i in a:
while i%2 == 0:
i = i//2
cnt += 1
print(cnt) |
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... | 3 | n=int(input())
a=list(map(int,input().split()))
s=0
ss=0
for i in range(len(a)):
s+=a[i]
if a[i]==-1 and s<0:
s=0
ss+=1
print(ss)
|
Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.
Input
The first line contains two integers n and k (2 ≤ n ≤ 100000, 1 ≤ k ≤ 20).
Output
If it's impossible to find the representation of n as a product of k... | 3 | import math
[n,k] = [int(i) for i in input().split()]
v = []
def Find(n,k):
if(k==1):
v.append(n)
return
p = FD(n)
if(p==-1):
v.append(n)
return
v.append(p)
Find(n/p,k-1)
def FD(n):
for i in range(2,int(math.sqrt(n)+1)):
if(n%i==0):
r... |
On the way to Dandi March, Gandhijee carried a mirror with himself. When he reached Dandi, he decided to play a game with the tired people to give them some strength. At each turn of the game he pointed out a person and told him to say a number N(possibly huge) of his choice. The number was called lucky if that equals ... | 1 | import re
for i in range(input()):
a=raw_input()
b='018'
if re.search(r'2|3|4|5|6|7|9',a):
print 'NO'
elif a==a[::-1]:
print 'YES'
else:
print 'NO' |
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other.
<image> The example of two segments on the x-axis.
Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an... | 3 | n=int(input())
for k in range(n):
a,b,c,d=map(int,input().split())
L=[(a,b,0),(c,d,1)]
L=sorted(L)
L1=[0,0]
L1[L[0][2]]=L[0][0]
L1[L[1][2]]=L[1][1]
print(L1[0],L1[1])
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a=int(input())
if a>=1 and 100>=a and a%2==0 and a!=2:
print('YES')
else:
print('NO')
|
You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.
One operation of a cyclic shift (rota... | 3 | s = input()
for _ in range(int(input())):
l, r, k = map(int,input().split())
n = (r - l + 1)
k = k%n
s = s[:l-1] + s[r-k:r] + s[l-1:r-k] + s[r:]
print(s) |
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1... | 1 | from __future__ import division,print_function
from heapq import*
import sys
le = sys.__stdin__.read().split("\n")[::-1]
af=[]
for zorg in range(int(le.pop())):
n=int(le.pop())
x= list(map(int,le.pop().split()))
y=[0]
for k in range(1,n):
last=y[-1]^x[k-1]
#last & (x[k]^newy)=last
... |
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.
Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n... | 3 | n = int(input())
x = input()
ones = 0
for i in x:
if i=='1':
ones += 1
mods = [0, 0]
for i in range(n):
if x[n-i-1]=='1':
if ones>1:
mods[0] += pow(2, i, ones-1)
mods[1] += pow(2, i, ones+1)
if ones>1:
mods[0] %= ones-1
mods[1] %= ones+1
def f(x):
if x==0:
ret... |
Print all the integers that satisfies the following in ascending order:
* Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.
Constraints
* 1 \leq A \leq B \leq 10^9
* 1 \leq K \leq 100
* All values in input are integers.
Input
Input is give... | 3 | A, B, K = map(int, input().split())
for n in sorted(filter(lambda n: A <= n <= B , set(range(A, A + K)) | set(range(B - K + 1, B + 1)))):
print(n)
|
Alica and Bob are playing a game.
Initially they have a binary string s consisting of only characters 0 and 1.
Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char... | 3 | import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
s = input()[:-1]
zero, one = s.count('0'), s.count('1')
c = min(zero, one)
if c%2==0:
print('NET')
else:
print('DA') |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | n,k=input().split()
ls=[]
n=int(n)
for i in range(int(k)):
ls.append(list(map(int,input().split())))
ls.sort()
flag=0
for i in ls:
if i[0]<n:
n+=i[1]
else:
flag=1
break
if flag==0:
print("YES")
else:
print("NO")
|
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | ans = 0
res = 0
for _ in range(int(input())):
a,b = map(int,input().split())
ans+=(b-a)
res = max(res,ans)
print(res)
|
Let's consider all integers in the range from 1 to n (inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≤ a < b ≤ n.
The greatest common divisor, gcd(a, b), of two positive integ... | 3 | n=int(input())
for i in range(n):
x=int(input())
print(x//2) |
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase.
A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD... | 3 | from string import ascii_uppercase as a
inf = float("inf")
n, k = map(int, input().split())
s = input()
m = inf
for i in range(k):
x = s.count(a[i])
m = min(m, x)
print(m*k)
|
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two... | 3 |
I=lambda:list(map(int,input().split()))
import collections as cc
for tc in range(int(input())):
n,=I()
s=list(input())
t=list(input())
tf=1
for i in range(n):
if s[i]>t[i]:
tf=0
break
if not tf:
print(-1)
continue
else:
ans=1
for i in 'abcdefghijklmnopqrst':
temp='u'
for j in range(n):
... |
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, …, b_n: ... | 3 | n = int(input())
b = list(map(int,input().split()))
m = [0]
a = []
for i in range(n):
a.append(b[i]+m[i])
m.append(max(m[i],a[i]))
# print(i,a)
print(*a,sep=' ') |
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turn... | 3 | import sys
file = sys.stdin
__author__ = 'RaiaN'
n, m = file.readline().split(' ')
n = int(n)
m = int(m)
ms = [int(val) for val in file.readline().split(' ')]
dsb = [0]*n
for val in ms:
for i in range(val-1, n):
if dsb[i] == 0:
dsb[i] = val
print(' '.join(str(x) for x in dsb)) |
You have a given integer n. Find the number of ways to fill all 3 × n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
<image> This picture describes when n = 4. The left one is the shape and the right one is 3 × n tiles.
Input
The only line cont... | 3 | from math import floor
size = int(input())
if size%2==1:
print("0")
else:
ans = int(pow(2, size/2))
print(ans) |
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | 1 | s = raw_input()
pos = max(0,s.find('0'))
print s[0:pos] + s[pos+1:]
|
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'... | 3 | a, b, c = map(int, input().split())
if a % c == 0:
a = a / c
else:
a = int(a / c) + 1
if b % c == 0:
b = b / c
else:
b = int(b / c) + 1
print(int(a*b))
|
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip ... | 3 | from sys import stdin
from math import *
def h(seq):
return sorted(range(len(seq)), key=seq.__getitem__)
line = stdin.readline().rstrip().split()
m = int(line[0])
k = int(line[1])
numbers = list(map(int, stdin.readline().rstrip().split()))
arrNum = h(numbers)
positions = list(reversed(arrNum))[:k]
positions.sor... |
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | m = 0
for i in range(5):
l = list(map(int, input().split()))
if 1 in l:
x = l.index(1)
y = i
print(abs(2-x) + abs(2-y)) |
You have a digit sequence S of length 4. You are wondering which of the following formats S is in:
* YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order
* MMYY format: the two-digit representation of the month and the last t... | 3 | s = input()
a = int(s[:2])
p = int(s[-2:])
if 0<a<=12 and 0<p<=12:
print('AMBIGUOUS')
elif 0<a<=12:
print('MMYY')
elif 0<p<=12:
print('YYMM')
else:
print('NA') |
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.
Input
The single line of the input contains a pa... | 3 | '''
Fuad Ashraful Mehmet
University of Asia Pacific
Category:combinatorics +data structure
'''
n,s=map(int,input().split())
if n==1 and s==0:
print(0,0)
elif 9*n<s or s==0:
print(-1,-1)
else:
res1=10**(n-1)
for i in range(s-1):
res1+=10**(i//9)
res2=0
for i in range(s):
res2+=10**(n-1-i//... |
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four... | 3 | T = int(input())
for i in range(T):
ai = list(map(int, input().split(' ')))
print(ai[0]+ai[1]+ai[2]-1) |
There was once young lass called Mary,
Whose jokes were occasionally scary.
On this April's Fool
Fixed limerick rules
Allowed her to trip the unwary.
Can she fill all the lines
To work at all times?
On juggling the words
Right around two-thirds
Sh... | 3 |
n = int(input())
ans=""
for i in range(2,n):
if n%i==0:
ans+=str(i)+str(n//i)
break
print(ans)
|
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 1 | n = input();a = map(int, raw_input().split())
b,c,d = a.count(1), a.count(2), a.count(3)
s = n - b - c;t = c * 2;b -= d
if b > 0: t += b
s += t / 4
if t % 4: s += 1
print(s) |
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ... | 1 | R=lambda:map(int,raw_input().split())
n,m=R()
a=map(lambda x: (x + m - 1) / m, R())
a.reverse()
print n-a.index(max(a)) |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | import math
def main():
t = input()
if len(t) % 2 == 0:
center = int(len(t) / 2 - 1)
else:
center = math.ceil(len(t) / 2 - 1)
#print(center)
if len(t) < 2:
print(t)
return
s = t[center]
n = 0
d1 = 1
d2 = 1
#print(t[center])
for i in range(len(t... |
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.
Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.
Now Dreamoon concatenates these two permutations into another sequence a of length... | 1 | """Template for Python Competitive Programmers prepared by Mayank Chaudhary """
# to use the print and division function of Python3
from __future__ import division, print_function
"""value of mod"""
MOD = 998244353
mod = 10**9 + 7
"""use resource"""
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, [0x10... |
We have N gemstones labeled 1 through N.
You can perform the following operation any number of times (possibly zero).
* Select a positive integer x, and smash all the gems labeled with multiples of x.
Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of ... | 3 | from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
fro... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ... | 3 | n, k = map(int, input().split())
s = list(map(int, input().split()))
participants = 0
for i in range(n):
if s[i]>=s[k-1] and s[i]>0:
participants += 1
print(participants)
|
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as ... | 3 | import sys
readline = sys.stdin.readline
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
def solve():
n = ni()
if n == 2:
print(0)
return
edges = [tuple(nm()) for _ in range(n-... |
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'... | 3 | ts_input = [int(i) for i in input().split(' ')]
"""
if int((ts_input[0]*ts_input[1])/(ts_input[2]**2)) == (ts_input[0]*ts_input[1])/(ts_input[2]**2):
print((ts_input[0]*ts_input[1])/(ts_input[2]**2))
else:
print(int((ts_input[0]*ts_input[1])/(ts_input[2]**2))+1)
"""
output = 0
if int(ts_input[0]/ts_input[2]) ==... |
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All valu... | 1 | n,k = map(int, raw_input().split())
from fractions import gcd
if n % k== 0:
print 0
else:
mini = n
s = set()
while True:
if n > k:
n = n % k
else:
n = abs(n-k)
mini = min(n, mini)
if n in s:
print mini
break
s.add(n)
|
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | x=input()
y=int(x)+1
def k(i):
return str(y).count(str(y)[i])
while k(0)+k(1)+k(2)+k(3)!=4:
y+=1
print(y) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.