problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:
* x occurs in sequence a.
* Consider all positions of numbers x in the sequence a (such i, that ai = x). These... | 3 | n = int(input())
a = list(map(int, input().split()))
count = [[] for _ in range(max(a)+1)]
for i, v in enumerate(a):
count[v].append(i)
res = []
for i, i_v in enumerate(count):
l = len(i_v)
if l == 0:
continue
if l == 1:
res.append([i, 0])
elif l == 2:
res.append([i, i_v[1]-i... |
Write a program which prints multiplication tables in the following format:
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Input
No input.
Output
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Example
Input
Output | 3 | for a in range(1, 10):
for b in range(1, 10):
print("{0}x{1}={2}".format(a, b, a*b)) |
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size n× n and he wants to traverse his grid f... | 3 | import sys
# sys.stdin = open("E:\\programming\\New folder\\input.txt", "r")
# sys.stdout = open("E:\\programming\\New folder\\output.txt", "w")
ans = 0
def fun(p, key1, key2):
k = 0
global ans
ans = 0
for i in range(1, -1, -1):
if int(st[k][i]) != key1:
ans += 1
p.ap... |
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
... | 3 | import bisect
import os
import sys
from io import BytesIO, IOBase
Cards = [0]*31623
for i in range (1,len(Cards)):
Cards[i] = i*(i+1) + i*(i-1)//2
def main():
T = int(input())
for _ in range (T):
ans = 0
n = int(input())
while True:
pos = bisect.bisect_right(Card... |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 3 | t=int(input())
while(t>0):
n1=int(input())
s=input()
n=[]
f=0
for i in s:
n.append(i)
for i in range(len(n)):
if n[i]=='8' and n1-i>=11:
f=1
break
if f==1 and n1>=11:
print("YES")
else:
print("NO")
t-=1 |
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 | import math
for _ in range (int(input())):
n=int(input())
a=list(map(int, input().split()))
a.sort(reverse=True)
b=[a[0]]
a.remove(a[0])
g=b[0]
i=0
while i<n-1:
res=0
val=0
for j in range(len(a)):
x=math.gcd(g,a[j])
if x>=res:
... |
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 1 | from collections import Counter
n=input()
l=map(int,raw_input().split())
l=Counter(l).most_common(n)
print l[0][1] |
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire strin... | 3 | n, x, y = map(int, input().split())
a = input()
a = a.strip('1')
n = len(a)
c = 0
i = 0
while i < n:
try:
i1 = a.index('1', i)
if x < y:
try:
i = a.index('0', i1)
except:
i = n
c += x
else:
i = a.index('0', i1)
... |
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
input = sys.stdin.readline
t = int(input())
res = [True for _ in range(t)]
for i in range(t):
_ = int(input())
a = [int(j) for j in input().split()]
a.sort()
for j in range(1, len(a)):
if a[j] > a[j - 1] + 1:
res[i] = False
break
print('\n'.join('YES' if i els... |
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())
c = 0
a = list(map(int, input().split()))
for i in range(n-1):
b = list(map(int, input().split()))
a.extend(b)
for i in range(0, 2*n, 2):
for j in range(1,2*n,2):
if a[i] == a[j]:
c = c + 1
print(c)
|
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.
Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k ≥ 2 and 2k non-empty strings s_1, t_1, s_... | 3 | ALPHA = 26
def unique(cnt, l, r):
sum = 0
for a,b in zip(cnt[l-1],cnt[r]):
sum += a < b
return sum
s = tuple(map(lambda c: ord(c)-ord('a'),tuple(input())))
cnt = [[0 for j in range(ALPHA)]]
for i in range(len(s)):
cnt.append(list(cnt[i]))
cnt[i+1][s[i]] += 1
n = int(input())
for i in rang... |
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started t... | 1 | n = int(raw_input())
result = 0
col_counts = [ 0 for i in range(n) ]
for r in range(n):
row = raw_input().strip()
for c, ch in enumerate(row):
if ch == 'C':
col_counts[c] += 1
x = row.count('C')
result += x * (x - 1) // 2
for x in col_counts:
result += x * (x - 1) // 2
print(result)
|
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co... | 3 | n = int(input())
visitedschools = []
c = 0
i = 1
visitedschools += [i]
j = 1
while len(visitedschools) < n:
k = n + j - i
j = 2 if j == 1 else 1
visitedschools += [k]
c += (k +i) % (n+1)
print(c) |
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ... | 3 | n,m =map(int,input().split())
h={}
for i in range(n):
a=input()
name,ip=a.split()
h[ip]=name
#print(h)
for i in range(m):
a=input()
name,ip=a.split()
s=ip.replace(';','')
s1='#'+h[s]
print(a,s1)
|
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.
Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.
Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.
You are given str... | 3 | for g in range(int(input())):
s = input()
slov = [0] * 10
data = [0] * 10
for i in range(len(s)):
data[int(s[i])] += 1
ans = max(data)
for i in range(10):
slov[i] = 1
for i in range(len(s)):
if slov[int(s[i])] == 1:
slov[int(s[i])] = 0
data = [... |
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he... | 1 | NAME = "P2"
try:
inFile = open(NAME+".txt")
except:
pass
def read():
try:
return inFile.readline().strip()
except:
return raw_input().strip()
def reduce(num,minn=99999999,maxn=99999999,first9=0):
if minn <= int(num) <= maxn:
return num
'''i = len(num)-1
while i... |
The flag of Berland is such rectangular field n × m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
... | 3 | #Функция exit() модуля sys - выход из Python. Она реализуется путем вызова исключения SystemExit, поэтому выполняются действия по очистке, указанные в предложениях finally операторов try и можно перехватить попытку выхода на внешнем уровне.
n, m = map(int, input().split())
flag = [list() for x in range(n)]
h1 = True
fo... |
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.
In the contest, N foods numbered 1 through N will be presented, and the difficulty of ... | 3 | N,K=map(int,input().split())
A=sorted(map(int,input().split()))
F=sorted(map(int,input().split()))[::-1]
left,right=-1,10**12
while left + 1 < right:
mid = (left + right)//2
if sum([max(0,a-mid//f) for a,f in zip(A,F)])>K:
left = mid
else:
right = mid
print(right) |
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | 3 | a=int(input())
def find_gcd(x, y):
while(y):
x, y = y, x % y
return x
for i in range(0,a):
b=int(input())
arr=list(map(int,input().split()))
fgcd=min(arr)
brr=arr[:]
brr.sort()
ans=[]
k=0
for i in range(0,len(arr)):
if((not arr[i]==brr[i]) and not arr[i]%fg... |
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | 3 | n, t = map(int, input().split())
num = -1
i = 10 ** (n - 1)
border = 10 ** n
while i < border and i % t != 0:
i += 1
if i != border:
num = i
print(num)
|
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 | t = int(input())
for i in range(t):
n = int(input())
a = [int(i) for i in input().split()]
a.sort()
print(*a[::-1]) |
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 3 | def new_year_transportation(m, s, b):
p = 1
while p < t:
p += b[p - 1]
if p == t:
return "YES"
else:
return "NO"
# --------------------------------------------------------------
if __name__ == '__main__':
f = lambda: map(int, input().split())
n,t = f()
a = list(f())
... |
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())
counter = 0
for i in range(0,n):
team = input()
count_1s = team.count('1')
if(count_1s > 1):
counter += 1
print(counter)
|
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want... | 1 | print [[[min(zip(*r)[0]),max(zip(*r)[1])] not in r and -1 or r.index([min(zip(*r)[0]),max(zip(*r)[1])])+1 for r in [[[int(c) for c in raw_input().split()] for i in xrange(n)]]][0] for n in [int(raw_input())]][0] |
Chandan is an extremely biased person, and he dislikes people who fail to solve all the problems in the interview he takes for hiring people. There are n people on a day who came to be interviewed by Chandan.
Chandan rates every candidate from 0 to 10. He has to output the total ratings of all the people who came in ... | 1 | t=int(raw_input())
s= []
for i in range(t):
n = int(input())
if n == 0:
s.pop()
else:
s.append(n)
print sum(s) |
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 | x=int(input())
sumx=0
sumy=0
sumz=0
for i in range(x):
a=list(map(int,input().split()))
sumx = sumx+ a[0]
sumz = sumz + a[2]
sumy = sumy + a[1]
#print(sumx,sumy,sumz)
if sumx==sumy==sumz==0:
print("YES")
else:
print("NO") |
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats... | 1 | # -*- coding: utf-8 -*-
import sys
tests_count = int(sys.stdin.readline().strip())
for _ in xrange(tests_count):
r, g, b = map(int, sys.stdin.readline().strip().split())
arr = [r, g, b]
arr.sort()
greatest = arr[2]
middle = arr[1]
lowest = arr[0]
result = 0
delta = greatest - middle... |
Monk A loves to complete all his tasks just before the deadlines for introducing unwanted thrill in his life. But, there is another Monk D who hates this habit of Monk A and thinks it's risky.
To test Monk A, Monk D provided him tasks for N days in the form of an array Array, where the elements of the array represen... | 1 | noOfTestCases = int(raw_input())
def order(list1):
# value : {index1: no1, index2: no2}
countHash = {}
for index, no in enumerate(list1):
no = int(no)
countOf1 = bin(no).count('1', 0, len(bin(no)))
if(countHash.has_key(countOf1)):
countHash[countOf1][index] = no
else:
countHash[countOf1] = {}
coun... |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | 1 | def solve(n, arr_a, arr_b):
target_a = arr_a[0]
target_b = arr_b[0]
for i in xrange(1, n):
target_a = min(target_a, arr_a[i])
target_b = min(target_b, arr_b[i])
moves = 0
for i in xrange(0, n):
diff_a = arr_a[i] - target_a
diff_b = arr_b[i] - target_b
move... |
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 | s = input().split("WUB")
r = list()
for i in s:
if i!="": r.append(i)
print(" ".join(r)) |
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The... | 1 | s1=raw_input().strip()
s2=raw_input().strip()
def putInDict(s):
d1={}
for c in s:
if c in d1:
d1[c]+=1
else:
d1[c]=1
return d1
d1=putInDict(s1)
d2=putInDict(s2)
good=0
ok=0
for key in d1:
if key in d2:
v1=d1[key]
v2=d2[key]
v=min(v1,v2)... |
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 | s=int(input())
while s>0:
x=input()
a=len(x)
if a<=10:
print(x)
else:
print(x[0]+str(a-2)+x[a-1])
s-=1 |
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend t... | 3 | n,k=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
l.sort(key=lambda x: x[0])
ans,maxx=0,0
ans=0
i,j=0,0
while i<n:
while j<n and l[j][0]-l[i][0]<k:
ans+=l[j][1]
j+=1
maxx=max(ans,maxx)
ans-=l[i][1]
i+=1
print(maxx)
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 3 | T = lambda:list(map(int,input().split()))
n,t = T()
lista = T()
p = 1
i = 0
for _ in range(n-1):
if p==t:
break
elif p<n:
p+=lista[p-1]
if p > n:
p = p-n
break
print(["NO","YES"][p==t]) |
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.
A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character... | 3 | import sys
import math as mt
#input=sys.stdin.buffer.readline
import bisect
t=int(input())
#tot=0
for __ in range(t):
#n=int(input())
s=input()
o=-1
t=-1
th=-1
n=len(s)
ans=n+1
for i in range(len(s)):
if s[i]=='1':
o=i
elif s[i]=='2':
t=i
... |
Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".
Constraints
* 0 ≤ a, b, c ≤ 100
Input
Three integers a, b and c separated by a single space are given in a line.
Output
Print "Yes" or "No" in a line.
Examples
Input
1 3 8
Output
Yes
Input
3 8 1
Output... | 1 | a, b, c = map(int, raw_input().split())
if a < b < c:
print("Yes")
else:
print("No") |
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | 3 | def list_output(s):
print(' '.join(map(str, s)))
def list_input():
return list(map(int, input().split()))
n = int(input())
a = list_input()
res = 0
for i in range(1, n-1):
if (a[i-1] < a[i] and a[i] > a[i+1]) or (a[i-1] > a[i] and a[i] < a[i+1]):
res += 1
print(res) |
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number... | 1 |
def solve():
n, m, d = map(int, raw_input().split())
a = []
for i in range(n):
a += map(int, raw_input().split())
a.sort()
total = n * m
median = a[total / 2]
ans = abs(a[0] - median) / d
for i in range(1, total):
if a[i - 1] % d != a[i] % d:
return -1
... |
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | s=input()
i=0
while i<len(s):
if s[i]=='.':
print('0',end='')
i+=1
elif s[i]=='-' and s[i+1]=='.':
print('1',end='')
i+=2
elif s[i]=='-' and s[i+1]=='-':
print('2',end='')
i+=2
|
Snuke has N integers. Among them, the smallest is A, and the largest is B. We are interested in the sum of those N integers. How many different possible sums there are?
Constraints
* 1 ≤ N,A,B ≤ 10^9
* A and B are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print th... | 3 | n,a,b=map(int,input().split())
m=b+(n-1)*a
M=a+(n-1)*b
print(max(M-m+1,0))
|
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | 3 | for i in range(int(input())):
s=input()
lst=list()
s1=list()
for i in range(len(s)):
s1.append(s[i])
for i in range(len(s)-2):
if s1[i]=='o':
if s1[i+1]=='n' and s1[i+2]=='e':
lst.append(i+2)
if s1[i]=='t':
if s1[i+1]=='w' and s1[i+2]==... |
Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | 3 | R,G,B,N=map(int,input().split())
ans=0
for r in range(N+1):
for g in range(N+1):
if r*R+g*G>N:
break
if (N-r*R-g*G)%B==0:
ans+=1
print(ans) |
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 | p=int(input())+1
m=0
for i in range(1,p,1):
x=0
a,b,c=input().split()
a=int(a)
b=int(b)
c=int(c)
if a == 1:
x = x + 1
if b == 1:
x = x + 1
if c == 1:
x += 1
if x == 2 or x == 3:
m += 1
print(m) |
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip ... | 3 |
__author__ = 'Juan Barros'
'''
http://codeforces.com/problemset/problem/1006/B
'''
def solve(n, k, a):
sum = 0
maximunsIndex = [-1]
maximuns = []
while sum != k:
maximum = max(a)
maximunsIndex.append(maximum)
maximuns.append(a[maximum])
a[maximum] = -1
sum += 1
... |
There are N cities and M roads. The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally. There may be more than one road that connects the same pair of two cities. For each city, how many roads are connected to the city?
Constraints
* 2≤N,M≤50
* 1≤a_i,b_i≤N
* a_i ≠ b_i
* All input values a... | 3 | n,m=map(int,input().split())
ab=[0]*n
for i in range(m):
a,b=map(int,input().split())
ab[a-1]+=1
ab[b-1]+=1
for i in ab:
print(i) |
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself.
<image>
Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight.
Now, she is going to pick three gems.
Xenia loves colorful things, ... | 3 | def find(arr,flag,num):
if flag:
low=0
high=len(arr)-1
while low<high:
mid=(low+high)//2
if arr[mid]<num:
low=mid+1
else:
high=mid-1
if arr[low]<num:
if low!=len(arr)-1:
return arr[low+1]
else:
return 10**20
else:
return arr[low]
else:
low=0
high=len(arr)-1
while low<... |
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 ≤ i - a_i) or to the position i + a_i (if i + a_i ≤ n).
For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the ... | 3 | import sys
input = sys.stdin.readline
n=int(input())
A=list(map(int,input().split()))
E=[[] for i in range(n+1)]
from collections import deque
ODD=deque()
EVEN=deque()
for i in range(n):
if i+1+A[i]<n+1:
E[i+1+A[i]].append(i+1)
if i+1-A[i]>=0:
E[i+1-A[i]].append(i+1)
if A[i]%2==1:
... |
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 | t = int(input())
for i in range(t):
n = int(input())
skills = list(map(int , input().split()))
skills.sort()
value = abs(skills[n] - skills[n-1])
#print(class1,class2)
print(value) |
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ... | 3 | import sys
# sys.setrecursionlimit(10**6)
from itertools import product
def all_repeat(str1, rno):
chars = list(str1)
results = []
for c in product(chars, repeat = rno):
results.append(c)
return results
input=sys.stdin.readline
t=int(input())
for t1 in range(t):
n=int(input())
l=list(map(int,inpu... |
The grandest stage of all, Wrestlemania XXX recently happened. And with it, happened one of the biggest heartbreaks for the WWE fans around the world. The Undertaker's undefeated streak was finally over.
Now as an Undertaker fan, you're disappointed, disheartened and shattered to pieces. And Little Jhool doesn't wan... | 1 | def peace(n) :
if int(n)%21==0:
return "The streak is broken!"
if '21' in n :
return "The streak is broken!"
else :
return "The streak lives still in our heart!"
t = input()
while t != 0:
t -= 1
print peace(raw_input()) |
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | t=int(input())
for _ in range(t):
s=input()
n=len(s)
if s[n-2:n]=="po":
print("FILIPINO")
elif s[n-4:n]=="desu" or s[n-4:n]=="masu":
print("JAPANESE")
else:
print("KOREAN")
|
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes.
Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.
2 coverings are different if some 2 triangles are covered by the same diamond shape in ... | 3 | #!/bin/env python3
import sys
N = int(sys.stdin.readline())
for _ in range(N):
print(sys.stdin.readline()) |
You are given an integer sequence x of length N. Determine if there exists an integer sequence a that satisfies all of the following conditions, and if it exists, construct an instance of a.
* a is N^2 in length, containing N copies of each of the integers 1, 2, ..., N.
* For each 1 ≤ i ≤ N, the i-th occurrence of the... | 3 | def solve(n, xxx):
n2 = n ** 2
yyy = sorted((x - 1, k) for k, x in enumerate(xxx, start=1))
i = 0
ans = [-1] * n2
for x, k in yyy:
j = k - 1
while j:
while ans[i] != -1:
i += 1
ans[i] = k
i += 1
j -= 1
if i > x:... |
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.
On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ... | 3 | n=int(input())
while n>0:
a,b,c,d=map(int,input().split())
if a>b:
s=b
e=a
else:
s=a
e=b
x1=c-d
x2=c+d
if(x1<s and x2<=s):
r=e-s
elif(x1>=s and x2<=e):
r=(e-s)-(x2-x1)
elif(x1<s and x2>e):
r=0
elif(x1<s and x2>s and x2<=e):
r=(e-s)-(x2-s)
elif(x1>=s and x1<e and x2>e):
r=(e-s)-(e-x1)
elif... |
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c... | 3 | for _ in range(int(input())):
a,b =[int(x) for x in input().split()]
if(a%b==0):
print(0)
else:
div=a//b
print(b*(div+1)-a) |
Write a program which identifies the number of combinations of three integers which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9
Note... | 3 | import sys
while True:
n,x=map(int,input().split())
if n==0 and x==0: sys.exit()
ans=0
for i in range(n):
i+=1
for j in range(n-i):
j+=i+1
for k in range(n-j):
k+=j+1
if i+j+k == x: ans+=1
print(ans)
|
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).
He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will... | 3 | t = int(input())
for f in range(t):
x1,y1,x2,y2 = map(int, input().split())
a = abs(x1 -x2)
b = abs(y1 - y2)
c = min(a,b)
d = max(a,b)
if a== 0 or b==0:
print(max(a,b))
else:
print(c+d+2)
|
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many ... | 3 | t = int(input())
for l in range(t):
n = int(input())
s = list(input())
k = list(input())
i = 0
swap = 0
ans = list()
flag2 = False
while (i < n) and (swap <= 2*n) and (not flag2):
if s[i] == k[i]:
i += 1
else:
flag = True
for j in range... |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | x=input()
h=list(x)
ucount=0
lcount=0
h=[ord(j) for j in h]
if(h[0]>96 and h[0]<123):
h[0]=h[0]-32
h=[chr(j) for j in h]
x=''.join(h)
print(x) |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | l = list(input())
p = []
for i in range(0,len(l),2):
p.append(l[i])
p = list(sorted(map(int,p)))
s = str(p[0])
for i in range(1,len(p)):
s += '+'+str(p[i])
print(s)
|
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input... | 1 | import sys
range = xrange
input = raw_input
N,A,B = [int(x) for x in input().split()]
k = 0
while N-A*k>= 0 and (N-A*k)%B != 0:
k+=1
if N-A*k<0:
print -1
sys.exit()
q = (N-A*k)//B
ind = 0
U = []
for _ in range(k):
for i in range(ind+1,ind+A):
U.append(i)
U.append(ind)
ind+=A
for... |
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.
Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.
Every time Polycarp wakes up, he decides if he wants to sleep... | 3 | for _ in range(int(input())):
a,b,c,d = map(int, input().split())
if a <= b:print(b);continue
if c <= d:print(-1);continue
m = a - b
tmp = 0--m//(c-d)
print(b + tmp * c) |
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that:
* Alice will get a (a > 0) candies;
* Betty will get b (b > 0) candies;
* each sister will get some integer number of candies;
* Alice will get a greater amount of candie... | 3 | n = int(input())
for j in range(n):
k = int(input())
if k == 1 or k == 2:
print(0)
elif k % 2 == 0:
print(k//2 - 1)
else:
print(k//2) |
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long... | 3 | a=input()
b="1"
for i in range(len(a[1:])):
b+="0"
if len(a)==1:
print(1)
else:
print(int(b)-int(a[1:])) |
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | 3 | def ab():
a=int(input())
b=0
while(a!=0):
if(a%2==0):
a=a//2
else:
a=a-1
b=b+1
print(b)
ab() |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k,n,w = [int(x) for x in input().split()]
print(max(k*int(w*(w+1)/2)-n,0)) |
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 | n = input()
t = input()
if n[::-1] == t:
print("YES")
else:
print("NO")
|
Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.
To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities nu... | 3 |
n , m , k = map(int,input().split())
l = []
for i in range(m):
l.append(list(map(int,input().split())))
if k == 0 :
print('-1')
exit()
else:
s = list(map(int,input().split()))
x = [0] * (n + 1)
for i in s :
x[i] = 1
ans = []
for i in l :
if x[i[0]] + x[i[1]] == 1 :
... |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
The decreasing coefficient of permutation p1, p2, ...,... | 3 | import math
from collections import defaultdict, Counter, deque
INF = float('inf')
def gcd(a, b):
while b:
a, b = b, a%b
return a
def isPrime(n):
if (n <= 1):
return False
i = 2
while i ** 2 <= n:
if n % i == 0:
return False
i += 1
return True
def primeFactor(n):
if n % 2 == 0:
return 2
i = 3
... |
We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times.
On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the r... | 1 | def gns():
x=raw_input().split(" ")
return list(map(int,x))
t=int(input())
for _ in range(t):
n,m=gns()
ns=gns()
ms1=gns()
ms1s=set(ms1)
md={}
for i in range(n):
if ns[i] in ms1s:
md[ns[i]]=i
w=set(ns)-set(md.keys())
mdd=998244353
ans=1
for mi in ms1:
... |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | cisla = [[1, 11, 111, 1111], [2, 22, 222, 2222], [3, 33, 333, 3333], [4, 44, 444, 4444], [5, 55, 555, 5555], [6, 66, 666, 6666], [7, 77, 777, 7777], [8, 88, 888, 8888], [9, 99, 999, 9999]]
n = 0
f = int(input())
while n < f:
suma = 0
cislo = int(input())
for i in range(len(cisla)):
if cislo in ... |
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i... | 1 | n,k=map(int,raw_input().split())
w=raw_input()
l=[0]*26
for i in w:
l[ord(i)-65]+=1
ans=0
chk=k
while 1:#while 1:,while True ha mugen roop
ma=max(l)
if chk>=ma:
chk-=ma
ans+=ma**2
l[l.index(ma)]=0
elif chk<ma:
ans+=chk**2
chk=0
if chk==0:
break
print a... |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | def f(s):
if len(s) <= 2:
return s
else:
if s[0] == s[1]:
return s[0] + f(s[2:])
else:
return s
for i in range(int(input())):
s = input()
print(s[0]+f(s[1:]))
#print(f(input()))
|
To stay woke and attentive during classes, Karen needs some coffee!
<image>
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows n ... | 3 | recipes, admisionNums, questions = list(map(int, input().split()))
recipeList = []
questionList = []
partialSum = [0]*(200002)
preSum = [0]*(200002)
partialSum2 = [0]*(200002)
preSum2 = [0]*(200002)
counter = 0
for i in range(recipes):
recipeList.append(list(map(int, input().split())))
for i in range(questions):
... |
This contest, AtCoder Beginner Contest, is abbreviated as ABC.
When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.
What is the abbreviation for the N-th round of ABC? Write a program to output the answer.
Constraints
* 100 ≤ N ≤ 999
I... | 3 | import math
N=input()
print('ABC'+N) |
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive comm... | 1 | def gcd(a,b):
return a if b == 0 else gcd(b, a % b)
n = int(raw_input())
bs = 0
for i in range(n+1):
a = i
b = n-i
if a < b and gcd(a,b) == 1 and a > bs:
bs = a
print bs,(n-bs) |
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ... | 3 | from sys import*
import math
k = int(input())
str1="codeforces"
if (k==1):
print(str1)
else:
i=2
found= False
while (not found):
j=1
while(j<11 and not found):
if(int(math.pow(i,j)*int(math.pow(i-1,10-j)))<k):
j=j+1
else:
found= True
if (not found):
i=i+1
result=""
for k in range (j):
for... |
Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)
Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?
(We as... | 3 | N=int(input())
A=N//500
N%=500
B=N//5
print(A*1000+B*5) |
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 case in range(t):
n = int(input())
n2 = n
cnt2 = 0
cnt3 = 0
while (n2 % 2 == 0):
n2 //= 2
cnt2 += 1
while (n2 % 3 == 0):
n2 //= 3
cnt3 += 1
# print(cnt2, cnt3)
if n2 != 1 or cnt2 > cnt3:
print(-1)
else:
ans = abs(cn... |
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | 3 | m,k = [int(a) for a in input().split()]
msgs = list(map(int, input().split()))
ls = min(m,k)
#stack = [0 for i in len(ls)]
stack = []
for i in range(m):
if msgs[i] not in stack:
if len(stack) == ls:
stack.pop(0)
stack.append(msgs[i])
print(len(stack))
print(*stack[-1::-1]) |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ... | 3 | import math
tc = int(input())
for _ in range(tc):
s = int(input())
ss=s
money_spend = 0
if s<10:
print(s)
else:
while s>10: #10
rem = s%10 #0
spend = s-rem # spend = 10
cashbacks = math.floor(spend/10) #cash = 1
money_spend += s... |
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 | for _ in range(int(input())):
n = int(input())
if n==1:
print(0)
continue
if n%6!=0 and n%3!=0:
print(-1)
continue
count = 0
flag = 0
while(n!=1):
if n%6==0:
n = n//6
elif n%3==0:
n = n*2
else:
flag = 1... |
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.
Initially t... | 1 | n, v = int(raw_input()), 0
for i in map(int, raw_input().split()):
v ^= i - 1
print 1 if v & 1 else 2 |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | t=int(input())
while t!=0:
t-=1
ans=0
a,b=map(int,input().split())
if a!=b:
x=abs(b-a)
ans=x//10
if x%10!=0 and 10*ans<x:
ans+=1
print(ans)
|
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | from collections import defaultdict
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
if arr.count(arr[0])==n:
print('NO')
else:
print('YES')
dic=defaultdict(lambda:[])
for i in range(n):
dic[arr[i]].append(i+1)
m=n
... |
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of... | 1 | for _ in range(int(input())):
s1 = raw_input()
t = raw_input()
p = raw_input()
if len(s1) > len(t): print 'NO'
elif len(s1) == len(t): print 'YES' if s1==t else 'NO'
else:
found,pos = True,0
for a in s1:
try:
pso1 = t.index(a,pos)
pos =... |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 | def rindex(list, num):
return len(list) - list[-1::-1].index(num) -1
n = int(input())
a = [int(num) for num in input().split()]
x, p = max(a), min(a)
if a.index(x) < rindex(a, p) :
print(a.index(x)+n-(rindex(a, p)+1))
else :
print(a.index(x) + n - (rindex(a, p) + 1)-1)
|
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.
Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po... | 3 | W, H, N = map(int,input().split())
l = 0
r = W
u = H
d = 0
for i in range(N):
x, y, a = map(int,input().split())
if a == 1:
l = max(x,l)
elif a == 2:
r = min(x,r)
elif a == 3:
d = max(y,d)
else:
u = min(y,u)
print(max((r-l),0)*max((u-d),0))
|
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 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 23:01:36 2019
@author: bhavi
"""
w=eval(input())
if w%2==0 and w!=2:
print("YES")
else:
print("NO") |
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t... | 3 | n=int(input())
a=[int(i) for i in input().split()]
count=0
k=sum(a)
for i in range(1,6):
k_1=k+i
j=k_1%(n+1)
if (j!=1):
count=count+1
#print(count)
print(count)
|
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | N = int(input())
database = {}
for i in range(N):
name = str(input())
try:
database[name] += 1
print('{}{}'.format(name, database[name]))
except:
database[name] = 0
print('OK') |
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:
(※) After each turn, (the number of times the player has played Paper)≦(the number of times the ... | 3 | s = list(input())
count = 0
for i in s:
if i == 'g':
count += 1
else:
count -= 1
print(count//2) |
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ... | 1 | rd = lambda : map(int, raw_input().split())
n = input()
a = rd()
ans = [0, 0]
i, j, k = 0, n - 1, 0
while i <= j:
if a[i] < a[j]:
ans[k & 1] += a[j]
j -= 1
else:
ans[k & 1] += a[i]
i += 1
k += 1
print ans[0], ans[1] |
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy).
You have time to use some emotes only m times. You are allowed t... | 3 | n, m, k = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
print(m//(k+1) * (a[-1] * k + a[-2]) + (m%(k+1)) * a[-1]) |
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())
while t:
a,b,x,y,n = [int(i) for i in input().split()]
temp1 = a
temp2 = b
temp3 = n
diff1 = b-y
b -= min(diff1,n)
n -= min(diff1,n)
a -= min(a-x,n)
ans1 = a*b
diff1 = temp1-x
temp1 -= min(diff1,temp3)
temp3 -= min(diff1,temp3)
temp2 -... |
You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | 3 | import sys
from collections import Counter
sys.setrecursionlimit(10**7)
n=int(input())
x=set()
for i in input().split():
x.add(int(i))
m=len(x)
if m==1:
ans=0
elif m==2:
aa=abs(x.pop()-x.pop())
if aa%2==1:
ans=aa
else:
ans=aa//2
elif m==3:
s,t,u=x.pop(),x.pop(),x.pop()
... |
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.
A result of the elimination stage is the tota... | 3 | t=int(input())
while t:
t-=1
lst=list(map(int,input().split()))
y=max(lst[0]+lst[1],lst[2]+lst[3])
print(y)
|
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 ≤ k ≤ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri... | 3 | #!/usr/local/bin/python3
import sys
get = lambda:map(int,input().split())
def main():
Num_Students, Max_Students = get()
arr = dict(zip(get(),range(1,Num_Students+1)))
if len(arr) >= Max_Students:
print("YES")
print(*list(arr.values())[:Max_Students])
else:
print("NO") ... |
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"... | 1 | p = raw_input()
if (not "H" in p) & (not "Q" in p) & (not "9" in p):
print "NO"
else:
print "YES" |
A bracket sequence is a string containing only characters "(" and ")".
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are reg... | 3 | # -*- coding: utf-8 -*-
"""
@Project : 牛客网
@File : Bracket Sequences Concatenation Problem.py
@Time : 2018/6/10 19:00
@Author : Koushiro
http://codeforces.com/contest/990/problem/C.
"""
if __name__ == "__main__":
n = int(input())
seq = []
regular = 0
left = {}
right = {}
for i in range(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.