problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 i in range(n):
s=input()
if len(s)>10:
r=s[0]+str(len(s)-2)+s[-1]
print(r)
else:
print(s) |
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and foun... | 3 | s = input()
x = int(s[0] + s[2] + s[4] + s[3] + s[1])
print(str(x**5)[-5:]) |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 3 | class Solution:
def __init__(self):
self.n, self.m = [int(x) for x in input().split()]
self.a, self.b = [], []
for _ in range(self.m):
a, b = [x for x in input().split()]
self.a.append(a)
self.b.append(b)
self.c = [x for x in input().split()]
... |
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | for i in range(int(input())):
n, m = [int(num) for num in input().split()]
if n == 1:
print(0)
elif n == 2:
print(m)
else:
print(2 * m)
|
You are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0.
You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 × 2, and replace every element in the chosen sub... | 3 | n,m=[int(x) for x in input().split()]
a=[[int(x) for x in input().split()] for j in range(n)]
b=[[0 for i in range(m)]for j in range(n)]
x=[]
count=0
def check(a,i,j,n,m):
if(i+1<n and j+1<m and a[i][j]==1 and a[i][j+1]==1 and a[i+1][j]==1 and a[i+1][j+1]==1):
return True
return False
for i in range(n)... |
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at... | 3 | def main():
from itertools import chain
from math import hypot
l = list(map(float, input().split()))
xa, xb = sorted(l[::2])
ya, yb = sorted(l[1::2])
l = []
for _ in range(int(input())):
x, y, r = map(float, input().split())
if not (x + r < xa or x - r > xb or y + r < ya or y... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | a = list(map(int, input().split()))
s = str(input())
x = s.count("1")
y = s.count("2")
z = s.count("3")
w = s.count("4")
print(a[0]*x + a[1]*y + a[2]*z + a[3]*w) |
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation ⊙ of two ternary n... | 3 | for _ in range(int(input())):
n = int(input())
number = input()
a = []
b = []
flag = 0
for c in number:
if c == '2':
if flag == 0:
a.append('1')
b.append('1')
else:
b.append('2')
a.append('0')
... |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n=int(input())
li=[input() for i in range(n)]
li2=[li[0]]
m=0
for i in li:
if(li2[m]!=i):
li2.append(i)
m+=1
print(len(li2)) |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | inp=input()
i=inp.replace('WUB'," ")
l=i.strip()
print(l) |
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 3 | import sys
t = sys.stdin.readline()
def main(l,n):
od = 0
ev = 0
for i in l:
if i%2 == 1:
od += 1
else:
ev += 1
if od%2 == 1 and od == n:
return 'Yes'
if od == 0:
return 'No'
if n%2 == 0:
if n <= od:
if ... |
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he... | 3 | t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(n-1):
ans+=max(a[i]-a[i+1],0)
print(ans) |
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can... | 3 |
def findMinHours(hours, chapters):
total_time = 0
for item in sorted(chapters):
total_time += item*hours
hours -=1
if(hours < 1):
hours = 1
return total_time
#input
subjects, hours = list(map(int, input().split()))
chapters = list(map(int, input().split()))
print(findMinHours(hou... |
"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!).
<image> illustration by 猫屋 https://twitter.com/nekoy... | 3 | import itertools
n = list(input())
a = []
for i in range(len(n)):
if(n[i] == 'Q' or n[i] == 'A'):
a.append(n[i])
# print(a)
a = list(itertools.combinations(a,3))
for i in range(len(a)):
a[i] = ''.join(a[i])
# print(a)
print(a.count('QAQ')) |
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... | 3 | from math import *
import sys
import collections
from random import*
sys.setrecursionlimit(99999)
eps = sys.float_info.epsilon
def is_prime(n):
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
def solve():
try:
n = int(input())
x = l... |
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ... | 1 | str = raw_input()
len = len( str )
n = int( raw_input() )
s = map( int , raw_input().split() )
#print str
s = sorted(s)
k = 0
#print s[k]
str = list(str)
for i in xrange(0 ,len/2):
# print i
while k < n and s[k]-1 <= i :
k+=1
# print i , k
if k%2 == 1 :
str[i],str[len-i-1] = str[len-... |
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessar... | 3 | n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
b=a[n-k:]
print(min(b)) |
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a... | 3 | t = int(input())
for i in range(t):
n,d = list(map(int, input().split()))
piles = list(map(int, input().split()))
sol = piles[0]
piles.pop(0)
k = 0
while d > 0 and k<len(piles):
count = piles[k]
cost = k+1
possible = d//cost
if (possible == 0):
bre... |
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | 3 | f = lambda l, r: abs(l - r) > 1 and l >= 0 and r >= 0
(lambda s: print('YES' if f(s.find('AB'), s.rfind('BA')) or f(s.find('BA'), s.rfind('AB')) else 'NO'))(input()) |
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())
if 1<=n<=100:
for i in range(n):
word=input().lower()
if len(word)<=10:
print(word)
if len(word)>10:
print(word[0],len(word)-2,word[-1],sep='')
|
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro... | 3 | from math import gcd
for T in range(int(input())):
n = int(input())
a = sorted(list(map(int, input().split())), reverse = True)
g = a[0]
for i in range(n):
Max = 0
ind = i
for j in range(i, n):
if gcd(g, a[j]) > Max :
Max = gcd(g,a[j])
... |
Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.
Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle ... | 1 | n = int(raw_input())
x = []
y = []
for _ in range(n):
a,b = raw_input().split()
x.append(int(a))
y.append(int(b))
no = [False]*n
for i in range(len(x)):
for j in range(len(y)):
if i != j and x[i] == y[j] and no[i] is False:
n-=1
no[i]=True
print n |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | l = [int(i) for i in input().split()]
soma = 0
l.sort()
print(l[3] - l[2], end = " ")
print(l[3] - l[1], end = " ")
print(l[3] - l[0])
|
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he sh... | 3 | n, m, k = map(int, input().split())
ans = []
append = ans.append
x, y = 1, 1
r_cnt = (m-1) // 4
if r_cnt:
ans.append((r_cnt, 'RRRR'))
x += r_cnt * 4
if x < m:
ans.append((1, 'R'*(m-x) + 'L'*min(m-1, 4-(m-x))))
x = m - min(m-1, 4-(m-x))
l_cnt = (x-1) // 4
if l_cnt:
ans.append((l_cnt, 'LLLL'))
x -= l_cnt... |
You are given 4n sticks, the length of the i-th stick is a_i.
You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only... | 3 | def valid(numbers,area):
for n in numbers.keys():
if area%n:
return False
if numbers[n]%2:
return False
if numbers[n] != numbers.get(area//n,0):
return False
return True
for _ in range(int(input())):
input()
b = {}
for a in map(int,input().... |
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... | 3 |
s=input()
cL=0
cU=0
for i in s:
if(i.islower()):
cL+=1
else:
cU+=1
if(cL>=cU):
print(s.lower())
else:
print(s.upper()) |
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 | def load():
matrix = []
for i in range(0, 5):
inp = list(input().rstrip().split())
matrix.append(inp)
return matrix
def locate(matrix):
f = False
location = ()
for string in matrix:
if f != True:
if '1' in string:
location = (string.index('1')... |
You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.
According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is... | 3 | n=input()
listA=list(map(int,input().split()))
flag="APPROVED"
for i in listA:
if i % 2 ==0 and i % 3 != 0 and i % 5 != 0:
flag="DENIED"
print(flag)
|
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d... | 3 | """
~~ Author : Bhaskar
~~ Dated : 31~05~2020
"""
# Method: Prefix Subarray & Binary Search :->
import sys
from bisect import *
from math import floor,sqrt,ceil,factorial as F,gcd,pi
from itertools import chain,combinations,permutations,accumulate
from collections import Counter,defaultdict,OrderedDict,deque
from arr... |
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | 3 | n = input()
n = int(n.strip())
niz = input()
niz = niz.strip()
resitev = niz[-1]
for k in range(len(niz) - 2, -1, -1):
dol = len(resitev)
if dol % 2 == 0:
resitev = resitev[:dol//2] + niz[k] + resitev[dol//2:]
else:
delim = (len(resitev) - 1) // 2
resitev = resitev[:delim] + niz[k]... |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 3 | x=int(input())
for i in range(0,x):
n,m=[int(a) for a in input().split()]
if(n>m):
if(n%2==m%2):
s=0
else:
s=1
else:
s=abs(m-n)
print(s)
|
A median in an array with the length of n is an element which occupies position number <image> after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.
We define... | 3 | n, x = map(int, input().split())
t = list(map(float, input().split()))
p = [0] * 3
for i in t:
p[1 + (i > x) - (i < x)] += 1
d = int(p[1] == 0)
p[1] += d
x = abs(p[2] - p[0]) - p[1]
print(d + max(0, x + int(p[0] > p[2]))) |
You are given an array a consisting of n integers a_1, a_2, ..., a_n. You want to split it into exactly k non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the e... | 3 | import sys
q = int(input())
for _ in range(q):
n, k = map(int, input().split())
nums = list(map(int, sys.stdin.readline().split()))
cntodd = 0
for x in nums:
if x % 2 == 1:
cntodd += 1
if cntodd < k or cntodd % 2 != k % 2:
sys.stdout.write("NO\n")
else:
sys.stdout.write("YES\n")
for i in range(n):
... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | def solve():
name = input()
if len(set(name)) % 2 != 0:
print("IGNORE HIM!")
else:
print("CHAT WITH HER!")
if __name__ == "__main__":
solve() |
In the Kingdom of AtCoder, only banknotes are used as currency. There are 10^{100}+1 kinds of banknotes, with the values of 1, 10, 10^2, 10^3, \dots, 10^{(10^{100})}. You have come shopping at a mall and are now buying a takoyaki machine with a value of N. (Takoyaki is the name of a Japanese snack.)
To make the paymen... | 3 | S = map(int, input())
a, b = 0, 1
for s in S:
a, b = min(a + s, b + 10 - s), min(a + (s + 1), b + 10 - (s + 1))
print(a) |
«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 ... | 3 | k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
c=[k,l,m,n]
z=0
for i in range(1,d+1):
for j in range(len(c)):
if(i%c[j]==0):
z+=1
break
print(z)
|
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.
So they play with each other according to following rules:
... | 3 | x = int(input())
a = [int(input()) for i in range(x)]
# print(a)
# print(len(a))
k = 0
t = 0
t1 = 0
if a[0] == 3:
print("NO")
k = 1
elif x == 1:
if a[0] == 3:
print("NO")
k = 1
else:
print("YES")
k = 1
elif a[0] == 1:
t = 1
t1 = 2
elif a[0] == 2:
t = 2
t1 = 1
for i in range(x-1):
# print(i)
# pri... |
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ... | 1 | n = int(raw_input())
l = len(raw_input().split('0')[0])+1
print min(n,l)
|
You're given an array a_1, …, a_n of n non-negative integers.
Let's call it sharpened if and only if there exists an integer 1 ≤ k ≤ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:
* The arrays [4], [0, 1], [... | 3 | for _ in range(int(input())):
n=int(input());s=list(map(int,input().split()))
c=x=1;l=[0]*n;k=[0]*n
for i in range(n):
k[i] = int(s[i]>=i)
l[i]=int(s[i]>=n-i-1)
p=q=r=w=-1
for i in range(n):
if k[i]==0 and p==-1:
p=i
if l[i]==0:
q=i
if ... |
You are given a sequence A_1, A_2, ..., A_N and an integer K.
Print the maximum possible length of a sequence B that satisfies the following conditions:
* B is a (not necessarily continuous) subsequence of A.
* For each pair of adjacents elements of B, the absolute difference of the elements is at most K.
Constraint... | 3 | class Segment_Tree():
"""
このプログラム内は1-index
"""
def __init__(self,L,calc,unit):
"""calcを演算とするリストLのSegment Treeを作成
calc:演算(2変数関数,モノイド)
unit:モノイドcalcの単位元 (xe=ex=xを満たすe)
"""
self.calc=calc
self.unit=unit
N=len(L)
d=max(1,(N-1).bit_length())
... |
Given are N points (x_i, y_i) in a two-dimensional plane.
Find the minimum radius of a circle such that all the points are inside or on it.
Constraints
* 2 \leq N \leq 50
* 0 \leq x_i \leq 1000
* 0 \leq y_i \leq 1000
* The given N points are all different.
* The values in input are all integers.
Input
Input is giv... | 3 | n=int(input())
xy=[list(map(int,input().split()))for _ in range(n)]
def gaisin(a,b,c,d,e,f):
if (a-c)*(d-f)==(c-e)*(b-d):return ["ng"]
aa=a**2
bb=b**2
cc=c**2
dd=d**2
ee=e**2
ff=f**2
py=((e-a)*(aa+bb-cc-dd)-(c-a)*(aa+bb-ee-ff))/(2*((e-a)*(b-d)-(c-a)*(b-f)))
if a==c:px=(2*(b-f)*py-aa-bb+ee+ff)/(2*(e-a)... |
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he... | 3 | #from collections import defaultdict
#import copy
def ii():return int(input())
def si():return input()
def li():return list(map(int,input().split()))
def mi():return map(int,input().split())
for _ in range(ii()):
n=ii()
arr=li()
fin=[0]*n
for i in range(n-1):
if (arr[i]>arr[i+1]):
f... |
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.
Each tool can be sold for exactly one emerald. How many... | 1 | def f(a,b):
if b < a:
return f(b,a)
x = min(a, b/2, b - a)
if x == 0:
t = min(a,b)/3
a -= t * 3
b -= t * 3
return 2 * t + (1 if ((a and b >=2) or (b and a >= 2)) else 0)
else:
return x + f(a- x, b - 2 * x)
for _ in range(int(raw_input())):
a,b = map(int, raw_input().split(' '))
print f(a,b)#,m, [map... |
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 | for i in range(int(input())):
a=input()
if len(a)>10:
print(a[0]+str((len(a)-2))+a[len(a)-1])
else:
print(a)
|
In mathematics, the absolute value (or modulus) |a| of a real number a is the numerical value of a without regard to its sign. So, for example, the absolute value of 3 is 3, and the absolute value of -3 is also 3. The absolute value of a number may be thought of as its distance from zero.
Input
There is a single pos... | 1 | a=int(raw_input())
for b in range(a):
c=int(raw_input())
print abs(c) |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 3 | n=int(input())
a=list(input())
left=a.count('L')
right=a.count('R')
total=left+right+1
print(total) |
A frog is about to return to the burrow. The burrow is D centimeters ahead of the frog, and the frog goes straight toward the burrow. There are only two actions that a frog can do:
* Large jump (go forward L centimeters)
* Small jump (go 1 cm forward)
The frog aims to just land in the burrow without jumping over it... | 3 | d, l = map(int, input().split())
cnt = d // l + d % l
print(cnt)
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | s=input()
l=list(s)
d={'a','e','i','o','u','y','Y','A','E','I','O','U'}
s1=''
for i in range(len(l)):
if(l[i] in d):
continue
elif(l[i].isupper()):
s1+='.'+l[i].lower()
else:
s1+='.'+l[i]
print(s1)
|
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | from math import ceil
for _ in range(int(input())):
n,m = map(int,input().split())
print((m*ceil(n/m))-n) |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | t = int(input())
ans=[0]*t
for i in range(t):
n,k=map(int, input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
for j in range(k):
mina=min(a)
maxb=max(b)
indexa=a.index(mina)
indexb=b.index(maxb)
if mina<=maxb:
a[indexa]=maxb
b[indexb]=mina
#p... |
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | 3 | n=int(input())
l=list(map(int,input().split()))
l.sort()
ans=0
curr=int(1e6)
for i in range(n-1,-1,-1):
if(l[i]<(curr-1)):
curr=l[i]+1
ans+=1
elif(l[i]==(curr-1)):
curr=l[i]
ans+=1
elif(l[i]==curr and curr>1):
curr=l[i]-1
ans+=1
print(ans) |
An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme.
Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:
... | 3 | import sys
def read_two_int():
return map(int, sys.stdin.readline().strip().split(' '))
def fast_solution(n, U, E):
best = -1
R = 2
for i in range(n-2):
# move R forcefully
R = max(R, i+2)
while (R + 1 < n) and (E[R+1] - E[i] <= U):
R += 1
if E[R] - E[i] <= U:
efficiency = float(E[R] - E[i+1]) / ... |
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$
Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes.
Your task is calculate a_{K} for given a_{1} and K.
Input
The ... | 3 | for _ in range(int(input())):
l=input().split()
if l[1]=='1':
print(l[0])
else:
l[1]=int(l[1])
x=int(l[0])
for i in range(2,l[1]+1):
x=x+int(min(list(str(x))))*int(max(list(str(x))))
if '0' in str(x):
break
print(x)
... |
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property.
Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=... | 3 | for _ in range(int(input())):
s=input()
n=len(s)
if s.count("0")==n:
print(s)
elif s.count("1")==n:
print(s)
else:
x=""
for i in range(n):
x+="01"
print(x)
|
After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.
Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi... | 3 | n = int(input())
L = []
for i in range(n): L.append([int(x)for x in input().split()])
x = int(input())
for i in L:
if i[0] <= x <= i[1]: print(len(L) - L.index(i))
|
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral.
Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the... | 3 | n = int(input())
t = [int(i) for i in input().split()]
d = t[1] - t[0]
for i in range(2, n):
if d != t[i] - t[i-1]:
d = 0
print(t[n-1] + d)
|
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 | n,m=list(map(int,input().split()))
a=[]
for i in range(0,n):
a.append(input())
b=list(map(int,input().split()))
s=0
for i in range(0,m):
c=[0]*5
for j in range(0,n):
c[ord(a[j][i])-65]+=1
s=s+max(c)*b[i]
print(s)
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 1 | if __name__=="__main__":
a = map(int,raw_input().split())
s = raw_input()
c = 0
for i in range(len(s)):
c+= a[int(s[i])-1]
print c
|
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | # code by RAJ BHAVSAR
for _ in range(int(input())):
n,x = map(int,input().split())
if(n <= 2):
print(1)
else:
ans = 1
s = 2
while(True):
if(s >= n):
break
s += x
ans += 1
print(ans) |
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 | n=int(input())
i=1
while True:
if i*(i+1)*(i+2)>6*n:
print(i-1)
break
else:
i=i+1
|
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please hel... | 3 | n=int(input())
if(n==0):
print(1)
if (n>0):
if (n%4==1):
print(8)
elif (n%4==2):
print(4)
elif (n%4==3):
print(2)
elif (n%4==0):
print(6)
|
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t... | 3 | import sys
input = sys.stdin.readline
for _ in range(int(input())):
_ = input()
a = list(map(int, input().split()))
a.sort()
ans = 0
for i, ai in enumerate(a, 1):
if ai <= i:
ans = i
print(ans + 1)
|
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 1 | from Queue import *
inp = raw_input().split(' ')
m = int(inp[0])
n = int(inp[1])
visited = {}
visited[m] = 0
q = Queue()
q.put(m)
while(q.qsize() > 0):
current = q.get()
if current == n:
print visited[current]
break
red = current * 2
if red > 0 and red not in visited and n > current:
q.put(red)
... |
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ... | 3 | from sys import stdin
def main():
stdin.readline()
A = list(map(int, stdin.readline().strip().split()))
menor = 101
ans = 101
for x in A:
if x < menor:
ans = menor
menor = x
elif x != menor and x < ans:
ans = x
if ans == 101:
print("NO")
else:
print(ans)
main()
... |
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.
In this task, a pattern will be a string con... | 1 | def solve():
n = int(raw_input())
tmp = raw_input()
ans = []
for i in tmp:
ans.append(i)
for i in range(n-1):
tmp = raw_input()
for i in range(len(tmp)):
if ans[i] != tmp[i]:
if ans[i] == "?":
ans[i] = tm... |
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg... | 3 | import sys
n = int(input())
a = [0]*(n+1)
for i in range(n):
l, r = map(int, sys.stdin.readline().split())
a[i+1] = l-r
a[0] += l-r
a[1:] = [a[0]-2*a[i] for i in range(1,n+1)]
a2 = [abs(i) for i in a]
ma2 = max(a2)
idx = a2.index(ma2)
print(idx)
|
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | X = list(map(int, input().split()))
X.sort()
print(str(X[-1]-X[0])+' '+str(X[-1]-X[1])+' '+str(X[-1]-X[2])) |
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white.
You think that this picture is not interesting enough. You consider a picture to be interesting... | 3 | for _ in[0]*int(input()):a=[input()for _
in[0]*int(input().split()[0])];b,c=([x.count('.')for x
in y]for y in(a,zip(*a)));print(min(s+t-(x>'*')for
r,s in zip(a,b)for x,t in zip(r,c))) |
Paul was the most famous character in Tekken-3. Of course he went to college and stuff. In one of the exams he wasn't able to answer a question which asked to check if a tuple of 3 non negative integers constituted a Primitive Pythagorian Triplet or not. Paul was not able to answer it correctly and henceforth, he coul... | 1 | t=input()
for j in range(t):
a,b,c=map(int,raw_input().split())
x=a
y=b
flag=0
while(y):
x,y=y,x%y
flag+=x
y,z=b,c
while(z):
y,z=z,y%z
flag+=y
x,z=a,c
while(x):
z,x=x,z%x
flag+=z
a,b,c=a*a,b*b,c*c
if(flag==3 and (a+b==c or b+c==a or a+c==b)):
print "YES"
else:
print "NO" |
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:
* multiply the current number by 2 (that is, replace the number x by 2·x);
* append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1).
You need to help Vasil... | 3 |
def get_ops_list(a, b):
if a == b:
return [a]
elif a > b:
return []
k = a * 2
ops = get_ops_list(k, b)
if len(ops) > 0:
return [a, *ops]
else:
k = 10 * a + 1
ops = get_ops_list(k, b)
if len(ops) > 0:
return [a, *ops]
else... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | import sys
p = input()
for i in p:
if i == 'H' or i == '9' or i == 'Q':
print("YES")
sys.exit()
print("NO") |
There are N people living on a number line.
The i-th person lives at coordinate X_i.
You are going to hold a meeting that all N people have to attend.
The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to atte... | 3 | n=int(input())
l=list(map(int,input().split()))
import statistics as st
m=round(st.mean(l))
print(sum((m-i)**2 for i in l)) |
Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms:
* Everyone must gift as many coins as others.
* All coins given to Ivan must be different.
* Not l... | 3 | n,m,k,l=map(int,input().split(' '))
if n<m:
print(-1)
elif n==m:
if k+l>n:
print(-1)
else:
print(1)
else:
if k+l>n:
print(-1)
else:
if (k+l)%m ==0:
x=(k+l)//m
print(x)
else:
x=(k+l)//m+1
if m*x>n:
... |
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.
We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,... | 3 | #!/usr/bin/env python
from functools import reduce
from itertools import combinations
def inner_prod(v1, v2):
assert len(v1) == len(v2)
return reduce(lambda acc, pair: acc + pair[0] * pair[1], zip(v1, v2), 0)
def vec_diff(v1, v2):
assert len(v1) == len(v2)
return list(map(lambda pair: pair[0] - pair[1... |
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())
problems = [input().split() for i in range(n)]
possible = 0
for problem in problems:
total = 0
for val in problem:
total += int(val)
if total >= 2:
possible += 1
print(possible)
|
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the f... | 3 | from sys import stdin
import math
inp = lambda: stdin.readline().strip()
n, m = [int(x) for x in inp().split()]
adj = [[] for x in range(n)]
ans = 0
bad = []
for i in range(m):
a, b = [int(x) for x in inp().split()]
adj[a-1].append(b-1)
adj[b-1].append(a-1)
while True:
for i in range(n):
if le... |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | mensAm = int(input())
mens = list(map(int,input().split()))
girlsAm = int(input())
girls = list(map(int,input().split()))
mens.sort()
girls.sort()
t = 0
was = [False]*girlsAm
for i in range(mensAm):
for g in range(girlsAm):
if abs(girls[g] - mens[i]) <= 1 and not was[g]:
t+=1
was[g]... |
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.
Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers:
[l1, r1], [l2... | 3 | n, m, k = map(int, input().split())
lst = list(map(int, input().split()))
if m == 1:
print(sum(sorted(lst)[-k:]))
exit()
s = sum(lst[:m])
i, j = 0, m
l = [s]
while j < n:
s = s - lst[i] + lst[j]
i +=1
j += 1
l.append(s)
n = len(l)
dp = [[0] * (n+1) for i in range(k+1)]
for i in range(1, n+1):
dp[1][i] = max(dp... |
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 ... | 1 | l = list()
n = input()
i = 1
for a in map(int, raw_input().split()):
l.append((a, i))
i += 1
l.sort()
i, j = 0, n - 1
while i < j:
print l[i][1], l[j][1]
i += 1
j -= 1
|
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.
Constraints
* 1 \leq K \leq N \leq 1000
* 1 \leq... | 3 | n,k=map(int,input().split())
a=[int(v) for v in input().split()]
a.sort()
print(sum(a[:k]))
|
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 | import math
for i in range(int(input())):
a,b=sorted(map(int,input().split()))
if(b%a!=0):
print(-1)
continue
else:
y=b//a
k=round(math.log2(y))
if(2**k!=y):
print(-1)
continue
print((k+2)//3)
|
Joisino is planning to record N TV programs with recorders.
The TV can receive C channels numbered 1 through C.
The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i.
Here, there will never be more than one program that are broadcast on ... | 3 | n,C = map(int,input().split())
d = [[0]*C for i in range(10**5)]
for i in range(n):
s,t,c = map(int,input().split())
for j in range(s-1,t):
d[j][c-1] = 1
#print(d)
a = 1
for i in range(10**5):
s = sum(d[i])
if s > a:
a = s
print(a) |
Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.
The hall also turned out hexagonal in its shape. The King walked along the perimeter of ... | 1 | a, b, c = map(int, raw_input().split())
print a * b + b * c + a * c - a - b - c + 1 |
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it `CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single space between the fi... | 1 | s = raw_input()
print s[:4] + ' ' + s[4:] |
Given an integer x, find 2 integers a and b such that:
* 1 ≤ a,b ≤ x
* b divides a (a is divisible by b).
* a ⋅ b>x.
* a/b<x.
Input
The only line contains the integer x (1 ≤ x ≤ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | x = int(input())
if x==1:
print(-1)
elif x%2==0:
print((x),2)
else:
print((x-1),2) |
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 | from math import ceil
n,m,a = map(int,input().split())
if (n*m) % (a*a) == 0 and n%a!=0 and m%a!=0: #vua khit
r = (n*m) // (a*a)
elif n*m > a*a :
r = ceil(n/a)*ceil(m/a)
elif n*m <= a*a : # be hon
r = 1
print(r)
|
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | 3 | n = int(input())
a = []
b = []
k = 0
for i in range(n):
s = input()
a.append(int(s.split(' ')[0]))
b.append(int(s.split(' ')[-1]))
for i in range(n):
for j in range(n):
if i != j:
if a[i] == b[j]:
k += 1
print(str(k)) |
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
1. Go 1 unit towards the positive direction, denoted as '+'
2. Go 1 unit towards the negative direction, ... | 1 |
# target Expert
# Author : raj1307 - Raj Singh
# Date : 21.07.19
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): re... |
In this problem you will be given an integer array A of size N, your task is find whether given array is sorted or not (in ascending order) , if print "YES" else print "NO".
Array a[n] is sorted if a[0] ≤ a[1] ≤ ... a[n - 1].
Input
First line of input contains contains integer T denoting number of test cases.
For... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n=int(raw_input())
for u in range(n):
k=raw_input()
l=map(int,raw_input().split())
a=l[:]
a.sort()
if(a==l):
print("YES")
else:
print("NO") |
Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
* At time 1, the first spectator stands.
* At time 2, the second spectator stands.
* ...
* At time k, the k-th spectator stands.
* At time k + 1, the (k + 1)-th specta... | 3 | n,k,t = [int(i) for i in input().split()]
if t < k:
print(t)
elif t > n:
print(k-t+n)
else:
print(k) |
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 | m=int(input())
if(m>0 and m<101):
if(m%2==0):
if(m==2):
print("NO")
else:
print("YES")
else:
print("NO")
else:
print("invalid input")
|
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.
It turned out that among Pasha's friends there are exactly n boys and exactly n... | 3 | def pasha_and_tea(n,w,l):
s=sorted(l)
if s[n]>=s[0]*2:
girl=s[0]
boy=s[0]*2
else:
girl=s[n]/2
boy=s[n]
if (girl+boy)*n<=w:
print((girl+boy)*n)
else:
print(w)
n,w=list(map(int, input().split()))
l=list(map(int, input().split()))
pasha_and_tea(n,w,l)
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and... | 3 |
n = int(input())
t =list(map(int,input().split()))
u = [0]*(max(t)+1)
for j in t:
u[j]+=1
f = [ 0 ]*(len(u))
f[0]=0
f[1]=u[1]
for k in range(2, len(f)):
f[k]= max( f[k-2]+u[k]*k,f[k-1] )
print(f[-1])
|
In Byteland it is always the military officer's main worry to order his soldiers on parade correctly. Luckily, ordering soldiers is not really such a problem. If a platoon consists of n men, all of them have different rank (from 1 - lowest to n - highest) and on parade they should be lined up from left to right in incr... | 1 | for tc in range(input()):
num = int(raw_input())
arr = map(int, raw_input().split())
rank = range(1, num+1)
for i in range(num-1, -1, -1):
rank.insert(i, rank.pop(i-arr[i]))
print ' '.join(map(str, rank)) |
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 | if __name__ == "__main__":
n, d = [int(s) for s in raw_input().split()]
songs = [int(s) for s in raw_input().split()]
jokes = (len(songs) - 1) * 2
time = jokes * 5
time += reduce(lambda x, y: x + y, songs)
if time > d:
print -1
elif time == d:
print jokes
else:
pr... |
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is ... | 1 | a = int(input(''))
b = int(input(''))
c = int(input(''))
d = int(input(''))
e = int(input(''))
list_i = [a,b,c,d,e]
min_n = list_i[0] % 10
v = 0
count = 0
for i in range(len(list_i)):
if list_i[i] % 10 < min_n and list_i[i] % 10 != 0:
count = i
for i in range(len(list_i)):
if i == count or list_i[i] % 10 == 0... |
AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number.
Constraints
* 1 ≤ a,b ≤ 100
* a and b are integers.
Input
Input is given from Standard Input in the following format:
a b
Output
If the concatenation of a and b in this o... | 3 | c = int(input().replace(" ",""))
print("Yes" if c== int(c**0.5)**2 else "No") |
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... | 3 | str1 = input()
str2 = input()
n = len(str1)
ans = ""
for i in range(n):
temp1 = int(str1[i])
temp2 = int(str2[i])
if temp1!=temp2:
print(1,end="")
else:
print(0,end="")
|
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.
There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai ratin... | 1 | from collections import defaultdict
def distribution(user_count, thresholds):
counts = defaultdict(list)
result = [0] * len(thresholds)
for index, threshold in enumerate(thresholds):
counts[threshold].append(index)
previous_value = float('-inf')
for threshold in sorted(counts.keys()):
... |
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 | s=str(input())
a=len(s)
b=t=0
while(b<a):
if(s[b]=='7' or s[b]=='4'):
t=t+1
b=b+1
x=int(s)
if(t==a or x%4==0 or x%7==0 or x%47==0 or x%74==0):
print("YES")
else:
print("NO") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.