problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are... | 3 | nStr = input()
n = int(nStr)
SeatLine = ['']*n
found = False
for i in range(n):
SeatLine[i] = input()
if SeatLine[i].find("OO") != -1 and not found :
SeatLine[i] = SeatLine[i].replace('OO','++',1)
found = True
if found:
print("YES")
for i in range(n):
print(SeatLine[i])
else:
print("NO") |
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=map(int,input().split())
if n%2==1:
n+=1
if k<=n/2:
print(2*k-1)
else:
print(2*(k-int(n/2))) |
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as s... | 3 | t = int(input())
for i in range(t):
n = int(input())
if n == 2:
print(2)
print(2, 1)
elif n == 3:
print(2)
print(3, 1)
print(2, 2)
else:
print(2)
x, y = n-2, n
print(x, y)
x, y = n-1, n-1
print(x, y)
x, y ... |
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`.
Constraints
* 2 β€ N β€ 200000
* 1 β€ A_i β€ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
If the elements... | 3 | input()
A = list(map(int, input().split()))
print("YES" if len(A)==len(set(A)) else "NO") |
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | 3 | h1 = list(map(str, input().split()))
h2 = list(map(str, input().split()))
m1 = int(h1[0][3:])
h1 = int(h1[0][:2])
m2 = int(h2[0][3:])
h2 = int(h2[0][:2])
x1 = ((h2 - h1) * 60 + (m2 - m1)) // 2
x2 = x1 // 60
x3 = x1 % 60
h1 = h1 + x2
m1 = m1 + x3
if m1 >= 60:
h1 += 1
if len(str(m1)) < 3:
if m1 % 60 == 0:... |
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible ... | 3 | import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
def get_list_string(): return list(map(str, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
def get_int(): return int(... |
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μλ
, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, β¦, s_{n} and m strings t_1, t_2, t_3, β¦, t_{m}. ... | 3 | n,m=map(int,input().split())
s=list(map(str,input().split()))
t=list(map(str,input().split()))
q=int(input())
for _ in range(q):
p=int(input())
print(s[(p%n)-1]+t[(p%m)-1])
|
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 β€ li β€ ri β€ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.
Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, ... | 3 | n, m, k = [int(n) for n in input().split()]
a = [int(n) for n in input().split()]
instructions = []
temp = []
for i in range(n+1):
temp.append(0)
for i in range(m):
instructions.append([int(n) for n in input().split()])
queries = []
for i in range(m+1):
queries.append(0)
for i in range(k):
x, y = [int(n) for n in i... |
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree β he can tell you only th... | 3 | (n, d, h) = [int(x) for x in input().split()]
if d > 2*h:
print(-1)
exit(0)
adj = [[] for i in range(n)]
pre = 0
cur = 1
for i in range(h):
adj[pre].append(cur)
pre = cur
cur += 1
pre = 0
for i in range(d - h):
adj[pre].append(cur)
pre = cur
cur += 1
if d == h:
if d < 2 and n > 2... |
2^N participants (P1 , P2 , P3 .... , P2^N ) have enrolled for a knockout chess tournament. In the first round, each participant P2k-1 is to play against participant P2k, (1 β€ k β€ 2^N-1) . Here is an example for k = 4 :
Some information about all the participants is known in the form of a triangular matrix A with dim... | 1 | import copy
n = int(raw_input())
table = [[None for i in range(pow(2,n))] for j in range(pow(2,n))]
for i in range(1,pow(2,n)):
temp = map(int,raw_input().split())
for j in range(len(temp)):
table[i][j] = temp[j]
# for _ in range(pow(2,n)-1):
# table.append(map(int,raw_input().split()))
game = [i for i in range... |
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | 3 | def hgstcmnfactr(l, m):
lst = set()
mst = set()
for i in range(1, l+1):
if l % i == 0:
lst.add(i)
for j in range(1, m+1):
if m % j == 0:
mst.add(j)
return max(lst & mst)
mn = max(list(map(int, input().split(" "))))
chns = 7-mn
print(str(int(chns/hgstcmnfactr... |
You're given an array a of length n. You can perform the following operations on it:
* choose an index i (1 β€ i β€ n), an integer x (0 β€ x β€ 10^6), and replace a_j with a_j+x for all (1 β€ j β€ i), which means add x to all the elements in the prefix ending at i.
* choose an index i (1 β€ i β€ n), an integer x (1 β€ x β€... | 3 | n = int(input())
a = list(map(int, input().split()))
print(n+1)
for i in range(n - 1, -1, -1):
x = i - a[i] % n + n
print(1, i + 1, x)
for j in range(i + 1):
a[j] += x
print(2, n, n)
for i in range(n):
a[i] %= n |
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 = map(int, input().split())
ans = k *((w * (w + 1)) // 2 )
if n > ans :
print(0)
else:
print(abs(n - ans)) |
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).
At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he... | 1 | ts = int(raw_input())
for cs in range(ts):
n, m, k = tuple(map(int, raw_input().split()))
pabe = min(n/k, m)
baki = m-pabe
boro = (baki+k-2)/(k-1)
print pabe-boro |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | MN = input().split()
M = int(MN[0])
N = int(MN[1])
answer = (N*M - (N*M)%2)//2
print(answer) |
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n... | 3 | # -*- coding: utf-8
n = int(input())
s = []
for num in range(n):
t = [i for i in input()]
s.append(t)
def criti(x) :
y = [ord(i) for i in x]
y.sort()
from collections import Counter
if len(x)-1 == sum([a-b for a, b in zip(y[1:], y[:-1])]) :
k = Counter(y)
if len([i for i in ... |
There are n piranhas with sizes a_1, a_2, β¦, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | 3 | import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import m... |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | t = int(input())
for _ in range(t):
n,m = map(int,input().split())
a =list(map(int,input().split()))
b = list(map(int,input().split()))
cnt = {}
flag = 0
for i in a:
cnt[i] = 0
for i in b:
cnt[i] = 0
for i in a:
cnt[i] = 1
for i in b:
if cnt[i] == 1:
... |
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
... | 3 | for _ in range(int(input())):
s=input()
n=len(s)
suf=[0]*(n+1)
s1=s.count("1")
mi=10000000000
mi2=10000000000
for i in range(1,n+1):
if s[i-1]=="1":
suf[i]+=suf[i-1]+1
else:
suf[i]=suf[i-1]
mi=min(mi,s1-suf[i]+i-suf[i])
mi2=min(mi2,suf[... |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly... | 3 | t = int(input())
while t:
t -= 1
n = int(input())
candies = list(map(int, (input().split())))
oranges = list(map(int, (input().split())))
min_c = min(candies)
min_o = min(oranges)
count = 0
for i in range(n):
if candies[i] - min_c > oranges[i] - min_o:
c... |
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | 3 |
from math import ceil
from math import radians
from heapq import heapify, heappush, heappop
import bisect
from math import pi
from collections import deque
from math import factorial
from math import log, ceil
from collections import defaultdict
from math import *
from sys import stdin, stdout
import itertools
import ... |
Bob is playing a game named "Walk on Matrix".
In this game, player is given an n Γ m matrix A=(a_{i,j}), i.e. the element in the i-th row in the j-th column is a_{i,j}. Initially, player is located at position (1,1) with score a_{1,1}.
To reach the goal, position (n,m), player can move right or down, i.e. move from ... | 1 | K = input()
def bob(A) :
n, m = len(A), len(A[0])
dp = [[0]*(m+1) for i in range(n+1)]
dp[0][1] = A[0][0]
for i in range(1,n+1) :
for j in range(1,m+1) :
dp[i][j] = max(dp[i-1][j]&A[i-1][j-1], dp[i][j-1]&A[i-1][j-1])
return dp[n][m]
m = pow(2,18)-1
t = pow(2,17)
A = [
[m, K, 0],
[t, K, 0... |
E869120's and square1001's 16-th birthday is coming soon.
Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.
E869120 and square1001 were just about to eat A and B of those pieces, respectively,
when they found a note attached to the cake saying that "the same person should not t... | 3 | n,m=map(int,input().split())
if n<9 and m <9:
print('Yay!')
else:
print(':(') |
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting o... | 3 | a=int(input())
b=list(map(int,input().split()))
b.sort(reverse=True)
c=0
d=0
if a%2!=0:
c=sum(b[:a-((a-1)//2)])
d=sum(b[a-((a-1)//2):])
print((c**2+d**2))
else:
c=sum(b[:a//2])
d=sum(b[a//2:])
print((c**2+d**2)) |
You have n coins, each of the same value of 1.
Distribute them into packets such that any amount x (1 β€ x β€ n) can be formed using some (possibly one or all) number of these packets.
Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve... | 3 | import math
n=int(input())
k=math.ceil(math.log2(n+1) - 1)
print(k+1)
|
You are given a number k and a string s of length n, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:
* The first character '*' in the original string should be replaced with 'x';
* The last character '*' in the... | 3 | import sys
import math
import bisect
from math import sqrt
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7
for _ i... |
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by η«ε± https://twitter.com/nekoy... | 3 | try:
s = input()
n = len(s)
a = [0]*n
for i in range(n):
if i>=1:
a[i] = a[i-1]
if s[i] == 'Q':
a[i]+=1
ans = 0
mx = a[n-1]
for i in range(n):
if s[i] == 'A':
ans += (a[i-1]* (mx-a[i-1]))
print(ans)
except:
pass |
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first.
On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first... | 3 | n = int(input())
arr = list(map(int, input().split()))
s = 0
for i in range(n):
s += arr[i]
h = int((s + 1) / 2)
ans = 0
s = 0
for i in range(n):
s += arr[i]
if s >= h:
ans = i
break
print(ans + 1) |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | for _ in range(int(input())):
n,a,b,c,d=map(int, input().split())
if (a-b)*n>(c+d) or (a+b)*n<(c-d):
print("NO")
else:
print("YES") |
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second a and then the next word at second b, then if b - a β€ c, just the new word is appended to other words on the screen. If b - a > c, then ever... | 3 | n,c=map(int,input().split())
l=list(map(int,input().split()))
x=1
for i in range(n-1):
if l[i+1]-l[i] > c:
x=1
else:
x+=1
print(x) |
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 | n = int (input ())
answer = 0
for n in range (n):
p, q = map (int, input ().split ())
if q - p >= 2:
answer += 1
print (answer)
|
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 | ''' ===============================
-- @uthor : Kaleab Asfaw
-- Handle : kaleabasfaw2010
-- Bio : High-School Student
==============================='''
# Fast IO
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file): s... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | in_list = input().split(" ")
n = int(in_list[0])
m = int(in_list[1])
a = int(in_list[2])
flagstones_n = int(n / a)
if n % a > 0:
flagstones_n += 1
flagstones_m = int(m / a)
if m % a > 0:
flagstones_m += 1
print(flagstones_n * flagstones_m) |
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 | a = "".join(reversed(input()))
b = input()
if a==b:
print("YES")
else:
print("NO") |
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever... | 3 | n, k = map(int, input().split())
sequence = list(map(int, input().split()))
for i in range(n):
if sequence[i] < 0 and k > 0:
sequence[i] *= -1
k -= 1
elif sequence[i] > 0:
break
if k != 0:
proxy = map(abs, sequence)
least = min(proxy)
least_index = 0
if least in sequenc... |
Bertown is a city with n buildings in a straight line.
The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise.
Bertown's best sapper knows how to activate... | 3 | t = int(input())
for j in range(0,t):
l1 = [int(x) for x in input().split()]
a = l1[0]
b = l1[1]
bomb = []
city = input()
for i in range(0,len(city)):
if city[i]=='1':
bomb.append(i)
out = 0
for i in range(0,len(bomb)-1):
out+=min(a,(bomb[i+1]-bomb[i]-1)*b)
... |
There are N children, numbered 1, 2, ..., N.
Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets.
For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy ... | 3 | n,x = map(int,input().split())
a = list(map(int,input().split()))
happy = 0
a.sort()
for i in range(n-1):
if x>=a[i]:
x -= a[i]
happy += 1
if x==a[n-1]:
happy += 1
print(happy)
|
Sayaka Saeki is a member of the student council, which has n other members (excluding Sayaka). The i-th member has a height of a_i millimeters.
It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wa... | 3 | from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key, lru_cache
import sys
input = sys.stdin.readline
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i... |
There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.
You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.
* Choose... | 3 | n = int(input())
a = [int(input()) for i in range(n)]
t = -1
s = 0
ans = 0
for i in range(n):
if a[i] == t+1:
t += 1
s = t
elif a[i] > t+1:
print(-1)
exit()
else:
ans += s
t = a[i]
s = t
ans += s
print(ans)
|
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two ot... | 3 | n=int(input())
s1,s2=0,0
l1,l2=[],[]
for i in range(n):
a,b,c=map(int,input().split())
if(a in l1 or b in l2):
a,b=b,a
s1+=c
else:
s2+=c
l1.append(a)
l2.append(b)
print(min(s1,s2)) |
We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.
According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is... | 3 | g=[[*map(int,input().split())]for _ in range(3)]
for h in [0,1]:
for w in [0,1]:
if g[h][w]+g[h+1][w+1]!=g[h+1][w]+g[h][w+1]:
exit(print('No'))
print('Yes') |
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 | cases = int(input())
for x in range(cases):
sub = input()
count = len(sub)-1
msg=""
while True:
msg+=sub[count]
if count == len(sub)-1:
count-=1
elif count == 0:
break
else:
count-=2
print(msg[::-1])
|
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | m,n=map(int,input().split())
k=m*n
f=k//2
print(f)
|
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 | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
q = b[0]
b[0] = b[1]
b[1] = b[2]
b[2] = q
Min = 0
Max = 0
for i in range(3):
Min += max(a[i] - b[(i + 1) % 3] - b[(i + 2) % 3], 0)
Max += min(a[i],b[i])
print(Min, Max)
|
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is ... | 3 | a = [int(input()) for _ in range(5)]
res = 10
for i in a:
if i%10: res = min(res, i%10)
ans = 0
for i in a:
ans += -(-i//10)*10
print(ans+res-10) |
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())
count = 0
for _ in range(N):
num = sum([int(i) for i in input().split()])
if num >= 2:
count += 1
print(count)
|
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | for u in range(int(input())):
a,b,c,d,k=map(int,input().split())
x=(a-1)//c+1
y=(b-1)//d+1
if(x+y<=k):
print(x,y)
else:
print(-1) |
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Va... | 3 | n,m = map(int,input().split())
ls=[]
x = []
no=[]
B=[]
for i in range(1,m+1):
B.append(i)
while(n):
n-=1
ls = list(map(int,input().split()))
x.append(ls[0])
for i in ls[1:]:
no.append(i)
no = set(no)
no=list(no)
if(no==B):
print('YES')
else:
print('NO')
|
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid.
You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to... | 3 | import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict
def solution(s):
counts = defaultdict(int)
for c in s:
counts[c] += 1
counts['L'] = min(counts['L'], counts['R'])
counts['R'] = min(counts['L'], counts['R'])
counts['U'] = min(counts['U'], counts['D']... |
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 | t=int(input())
for i in range(t):
a,b,c,r=map(int,input().split())
d=abs(a-b)
left,right=c-r,c+r
print(d-max(0,min(right,max(a,b))-max(left,min(a,b)))) |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | import math
#input
n=int(input())
#variables
def composite(x):
if x%2==0:
return True
elif x%3==0:
return True
else:
for i in range(5,math.floor(math.sqrt(x))+1):
if x%i==0:
return True
return False
#main
if n%2==0:
while True:
for i in range(n//2,1,-1):
if composite(i) and composite(n-i):... |
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | 3 | import math
def divisors(number):
l = []
for x in range(2, int(math.sqrt(number))):
if number % x == 0:
l.append(x)
l.append(number)
return l
read = input().split()
l = int(read[0])
r = int(read[1])
div_count = {'max': '2', 'max_count': 0}
if (len(range(l, r+1)) < 3):
for number... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n,k=input("").split()
s_k=int(k)-1
scores=[]
counter=0
data=0
new_scores=[]
scores=input("").split()
for i in range(int(n)):
if int(scores[i])==0:
data=data+1
elif int(scores[i])>=int(scores[s_k]):
counter=counter+1
print(counter)
|
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha... | 1 | s = list(raw_input())
r = {}
c = s[ : 10].count('-')
for i in range(len(s) - 9):
if c == 2 and s[i + 2] == s[i + 5] == '-':
d, m, y = map(int, [''.join(s[i : i + 2]), ''.join(s[i + 3 : i + 5]), ''.join(s[i + 6 : i + 10])])
if 2013 <= y <= 2015 and 1 <= m <= 12 and 1 <= d <= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31,... |
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1β€iβ€N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically.
<image>
A pyramid with N=4 steps
Snuke wrote a per... | 3 | n,x = (int(i) for i in input().split())
if x==1 or x==2*n-1: print("No")
else:
print("Yes")
for i in range((x+n-1)%(2*n-1),0,-1): print(i)
for i in range(2*n-1,(x+n-1)%(2*n-1),-1): print(i) |
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 | (n, k) = list(map(int, input().split()))
Massage = []
id_all = list(map(int, input().split()))
A = set()
for i in range(n):
id = id_all[i]
if id not in A:
Massage.append(id)
A.add(id)
if len(A) > k:
A.remove(Massage[-k-1])
if len(Massage) > k:
print(k)
print(*Massage... |
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation:
Choose one of these numbers and add or subtract 1 from it.
In particular, we can apply this operation to the same number several times.
We want to make the product of all these numbers equal to 1, in other wo... | 3 | n = int(input())
a = list(map(int,input().split()))
ans = 0
for i in range(n):
ans += abs(1 - a[i])
count = 0
for i in range(n):
if a[i] < 0 :
count += 1
if count%2 != 0 :
for i in range(n):
if a[i] == 0 :
ans -= 2
break
print(ans - (count//2)*4) |
You are given two positive integers n (1 β€ n β€ 10^9) and k (1 β€ k β€ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, β¦, a_k such that all a_i>0, n = a_1 + a_2 + β¦ + a_k and either all a_i are even or all a_i ar... | 3 | for i in range(int(input())):
n,k=[int(num)for num in input().split()]
if n%2==0 and k%2==0 and n>=k:
x=[1]*(k-1)
c=n-(sum(x))
x.append(c)
if x[-1]<=0:
print('NO')
x.clear()
else:
print('YES')
print(*x,sep=' ')
x... |
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.
Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.
Dima can buy boxes at a factory. The factory pr... | 3 | x=input().split()
n=int(x[0])
k=int(x[1])
x.clear()
x=input().split()
few=int(10**18)
ind = 0
a=0
for i in range(k):
# print(x[i])
p=n%int(x[i])
# print("p: ",p)
if not p:
ind = i + 1
a = int(n // int(x[i]))
break
elif p<few:
few=p
ind=i+1
a=int(n//i... |
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 | t = int(input())
for _ in range(t):
n = int(input())
for i in range(2, 30):
if n % ((1 << i) - 1) == 0:
print(n // ((1 << i) - 1))
break |
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A1440... | 3 | print('10'[input()[-1] in '02468ACE']) |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
line = [int(x) for x in input().split()]
cut = []
for i in range(1, n):
x = line[i] - line[i - 1]
cut.append(x)
d = 0
D = 0
for i in range(n - 1):
if cut[i] >= 0:
D += 1
else:
d = max(d, D)
D = 0
d = max(d, D)
print(d + 1) |
Luba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every <image> the condition ai β₯ ai - 1 is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a... | 3 | if __name__ == "__main__":
n, k, x = list(map(int, input().split()))
chore_times = list(map(int, input().split()))
for i in range(1, k + 1):
chore_times[-i] = x
print(sum(chore_times))
|
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | 3 | n = int(input())
l = list(map(int, input().split()))
if n == 1 and l[-1] == 15:
print("DOWN")
exit()
elif n == 1 and l[-1] == 0:
print("UP")
exit()
elif n == 1:
print(-1)
exit()
if l[-1] == 15:
print("DOWN")
exit()
if l[-1] == 0:
print("UP")
exit()
elif l[-1] == 1 and l[-2] ==... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n, k = input().split()
x = [int(x) for x in input().split()]
z = [z for z in x if z >= x[int(k)-1] and z != 0]
print(len(z))
|
This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters one of the two ... | 3 | n = int(input())
s = input()
ans = ""
lst0 = "a"
lst1 = "a"
for i in range(n):
if s[i] >= lst0:
ans += "0"
lst0 = s[i]
elif s[i] >= lst1:
ans += "1"
lst1 = s[i]
else:
print("NO")
exit()
print("YES")
print(ans) |
There are N dishes of cuisine placed in front of Takahashi and Aoki. For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.
When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.
Starting from Takahashi, they alternately choose one dish and ... | 3 | l = []
c = int(input())
for i in range(c):
a,b = map(int, input().split())
l.append([a,b,abs(a+b)])
l.sort(key=lambda x:x[2])
k = l[::-1]
s = 0
for i in range(c):
if i%2==0:
s +=k[i][0]
else:s-=k[i][1]
print(s) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 16:17:50 2019
@author: lfy
"""
"""beautiful year"""
y=int(input())
y0=y
y=y+1
while y>y0:
if len(list(set(list(str(y)))))==4:
print(y)
break
y=y+1 |
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n β₯ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he ne... | 1 | def is_prime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
n=int(raw_input())
if n%2==0:
if n==2:
print 1
else:
print 2
else:
if is_prime(n):
print 1
elif is_prime(n-2):
print 2
else:
print 3
|
Input
The input contains a single integer a (0 β€ a β€ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 3 | x = int(input())
bits = range(5, -1, -1)
i1, schastlivo, dolgo, zhili, i2, oni = bits
# title = [i1, zhili, oni, dolgo, i2, schastlivo]
title = [i1, oni, zhili, dolgo, i2, schastlivo]
print(sum(
1 << replacement
for bit, replacement in zip(bits, title)
if x & (1 << bit)
))
def apply(x, mask):
return s... |
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.
Anton can perform the following sequence of operations any number of ti... | 3 | import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
check = [False, False, False] # [0, 1, -1]
result = 'YES'
if a[0] != b[0]:
print('NO')
continue
if a[0] == 0 or ... |
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ... | 3 | n = int(input())
count = 0
for i in range(1,n):
if n % i == 0:
count+=1
print(count) |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 1 | raw_input()
x = map(int, raw_input().split(' '))
left = [0]
right = []
for i in xrange(len(x) -1):
left.append(abs(x[i] - x[i+ 1]))
right.append(abs(x[i] - x[i+ 1]))
right.append(0)
m = sum(left)
n = 0
for i in xrange(len(x)):
if i == 0 or i == len(x) - 1:
print max(left[i], right[i]),
else:
print min(left[i]... |
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | 3 | t=int(input())
for _ in range(t):
n=int(input())
k=0
a=1
num=0
while(num<n//2-1):
#k=a+a*2
a=a*2
k=k+a
num+=1
num=0
b=0
while(num<n//2):
#k=a+a*2
a=a*2
b=b+a
num+=1
k+=a*2
print(abs(k-b))
|
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways... | 1 | def modInverse(a,m):
'''solves for a*x = 1 (mod m)'''
return egcd(a,m)[1]%m
def egcd(a, b):
'''solves for a*x+b*y = gcd(a,b)'''
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
mod = 1000000007
pow2 = [1]
for i in ... |
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i... | 3 | n,m=map(int,input().split())
A=list(map(int,input().split()))
c=0
t=1
for i in range(m):
x=A[i]-t
x=x%n
c+=x
t+=x
print(c)
|
"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 | x,y=(int(c) for c in input().split())
ar=list(map(int,input().split()))
k=0
l=ar[y-1]
for i in ar:
if i>0 and i>=l:
k+=1
else:
break
print(k) |
You are given N items.
The value of the i-th item (1 \leq i \leq N) is v_i.
Your have to select at least A and at most B of these items.
Under this condition, find the maximum possible arithmetic mean of the values of selected items.
Additionally, find the number of ways to select items so that the mean of the values o... | 3 | from math import factorial as f
def comb(n, k):
return f(n)//f(k)//f(n-k)
n, a, b = map(int, input().split())
V = sorted(map(int, input().split()))
s = sum(V[-a:]) / a
print(s)
small = V[-a]
cnt = V[-a:].count(small)
total = V.count(small)
if V[-1] != small:
ans = comb(total, cnt)
else:
ans = 0
for i in range(... |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | a=input()
b=input()
c=input()
d=dict()
for i in range(0,len(a)):
if (d.get(a[i])==None):
d[a[i]]=1
else:
d[a[i]]=d[a[i]]+1
for i in range(0,len(b)):
if (d.get(b[i])==None):
d[b[i]]=1
else:
d[b[i]]=d[b[i]]+1
r=True
for i in range(0,len(c)):
if (d.get(c[i])==None):
... |
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 β₯ w_2. In this game, exactly one ship is used... | 3 | w1, h1, w2, h2 = map(int, input().split())
print((h1 + h2) * 2 + w1 + w2 + abs(w1 - w2) + 4)
|
Petya's friends made him a birthday present β a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.
To make everything right, Petya is going to move at most one bracket from i... | 3 | n = int(input())
s = input()
if s.count('(')!=s.count(')'):
print('No')
else:
x=0
for i in s:
if i=='(':
x+=1
else:
x-=1
if x<=-2:
print('No')
break
else:
print('Yes') |
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya... | 3 |
if __name__ == '__main__':
_, d = (int(x) for x in input().split())
curr_win_streak = 0
max_win_streak = 0
for _ in range(d):
if '0' in input():
curr_win_streak += 1
else:
curr_win_streak = 0
max_win_streak = max(max_win_streak, curr_win_streak)
prin... |
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose s... | 3 | import math
if __name__== '__main__':
testCases= int(input())
for _ in range(testCases):
for _ in range(9):
print(input().replace('1','2'))
|
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, β¦, d_k, such that 1 β€ d_i β€ 9 for all i and d_1 + d_2 + β¦ + d_k = n.
Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d... | 3 | n = int(input())
x = [9,8,7,6,5,4,3,2,1]
for i in x:
if n%i==0:
print(n//i)
print((str(i)+' ')*(n//i))
break |
"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 | su, cm = map(int, input().split())
li = list(map(int, input().split()))
temp = li[cm-1]
count = 0
for ans in li:
if ans >= temp and ans > 0:
count += 1
print(count)
|
Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.
Circle inside a rectangle
Cons... | 3 | W,H,x,y,r=map(int,input().split())
if W>=x+r and H>=y+r and 0<=x-r and 0<=y-r:
print("Yes")
else:
print("No")
|
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 β€ k β€ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) ]))
def invr():
return(map(int,input().split()))
n = inp()
for i in range(n):
l = inlt()
n = l[0]
r = l[1]
res = 0
x = min(n,r+1)
res = (x*(x-1)... |
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.
Heidi figured out that Madame Kovarian uses a... | 3 |
r = int(input())
x = 0
res = ""
loop = True
while loop:
x += 1
y = (r - (x**2) - x - 1) / (2*x)
#print("\n%d %d %d\n" % (r, x, y))
if y <= 0:
loop = False
res = "NO"
break
if y == int(y):
loop = False
res = "%d %d" % (x, y)
print(res)
|
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now sh... | 3 | # cook your dish here
from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right
def L():
return list(map(int, stdin.readline().split()))
def In():
return map(int, stdin.readli... |
n! = n Γ (n β 1) Γ (n β 2) Γ ... Γ 3 Γ 2 Γ 1
Is called the factorial of n. For example, the factorial of 12
12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600
And there are two consecutive 0s at the end.
Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of... | 3 | while True:
n=int(input())
if n==0:
break
v=1
for i in range (0,n):
v*=(n-i)
s=0
while True:
if v%10!=0:
break
else:
s+=1
v//=10
print(s)
|
There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region. The front and back sides of these cards can be distinguished, and initially every card faces up.
We will perform the following op... | 3 | N,M=map(int,input().split())
if(N*M==1):
print(1)
elif(N>1 and M>1):
print((N-2)*(M-2))
else:
print(N*M-2)
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | s=input()
sl=sf=''
s=s.lower()
l=['a','e','i','o','u','y']
for x in s:
if x not in l:
sl+=x;
for y in sl:
sf+='.'
sf+=y
print(sf)
|
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte... | 3 | l = int(input())
s = str(input())
m = int(s)
if l == 2:
print(int(s[0]) + int(s[1]))
else:
for i in range(l//2, l):
if s[i] != '0':
m = min(int(s[i:]) + int(s[:i]), m)
break
for i in range(l//2 + 1, 0, -1):
if s[i] != '0':
m = min(int(s[i:]) + int(s[:i]), ... |
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n.
Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times.
Alice wins if she beats Bob in at lea... | 3 | import sys
#import heapq as hq
#from collections import deque
#sys.stdin = open('in', 'r')
readline = sys.stdin.readline
rdw = lambda: readline().rstrip()
rdws = lambda: readline().split()
rdwl = lambda: list(readline().split())
rdi = lambda: int(readline())
rdis = lambda: map(int, readline().split())
rdil = lambda: li... |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | a=[]
x=0
y=0
for i in range(5):
c=list(map(int,input().strip().split(' ')))
if(c.count(1)>0):
x=c.index(1)
y=i
print(abs(x-2)+abs(y-2))
|
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas... | 3 | from collections import Counter
k = Counter("Bulbasaur")
r = Counter(input())
print(min([r[c] // k[c] for c in k]))
|
We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N. We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M). AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 β€ i β€ N)... | 3 | N, M = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
P[i] -= 1
T = [[] for _ in range(N)]
for _ in range(M):
x, y = map(int, input().split())
x-=1
y-=1
T[x].append(y)
T[y].append(x)
s1 = set()
def dfs(x):
s1.add(x)
s2 = set([x])
stack = [x]
whi... |
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number nΒ·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 3 | from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | n = int(input())
s = input()
cnt = s.count('A')
if cnt>(n/2):
print('Anton')
elif cnt==(n/2):
print('Friendship')
else:
print('Danik') |
Given an integer x, find 2 integers a and b such that:
* 1 β€ a,b β€ x
* b divides a (a is divisible by b).
* a β
b>x.
* a/b<x.
Input
The only line contains the integer x (1 β€ x β€ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | x = int(input())
pairs = []
for b in range(x+1):
for a in range(b, x+1):
if a*b > x and a % b == 0 and a // b < x:
pairs.append((str(a), str(b)))
if pairs:
print(' '.join(pairs[0]))
else:
print('-1')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.