problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | tc=int(input())
for _ in range (tc):
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
b=sorted(b, reverse=True)
a=sorted(a)
for i in range(k):
if(b[i]>a[i]):
a[i]=b[i]
print(sum(a))
|
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 |
n = int(input())
s = str(input())
if '1' in s:
print('HARD')
else:
print('EASY')
|
You are given four integers n, c_0, c_1 and h and a binary string s of length n.
A binary string is a string consisting of characters 0 and 1.
You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change.
After some changes (possibly zero) ... | 3 | t = int(input())
for i in range(t):
n, c0, c1, h = list(map(int, input().split()))
s = input()
count = 0
count_0 = s.count('0')
count_1 = s.count('1')
if c0*count_0 > count_0*(c1+h):
count += count_0*(c1+h)
if c0*count_0 <= count_0*(c1+h):
count += c0*count_0
if c1*count_1 > count_1*(c0+h):
count += count... |
problem
In the area where Kazakhstan is now located, there used to be a trade route called the "Silk Road".
There are N + 1 cities on the Silk Road, numbered from west as city 0, city 1, ..., city N. The distance between city i -1 and city i (1 ≤ i ≤ N) is Di.
JOI, a trader, decided to start from city 0, go through ... | 3 | INF = 10 ** 20
n, m = map(int, input().split())
dist = []
weth = []
for _ in range(n):
dist.append(int(input()))
for _ in range(m):
weth.append(int(input()))
dp = [INF] * (n + 1)
dp[0] = 0
for i in range(m):
for j in range(n, 0, -1):
dp[j] = min(dp[j], dp[j - 1] + dist[j - 1] * weth[i])
print(dp[n])
|
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | import sys
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input().strip()
def listStr():
return list(input().strip())
import collections as col
import m... |
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ... | 3 | import sys
input = sys.stdin.buffer.readline
n,m=map(lambda x:int(x), input().split())
A = []
for _ in range(n):
scores = list(map(lambda x:int(x), input().split()))
A.append(scores)
def solve(n,m,A):
# O(31*( 5*n + 4**5 ))
# all index from 0
ans = ()
nstats = 2**m
def judge(finalScore):
... |
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 | m=int(input( ))
sum=0
count=0
for i in range(m):
a,b,c=map(int,input().split())
sum=a+b+c
if sum>=2:
count=count+1
print(count) |
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows t... | 3 | N=100
a=(5,N,N,2,N,N,8,N,0,1)*6
R=lambda x=' ':map(int,input().split(x))
t,=R()
while t:
t-=1;h,m=R();x,y=R(':');y+=x*m;u=v=w=q=N
while h<=w+q*10or v*10+u>=m:r=f'{y//m%h:02}:{y%m:02}';y+=1;u,v,_,w,q=(a[ord(x)]for x in r)
print(r) |
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | for _ in range(int(input())):
input()
print(' '.join(map(str, sorted(map(int, input().split()))[::-1])))
|
Ilya lives in a beautiful city of Chordalsk.
There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.
The ho... | 3 | t = int(input())
arr = list(map(int,input().split(' ')))
first = len(arr)-1
last = 0
while arr[first]==arr[0]:
first-=1
while arr[last]==arr[len(arr)-1]:
last+=1
last = len(arr)-1 - last
print(max(first,last))
|
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 | n = input()
m = ""
m += n[0]+n[2]+n[4]+n[3]+n[1]
m = int(m)
m = m**5
m = str(m)
print(m[len(m)-5:len(m)]) |
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | 3 | t = int(input())
as1 = as2 = 0
while True:
if (t == 0):
break;
t -= 1
a, b, x, y, n = map(int, input().split())
as1 = as2 = 0
if (n >= a - x):
as1 = x * (b - min(b-y, n-a+x))
else:
as1 = (a-n) * b
if (n >= b-y):
as2 = y * (a - min(a-x, n-b+y))
else:
as2 = (b-n) * a
print(min(as1, as2))
|
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 | from collections import deque
if __name__ == '__main__':
n, m = [int(num) for num in raw_input().split()]
d = deque((i, int(num)) for i, num in enumerate(raw_input().split(), start=1))
while len(d) > 1:
idx, child = d.popleft()
child -= m
if child <= 0:
continue
... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n=int(input())
A=[]
for i in range(n):
A.append(list(map(int,input().split())))
a=sum([x[0] for x in A])
b=sum([x[1] for x in A])
c=sum([x[2] for x in A])
if a==0 and b==0 and c==0:
print('YES')
else:
print('NO') |
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100).
The first line of... | 3 | for _ in " "*int(input()):
a=int(input())
if a==1:
z=int(input())
if z==1:print("1 2")
else:print(-1)
continue
b=list(map(int,input().split()))
if 1 not in b or 2*a in b:print(-1);continue
c=[ i for i in range(1,(2*a)+1) if i not in b]
r=[]
for i in range(a):
... |
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.
The main school of the capital is located in (s_x, ... | 3 | import sys
from collections import deque
ints = deque(int(x) for x in sys.stdin.read().split())
def main():
n, x0, y0 = (ints.popleft() for i in range(3))
xy = [(ints.popleft(), ints.popleft()) for i in range(n)]
locs = [(0,1), (0,-1), (1,0), (-1,0)]
between = lambda x0,x,dx: (x>x0 and dx>=0) or (x<x0 and dx<=... |
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner.
Output the probability th... | 1 | z=raw_input()
z=z.split()
a=float(z[0])
b=float(z[1])
c=float(z[2])
d=float(z[3])
q=a/b;
s=c/d;
if (q==1):
print 1
elif (s==1):
print q;
else:
r=(1-q)*(1-s);
print (q)/(1-r)
#print a,b,c,d,q,r
|
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 | def lowerChar(x):
if (ord(x)>=ord("A")) and (ord(x)<=ord("Z")):
return chr(ord(x)-ord("A")+ord("a"))
else:
return x
def lowerString(x):
s=""
for i in range (0,len(x)):
s=s+lowerChar(x[i])
return s
iString = input()
iString = lowerString(iString)
s=""
for i in range... |
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n)... | 3 | s=input()
q=int(input())
c=[0]*(len(s))
for i in range(len(s)-1):
if s[i]==s[i+1]:
c[i+1]=c[i]+1
else:
c[i+1]=c[i]
#print(c)
for i in range(q):
l,r=map(int,input().split())
print(c[r-1]-c[l-1]) |
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | n=int(input())
t=list(map(int,input().split()))
t1=t.count(1)
t2=t.count(2)
t3=t.count(3)
#ul=[it for it in t if it not in ul]
ans=min(t1,t2,t3)
if ans == 0:
print(0)
exit()
print(ans)
while(ans!=0):
teaml=[]
for i in range(1,4):
index=t.index(i)
teaml.append(index+1)
t[index] = 0
print(*teaml,sep=" ")
ans-... |
We have a grid with H rows and W columns. At first, all cells were painted white.
Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.
Compute the following:
* For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the gr... | 3 | H,W,N=map(int,input().split())
direc=[[0,0],[-1,0],[-2,0],[0,-1],[-1,-1],[-2,-1],[0,-2],[-1,-2],[-2,-2]]
dic={}
for i in range(N):
h,w=map(int,input().split())
for d in direc:
if 1<=h+d[0]<=(H-2) and 1<=w+d[1]<=(W-2):
l=(h+d[0],w+d[1])
if l in dic:
dic[l]=dic[l]+1
else:
dic[l]=... |
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | 3 | import re
from collections import deque
T = int(input())
for test in range(T):
a = input()
basket = deque(re.findall('A+|B+', a))
i = 0
while i < len(basket) - 1: # A 덩어리가 마지막에 있으면 안된다.
if basket[i][0] != 'A':
i += 1
continue
temp = len(basket[i]) - len(baske... |
Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.
The camera's memory is d megabytes. Valera's camera can take photos of high and l... | 1 | import sys
import math
import re
file = sys.stdin
#file = open("test", "r")
n, d = map(int, file.readline().rstrip().split())
a, b = map(int, file.readline().rstrip().split())
p = []
for i in range(1, n + 1):
c, e = map(int, file.readline().rstrip().split())
p.append((i, a*c + b*e))
p.sort(cmp=lambda a, b : cm... |
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | t = int(input())
for i in range(t):
a = int(input())
if a == 1:
print(0)
else:
ost2 = 0
ost3 = 0
while a % 2 == 0:
a //= 2
ost2 += 1
while a % 3 == 0:
a //= 3
ost3 += 1
if ost3 < ost2 or a != 1:
print... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | t=int(input())
c=0
for i in range(t):
p,q=map(int,input().split(" "))
if(q-p>=2):
c=c+1
print(c) |
You have a fraction <image>. You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.
Input
The first contains three single positive integers a, b, c (1 ≤ a < b ≤ 105, 0 ≤ c ≤ 9).
Output
Print position of the first occurrence of digit c into the fraction. Positions... | 1 | a, b, c = map(int, raw_input().split())
counter = 0
ans = -1
n = len(str(a))+1
rests = set()
while True:
counter += 1
a = a * 10
d = a / b
if d == c:
ans = counter
break
a = a - d * b
if counter > n:
if a not in rests:
rests.add(a)
else:
br... |
<image>
This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks.
We can simulate the movement (comings an... | 3 | def get_input():
while True:
try:
yield ''.join(input())
except EOFError:
break
N = list(get_input())
stack = []
for l in range(len(N)):
a = int(N[l])
if a == 0:
print(stack.pop())
#print("POP")
else:
#print(a)
stack.append(a)
|
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | 3 | n=int(input())
M=0
Ch=0
Fr=0
for i in range(1,n+1):
m_n,c_n=map(int,input().split())
if m_n>c_n:
M+=1
elif m_n<c_n:
Ch+=1
elif m_n==c_n:
Fr+=1
if M>Ch:
print('Mishka')
elif Ch>M:
print("Chris")
else:
print('Friendship is magic!^^')
|
For a string S consisting of the uppercase English letters `P` and `D`, let the doctoral and postdoctoral quotient of S be the total number of occurrences of `D` and `PD` in S as contiguous substrings. For example, if S = `PPDDP`, it contains two occurrences of `D` and one occurrence of `PD` as contiguous substrings, s... | 1 | s=raw_input()
t=[]
for x in s:
if x=='?':
t.append('D')
else:
t.append(x)
print "".join(t) |
You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.
Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:
* Operation: Choose one of the strings A, B and C, and specify an integer i betwe... | 1 | import sys
from collections import deque
import copy
import math
def get_read_func(fileobject):
if fileobject == None :
return raw_input
else:
return fileobject.readline
def main():
if len(sys.argv) > 1:
f = open(sys.argv[1])
else:
f = None
read_func = get_read_func(... |
"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 | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
l=[]
f,s = map(int,input().split())
count=0
p=0
if 0 <= f <= 50:
if 0 <= s <= 50:
l= list(map(int, input ().split()))
com=l[s-1]
for i in l:
if i == 0:
... |
“All Hail The King.”
Middle aged, and overqualified highschool chemistry teacher Walter White has been diagnosed with lung cancer. To make sure his family is financially secure, he teams up with a former student Jesse Pinkman and turns to a life of crime to make and distribute the purest crystal meth on the streets.
... | 1 | t = int(raw_input())
for i in range(t):
N = int(raw_input())
a = map(int, raw_input().split())
a.sort()
sum = 0
for i in xrange(0, N, 2):
if i <= N - 2:
sum += a[i] * a[i + 1]
print sum |
12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.
There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.
If child i is given a candies, the child's happine... | 3 | mod=10**9+7
table=[[0 for i in range(401)] for j in range(401)]
for i in range(401):
S=0
for j in range(1,401):
S+=pow(j,i,mod)
S%=mod
table[i][j]=S
N,C=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
dp=[[0 for i in range(C+1)] for j in ran... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 1 | from sys import stdin
a = stdin.readline().strip()
b = stdin.readline().strip()
c = list(a)
d = list(b)
d.reverse()
if c==d:
print "YES"
else:
print "NO" |
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems.
Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o... | 3 | from itertools import accumulate
def divisors(n):
tab = []
for i in range(2, int(n**.5) + 2):
if n % i == 0:
while n % i == 0:
n //= i
tab.append(i)
if n > 1:
tab.append(n)
return tab
n = int(input())
a = list(map(int, input().split()))
s = sum(a)
tab = divisors(s)
if s == 1:
print(-1)
else:
m... |
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated i... | 3 | n, m = map(int, input().split())
b = n // 2
target = n % m
current = b % m
if target <= current:
shift = current - target
else:
shift = m + current - target
if shift > b:
print (-1)
else:
b = b - shift
a = n - 2 * b
print(a + b) |
You have n stacks of blocks. The i-th stack contains h_i blocks and it's height is the number of blocks in it. In one move you can take a block from the i-th stack (if there is at least one block) and put it to the i + 1-th stack. Can you make the sequence of heights strictly increasing?
Note that the number of stacks... | 3 | for cvx in range(int(input())):
h = int(input())
num = 0
all = 0
ind = True
str = input().split()
for i in range(h):
if num <= int(str[i]):
all += int(str[i]) - num
else:
if all >= num - int(str[i]):
all -= (num - int(str[i]))
e... |
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems.
Polycarp has a list of n contests, th... | 3 | n = int(input())
problems = sorted([int(x) for x in input().split(' ')])
start = 0
i = 0
while True:
if i >= n:
break
if problems[i] < start:
break
if problems[i] >= start + 1:
start += 1
i += 1
print(start)
|
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | import math
for i in range(int(input())):
n = int(input())
goods = [int(elem) for elem in input().split()]
price = math.ceil(sum(goods) / n)
print(price) |
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.
Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the... | 3 | n = input()
s = map(int,input().split())
s = map(abs,s)
print(sum(s))
|
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 | l,R = map(int,input().split())
j = -1
for i in range(l,R+1):
if len(str(i))==len(set(str(i))):
j=i
break
print(j)
|
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p... | 3 | import sys
def findPossibleSquare(matrix):
row1 = 0
row2= 1
column1 = 0
column2 =1
square = []
dot = 0
while True:
square.append(str(matrix[row1][column1]))
square.append(str(matrix[row1][column2]))
square.append(str(matrix[row2][column1]))
square.append(str(... |
At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.
The nameplate is to be rectangular an... | 3 | string=input()
s=len(string)
for a in range(1,6):
if(s/a<=20):
b=abs(-s//a)
st=a*b-s
break
i=0
print(a,b)
for m in range(a):
print(str(string[i:i+b-bool(st)])+bool(st)*'*')
i+=b-bool(st)
st-=bool(st) |
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple ta... | 3 | from sys import stdin
n, m = [int(i) for i in stdin.readline().split(' ')]
trim = lambda s: s[:-1] if (s[-1] == "\n") else s
s = trim(stdin.readline())
t = trim(stdin.readline())
minNumber = n
minPlaces = [str(i) for i in range(1, n+1)]
for i in range(0, m-n+1):
curNumber = 0
curPlaces = []
for j in range(... |
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.
... | 3 | def isInteresting(n):
s = str(n)
totalsum = 0
for i in s:
totalsum+=int(i)
return totalsum
a = int(input())
totalsum = isInteresting(a)
if(totalsum%4==0):
print(a)
else:
x = totalsum%4
# print(x,totalsum)
x = 4 - x
# print(x,a+x,isInteresting(a+x))
if(isInteresting(a+x)%4 ==0):
print(x+a)
else:
flag = ... |
You are given a permutation p_1, p_2, ..., p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence.
Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m.
The ... | 1 | from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin, floor
from itertools import *
from fractions import Fraction
import string
import copy
import random
import bisect
from decimal import *
from collections import deque
def id_generator(size=20, chars=string.digits)... |
Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.
Each spell consists of several lines. The line, whose first non-space chara... | 1 | ##-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: fukuhara
#
# Created: 26/03/2012
# Copyright: (c) fukuhara 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
import... |
A and B are preparing themselves for programming contests.
An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi... | 1 | n,m = map(int,raw_input().split())
print max( k + min((m-k)/2,n-2*k) for k in range(min(n/2,m)+1))
|
Alice and Bob have decided to play the game "Rock, Paper, Scissors".
The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 14:55:19 2020
@author: Dark Soul
"""
n=int(input(''))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
mxsol=min(a[0],b[1])+min(a[1],b[2])+min(a[2],b[0])
mnsol=max(0,a[0]-b[0]-b[2],a[1]-b[1]-b[0],a[2]-b[2]-b[1])
print(mnsol,mxsol)
|
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | n=int(input())
m=0
if n>=100:
m+=n//100
n=n%100
if n>=20:
m+=n//20
n=n%20
if n>=10:
m+=n//10
n=n%10
if n>=5:
m+=n//5
n=n%5
if n>=1:
m+=n//1
n=n%1
print(m)
|
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?
The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which i... | 1 | from math import pi as pi
def contain(ci,cj):
x,y,r = ci
x2,y2,r2 = cj
#print x,y,r
return (x-x2)**2 + (y-y2)**2 < (r+r2)**2
n = input()
c = sorted([[int(_) for _ in raw_input().split()] for _ in range(n)],reverse = True, key = lambda x:x[2])
rank = [1]
for i in range(1,n):
for j in range(i-1,-... |
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ... | 3 | z=list(map(int,input().split()))
n=int(input())
s=z[0]
m=z[1]
l=z[2]
xl=z[3]
xxl=z[4]
for i in range(n) :
z=input()
if z=="XL" :
if xl>0 :
xl-=1
print("XL")
elif xxl>0 :
xxl-=1
print("XXL")
elif l>0 :
l-=1
print("L"... |
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | 3 | t = int(input())
for i in range(t):
a, b, x, y, n = map(int, input().split())
d = max(0, n - a + x)
ans = max(x, a - n) * max(y, b - d)
d = max(0, n - b + y)
ans = min(ans, max(y, b - n) * max(x, a - d))
print(ans) |
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | 3 | # https://codeforces.com/problemset/problem/1352/C
import sys
# sys.stdin = open(r"./file/input.txt", 'r')
# sys.stdout = open(r"./file/output.txt", 'w')
t = int(input())
for _ in range(t):
n = int(input())
arr = input().split(" ")
arr = list(map(int, arr))
# print(arr)
step = 0
l = 0
r... |
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n.
Help the jury distrib... | 3 | def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
INF = 10**20
I =... |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n = int(input())
total = sum(list(map(int, input().split())))
if total != 0:
print("HARD")
else:
print("EASY") |
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 | a=int(input())
print(["YES","NO"][all(a%i for i in[4,7,47,744,477])]) |
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... | 3 | a = int(input())
b = list(map(int, input().split()))
m = c = d = e = f = 0
for i in range(a):
if b[i] == 1:
c += 1
elif b[i] == 2:
d += 1
elif b[i] == 3:
e += 1
else:
f += 1
m += f
m += e
c -= e
m += d // 2
d -= (d // 2) * 2
if d == 1:
m += 1
if c > 0:
c -... |
For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operatio... | 3 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self... |
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.
An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.
Constraints
* 1 ≤ n ≤ 100000
* 0 ≤ ai ≤ 109
Input
n
a0
a1
:
... | 3 | import sys
from bisect import bisect_left
read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7
def main():
N = int(readline())
A = list(int(readline()) for _ in range(N))
LIS = [INF]*(N+1)
for a in A:
i = bisect_left(LI... |
Vasya has a string s of length n. He decides to make the following modification to the string:
1. Pick an integer k, (1 ≤ k ≤ n).
2. For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through:
* qwe... | 3 | import sys
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
N = int(input())
S = input().strip()
ans = []
for k in range(1, N + 1):
tmp = S[::]
if k == 1:
pass
elif (N + k) % 2 == 1:
... |
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(*sorted(a))
print(*sorted(b))
|
M-kun is a student in Aoki High School, where a year is divided into N terms.
There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:
* For the first through (K-1)-th terms: not given.
* For each of the K-th through N-th terms: the multipl... | 3 | n, k = map(int, input().split())
l = list(map(int, input().split()))
for i in range(1, n - k + 1):
print("Yes" if l[i - 1] < l[i + k - 1] else "No") |
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands o... | 3 | def compress(ops):
cops = []
for r, dir in ops:
while cops and cops[-1][0] <= r:
cops.pop()
if not cops or cops[-1][1] != dir:
cops.append((r, dir))
return cops
def transform(lst, ops):
mr, mdir = ops[0]
sections = [range(mr, len(lst))]
ost = 0
oen... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | s = input()
t = input()
w = ""
for i in range(len(s)):
w += s[-i-1]
if w == t:
print("YES")
else:
print("NO") |
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc... | 3 | s = input()
l = len(s)
fault = 0
for i in range (l):
if s[i] != s[l - 1 - i]:
fault += 1
if (fault == 0 and l % 2 == 1) or fault == 2:
print("YES")
else:
print("NO") |
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | 3 | from sys import stdin
input=stdin.buffer.readline
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
a.sort()
k1=0
k2=0
m1=1
for i in range(n):
m1=max(m1,a[i])
k1=k1+1
if(k1>=m1):
k2=k2+1
k1=k1-m1
print(k2) |
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | 3 | x, y = map(int, input().split())
if (x == y or (x == 2 and y == 4) or (x == 4 and y== 2)):
print("=")
exit(0)
if x > 2 and y > 2:
if x > y:
print("<")
else:
print(">")
exit(0)
if x == 1:
print("<")
exit(0)
if y == 1:
print(">")
exit(0)
if x == 2:
... |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | # encoding: utf-8
"""
"""
from math import sqrt
from queue import Queue
import sys
sys.setrecursionlimit(10**6)
if __name__ == '__main__':
# sys.stdin = open('1.txt', 'r')
nokfase = int(input())
for kase in range(nokfase):
n = int(input())
t = 4
while True:
if n % (t -... |
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | for _ in range(int(input())):
n=int(input())
l=[];st='';ans=0
for j in range(n):
s=str(input())
st+=s
cv=set(st)
for i in range(len(st)):
l.append(st[i])
for i in cv:
if l.count(i)%n==0:
ans+=1
if len(cv)==ans:
print("YES")
else:
... |
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≤ a ≤ b ≤ n). For e... | 3 | # Looked up the tutorial
length,keys_my = map(int,input().split())
my_String = input()
key_val = input().split()
k_map = {}
for k in key_val:
k_map.update({k:0})
n = 0; final = 0
for s in my_String:
if s in k_map.keys():
# find the longest consecutive substring
n += 1
else:
# Combina... |
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:
* Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
* Each time Applema... | 3 | n=int(input())
data=list(map(int,input().split()))
data.sort()
ans=0
for (i,x) in enumerate(data,2):
ans+= x*i
ans-=data[-1]
print(ans)
|
A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.
m buyers ... | 1 | # -*- coding: utf-8 -*-
def readline(): return map(int, raw_input().split())
def readint(): return int(raw_input(), 10)
def main():
n = readint()
p = readline()
a = readline()
b = readline()
m = readint()
c = readline()
colors = [ list() for __ in xrange(3) ]
for (i, customer) in enum... |
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.
You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each... | 1 | t = int(raw_input())
def check(a, b, c, n, k):
# print a, b, c
val = min(a, b, c)
if val < 0:
a += -val
b += -val
c += -val
# print a, b, c
s = a + b + c
if k < s:
return False
if (k-s) % 3 != 0:
return False
games = n - k
if (games+s) % 3 == 0:... |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | 3 | n = int(input())
data = [n]
for i in range(n - 1, 0, -1):
data.append(1 + (i - 1) * (n - i + 1))
print(sum(data)) |
We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.
For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:
* Let S be the set of the vertices numbered L through R. f(L, R) represents the number ... | 3 | n=int(input())
ans=0
for i in range(1,n+1): #頂点数の総和を求める
ans+=i*(n-i+1)
for _ in range(n-1): #各辺についてu*(n-v+1)を頂点数の総和から引く
u,v=map(int,input().split())
if u>v: #上記ではu<vを仮定しているのでu>vのときuとvを入れ替える
u,v=v,u
ans-=u*(n-v+1)
print(ans) |
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square.
A square of size n × n is called prime if ... | 3 | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode... |
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, ... | 3 | def calc(N, s):
counter = {}
for l in s:
counter[l] = counter.get(l, 0) + 1
s = ""
for key in counter:
if counter[key] % N != 0:
return -1
m = counter[key] // N
m = m if m > 0 else 1
s += key*m
return s*N
# get inputs
#a = list(map(int, inp... |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | n, k = [int(x) for x in input().split()]
even = n // 2
if n % 2 == 0:
odd = n // 2
else:
odd = n // 2 + 1
if k <= odd:
ans = 2 * k - 1
else:
k -= odd
ans = 2 * k
print(ans) |
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-... | 1 | # resubmission - i still don't see the prob highlighted green on my contest
import sys
it = iter(sys.stdin.read().splitlines())
nListed = list((int(x) for x in next(it)))
nOfDigits = len(nListed)
# print nListed # prueba
count = 0
count2 = 0
for i in xrange(nOfDigits):
slc = nListed[::1]
if(count > 0)... |
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}.
There are 2n students, the i-th student has... | 3 | for _ in range(int(input())):
n = int(input())
a = list(sorted(map(int, input().split())))
print(a[n] - a[n - 1])
|
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the... | 3 | def main():
n = int(input())
ratings = [int(_) for _ in input().split()]
copied_ratings = ratings[::]
copied_ratings.sort(reverse=True)
positions = [1 for _ in range(n)]
same_position_count = 0
for i in range(1, n):
if copied_ratings[i] == copied_ratings[i - 1]:
positio... |
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of a... | 3 | n=int(input())
l=list(map(int,input().split()))
neg=[]
z=[]
pos=[]
for i in l:
if(i>0):
pos.append(i)
elif(i==0):
z.append(i)
else:
neg.append(i)
if(len(pos)==0):
pos.append(neg[0])
pos.append(neg[1])
neg.remove(neg[0])
neg.remove(neg[0])
if(len(neg)%2==0):
z.appe... |
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 | def fun():
p=0
for _ in range(int(input())):
(a,b,c)=map(int,input().split())
if a+b+c>=2:
p=p+1
return p
p=fun()
print(p) |
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
<image>
You should count, how many there are pai... | 1 | n,m = [int(x) for x in raw_input().split()]
count = 0
for i in range(1000):
for j in range(1000):
if (i*i + j) == n and (i + j*j) == m:
count += 1
print count |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | def f1(a,b,c):
return(a+(b*c))
def f2(a,b,c):
return(a*(b+c))
def f3(a,b,c):
return(a*(b*c))
def f4(a,b,c):
return((a+b)*c)
def f5(a,b,c):
return((a+b)+c)
a = int(input())
b = int(input())
c = int(input())
l = []
l.append(f1(a,b,c))
l.append(f2(a,b,c))... |
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number a, the second player wrote number b. How many ways ... | 3 | string_input = input()
a = int(string_input.split(' ')[0])
b = int(string_input.split(' ')[1])
l = [0,0,0]
for i in range(1,7):
if abs(i-a)>abs(i-b):
l[2]+=1
elif abs(i-a)<abs(i-b):
l[0]+=1
else:
l[1]+=1
print(" ".join([ str(k) for k in l]))
|
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.
Therefore, Sasha decided ... | 3 | n = int(input())
a = [int(x) for x in input().split()]
pref = [0]
for i in range(n):
pref.append(pref[-1] ^ a[i])
dp = [[0 for i in range(2**20 + 5)] for j in range(2)]
ans = 0
for i in range(len(pref)):
ans += dp[i % 2][pref[i]]
dp[i % 2][pref[i]] += 1
#print(ans, pref[i])
print(ans)
|
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program that... | 1 | # your code goes here
import sys
a = map(int,raw_input().split())
total = sum(a)
if total%5 == 0 and total>=5:
print total/5
else:
print -1 |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | # import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
def check(r,g,b,w):
return False if r%2 + g%2 + b%2 + w%2 > 1 else True
t = int(input())
for _ in range(t):
n = int(input())
nums = list(map(int, input().split()))
nums.sort()
last = 'x'
for i in range(n-1):
if nums[... |
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if:
1. gcd(a, b) = 1 or,
2. a divides b or b d... | 3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 20:10:33 2020
@author: Aditee
"""
t=int(input())
for i in range(0,t):
n= int(input())
a=[]
a.append((4*n)-2)
for j in range(1,n):
x= 4*n-((j+1)*2)
a.append(4*n-((j+1)*2))
for k in a:
print(k,en... |
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Eac... | 3 | from collections import Counter, defaultdict
n = int(input())
w = input()
keep = defaultdict(list)
o = ''
for i in range(n):
keep[w[i]].append(i + 1)
m = int(input())
for _ in range(m):
s = input()
c = Counter(s)
output = 0
for letter in c:
output = max(output, keep[letter][c[letter] - 1]... |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | t=int(input())
while t:
t=t-1
n=int(input())
a=list(input())
b=input()
rev=0
i=0
j=n-1
n=n-1
l=[]
while(n>=0):
if rev==0:
rev=1
if a[i]==b[n]:
l.append(1)
l.append(n+1)
i=i+1
n=n-1
elif re... |
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... | 3 | n, m = map(int, input().split())
used = [False] * (m + 1)
for i in range(n):
l, r = map(int, input().split())
for j in range(l, r + 1):
used[j] = True
ans = 0
A = [0] * (m + 1)
for i in range(1, m + 1):
if not(used[i]):
A[ans] = i
ans += 1
print(ans)
print(*A[:ans]) |
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the n... | 3 | n = int(input())
a={}
a['polycarp']=1
for i in range(n):
f,m,l = input().lower().split()
a[f] = a[l]+1
print(max(a.values()))
|
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has n lanterns and Big Ban... | 3 | #!/usr/bin/env python3
from sys import stdin, stdout
def rint():
return map(int, stdin.readline().split())
#lines = stdin.readlines()
n, m = rint()
a = []
b = []
a = list(rint())
b = list(rint())
Max = -10**1000
maxi = -1
for i in range(n):
for j in range(m):
if Max < a[i]*b[j]:
Max = a... |
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. ... | 3 | n, a, b, c, t = map(int,input().split())
sum = n * a
s = list(map(int,input().split()))
for i in range(n):
if b < c:
sum += (c - b) * (t - s[i])
print(sum)
|
You want to make change for $ n $ cents. Assuming that you have infinite supply of coins of 1, 5, 10 and / or 25 cents coins respectively, find the minimum number of coins you need.
Constraints
* $ 1 \ le n \ le 10 ^ 9 $
Input
$ n $
The integer $ n $ is given in a line.
output
Print the minimum number of coins... | 3 | n = int(input())
cnt = 0
cnt += n//25
n = n % 25
cnt += n//10
n = n % 10
cnt += n//5
n = n % 5
cnt+=n
print(cnt)
|
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 | a=list(map(int,input().split()))[:4]
x=max(a)
for i in range(len(a)):
if a[i]!=x:
print(x-a[i],end=" ")
|
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... | 1 | tc = int(raw_input())
for i in range(tc):
s=raw_input()
if len(s)>10:
s=s[0]+str(len(s)-2)+s[-1]
print s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.