problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | p = input()
for i in p:
if i in 'HQ9':
print('YES')
break
else:
print('NO')
|
There are N positive integers written on a blackboard: A_1, ..., A_N.
Snuke can perform the following operation when all integers on the blackboard are even:
* Replace each integer X on the blackboard by X divided by 2.
Find the maximum possible number of operations that Snuke can perform.
Constraints
* 1 \leq N... | 3 | input()
A=list(map(int,input().split()))
index = 0
while all (a%2 == 0 for a in A):
A = [a/2 for a in A]
index += 1
print(index) |
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k.
Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic... | 3 | n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
c = 0
for d in a:
if d <= k:
c += 1
else:
for d in a[::-1]:
if d <= k:
c += 1
else:
break
break
print(c) |
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... | 3 | import math
text = [*open(0)]
for s in text[1:]:
n, m, k = map(int, s.strip().split())
if m == 0:
print(0)
elif m <= n // k:
print(m)
else:
a = n // k
m -= a
if m // (k - 1) < 0:
print(a - 1)
else:
print(a - math.ceil(m / (k - 1)))... |
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the ... | 3 | t,s,x=map(int,input().split())
y=x-t
if (y%s==0 or (y%s==1 and y//s>=1)) and x>=t:
print("YES")
else :
print("NO")
|
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 | s=input();
print(s[0].upper()+s[1:]); |
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 | st = input().lower()
final_string = ''
vowels = ['a', 'o', 'y', 'e', 'u', 'i']
for i in range(0, len(st)):
if (not (st[i] in vowels)):
final_string += '.'+st[i]
print(final_string)
|
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n Γ m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | import os
import heapq
import sys
import math
from collections import defaultdict
from io import BytesIO, IOBase
# def gcd(a, b):
# if b == 0:
# return a
# else:
# return gcd(b, a % b)
def main():
#mod = 10 ** 9 + 7
for _ in range(int(input())):
#n=int(input())
n, m, x... |
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive ... | 3 | from math import factorial
mod=10**9+7
def cmb(n, r):
if n-r<0:
return 0
else:
return factorial(n) // factorial(r) // factorial(n - r)
n,k=map(int,input().split())
for i in range(1,k+1):
print(((cmb(n-k+1,i)%mod)*(cmb(k-1,i-1)%mod))%mod) |
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] m... | 3 | for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
odd, even = [], []
for i in range(len(arr)):
if i % 2 == 0 and arr[i] % 2 != 0:
even.append(arr[i])
elif i % 2 != 0 and arr[i] % 2 == 0:
odd.append(arr[i])
if len(even) == len(odd):
print(len(even))
... |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 3 | def function1(a,b):
hour=0
n=0
while a>=1:
hour+=1
a-=1
n+=1
if n%b==0:
a+=1
n=0
return hour
def main():
a,b=list(map(int,input().split()))
print(function1(a,b))
if __name__=='__main__':
main()
|
There are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the da... | 3 | n=int(input())
a=[]
b=[]
if n==3:
print("1 2 3")
else:
for i in range(n):
x,y=map(int,input().split())
a.append(x)
b.append(y)
real=[1]
for i in range(n-1):
c,d=a[real[-1]-1],b[real[-1]-1]
if d==a[c-1] or d==b[c-1]:
real.append(c)
else:
... |
Ron is a happy owner of a permutation a of length n.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is... | 3 | from sys import stdin,stdout
import math,bisect
from collections import Counter,deque,defaultdict
L=lambda:list(map(int, stdin.readline().strip().split()))
M=lambda:map(int, stdin.readline().strip().split())
I=lambda:int(stdin.readline().strip())
S=lambda:stdin.readline().strip()
C=lambda:stdin.readline().strip().split... |
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers β amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers ... | 3 | l,r,x,y,k=map(int,input().split())
l+=(k-l%k)%k
r-=r%k
print("YES"if l<=r and k*x<=r and l<=k*y else"NO") |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | n = int(input())
count = 0
for i in range(n):
a, b, c = map(int, input().split())
while a <= c and b <= c:
if a < b: a += b
else: b +=a
count += 1
print(count)
count = 0 |
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 β€ i β€ k). The store has an infinite number of packages of each type.
Polycarp wants to choose one type of packages and then buy several (one or... | 3 | from math import sqrt
for _ in range(int(input())):
n, k = [int(i) for i in input().split()]
maxDiv = 1
if k < sqrt(n):
lim = k+1
else:
lim = int(sqrt(n)+1)
for i in range(1,lim):
if n%i == 0:
if n//i <= k:
maxDiv = n//i
br... |
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())
tc= 0
for _ in range(0,n):
a,b,c = map(int , input().split())
if a+b+c>=2:
tc+=1
print(tc) |
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t.
Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second... | 1 | import sys
(h1,m1) = raw_input().split(':')
(h2,m2) = raw_input().split(':')
nh = int(h1) - int(h2)
nm = int(m1) - int(m2)
if nm < 0:
nm += 60
nh -= 1
if nh < 0:
nh += 24
s1 = str(nh)
s2 = str(nm)
if nh < 10:
s1 = '0' + s1
if nm < 10:
s2 = '0' + s2
print s1+':'+s2
|
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 | import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int, input().split()))
print(*sorted(A, reverse=True)) |
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes... | 3 | e= list(map(int, input().split()))
a,b,c,d=e[0],e[1],e[2],e[3]
if max(3*a/10,a-(a/250)*c)>max(3*b/10,b-(b/250)*d):
print('Misha')
elif max(3*a/10,a-(a/250)*c)<max(3*b/10,b-(b/250)*d):
print('Vasya')
else:
print('Tie')
|
<image>
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to tran... | 1 | #!/usr/bin/python
import os
import sys
import itertools
def solve(f):
n = f.read_int()
l = sorted(f.read_int_list(), reverse=True)
if l[0] > sum(l[1:]):
return l[0] - sum(l[1:]) + 1
else:
return 1
class Reader(object):
def __init__(self, filename=None):
self.test_mode = f... |
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below... | 1 | #!/usr/bin/env python2
n = int(raw_input())
inf = -10000
M = {"void": 0, "errtype": inf}
for i in xrange(n):
line = raw_input().split()
s1 = line[0]
s2 = line[1]
if len(line) > 2: s3 = line[2]
d = s2.count("*") - s2.count("&")
s2 = s2.strip('*&')
d += M.get(s2, inf)
if d < 0: d = inf
if s1 == "typedef":
M[s... |
Pravin and Saddam are room-mates.They always solve aptitude questions together. Once, they came across a problem stated as:
"Find the digit at the unit place that appears in sum of factorials of all numbers between A and B (both inclusive)."
Though they are good at mathematics ,but this time they are scratching their... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def fact(num):
if(num==1):
return 1
else:
return num*fact(num-1)
t=input()
t=int(t)
for i in range(t):
sum=0
m=raw_input()
x=[int(j) for j in m.split()]
s=len(x)
for k ... |
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 | print([['1' if input().split().count('1')>1 else '0'] for _ in range(int(input()))].count(['1'])) |
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 | ans = ""
for _ in range(int(input())):
x = int(input())
ans = f"{ans}{x-1>>1 if x > 2 else 0} "
print(ans) |
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())
sizes = list(map(int, input().split()))
if n == 1:
if sizes[0] == 0:
print('UP')
elif sizes[0] == 15:
print('DOWN')
else:
print(-1)
else:
if sizes[n - 1] > sizes[n - 2]:
if sizes[n - 1] < 15:
print('UP')
else:
print('DOWN')... |
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 | def getLines(num):
inputLines = []
for i in range(0,num):
line = input()
if line:
inputLines.append(line)
else:
break
return inputLines
line = getLines(1)[0]
result = "YES" if int(line) % 2 == 0 and int(line) > 2 else "NO"
print(result)
|
You are given an array a consisting of n integers.
Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.
Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c... | 3 | for i in range(int(input())):
n = int(input())
a = [int(s) for s in input().split()]
d = {}
for j in range(n):
d.setdefault(a[j],set())
d[a[j]].add(j)
for j in d.values():
l = len(j)
if l >= 3:
print('YES')
break
elif l == 2:
... |
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ... | 3 | n=int(input())
c1=c2=0
l=[int(x) for x in input().split()]
for i in range(n):
if(l[i]==100):
c1+=1
else:
c2+=1
if(c1%2==0 and c2%2==0):
print("YES")
elif((c1==0 and c2!=0 and c2%2==0)or(c2==0 and c1!=0 and c1%2==0)):
print("YES")
elif(c1%2==0 and c2%2!=0 and c1!=0):
print("YES")
else... |
"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 |
def main():
t, n = input().split(" ")
arr = [int(i) for i in input().split(" ") if i != '']
n = int(n)
m = arr[n-1]
if m == 0:
m += 1
ans = 0
for i in arr:
if i >= m:
ans +=1
print(ans)
main() |
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 | import math
for q in range(int(input())):
a,b,c,d=map(int,input().split())
ans = b
te = a-b
if te<=0:
print(b)
else:
if te>0 and c-d <=0:
print(-1)
else:
te = math.ceil(te/(c-d))
te *=c
ans+=te
print(ans) |
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ... | 3 | n=int(input())
l=list(map(int,input().split()))
m=int(input())
s=list(map(int,input().split()))
print(max(l),max(s)) |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | def amazingPerformance(scores):
smallest = largest = scores[0]
howMany = 0
for s in scores[1:]:
if s < smallest:
smallest = s
howMany += 1
if s > largest:
largest = s
howMany += 1
return howMany
size = int(input())
scores = [int(i) for... |
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute β health points, shortened to HP.
In general, different values of HP are grouped into 4 categories:
* Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ... | 3 | a=int(input())+2
a=a%4
if(a==0): print(1,'B')
else: print(3-a,'A') |
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
l=[]
for i in range(n):
ll=list(map(int,input().split()))
l.append(ll)
c=0
r=0
for i in range(n):
if l[i]==[0]*m:
c+=1
for j in range(m):
p=[l[x][j] for x in range(n)]
if p==[0]*n:
... |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | s1 = input()
s2 = input()
s1=s1.upper()
s2=s2.upper()
for i in range(len(s1)):
if s1[i]==s2[i]:
continue
elif s1[i]<s2[i]:
print(-1)
exit(0)
elif s1[i]>s2[i]:
print(1)
exit(0)
print(0)
|
Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the... | 3 | # coding: utf-8
O = input()
E = input() + " "
print("".join([o+e for o,e in zip(O, E)])) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | input()
s = input()
res = 0
for a in 'RGB':
for i in range(len(s)-1):
if s[i:i+2] == a*2:
res += 1
print(res) |
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one can... | 1 | m,t,r = map(int,raw_input().split())
a=map(int,raw_input().split())
if r > t: print('-1')
else:
cand=[]
ans=0
for i in a:
lite=0
for j in cand:
dif=i-j
if dif<=t:
lite+=1
to_lite=r-lite
c=i-1
for j in xrange(to_lite):
ans+=1
cand.append(c)
c-=1
print ans
|
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.
The bus stop queue has n groups of people. The i-th group from the beginning has ... | 3 | n, m = map(int, input().split())
q = list(map(int, input().split()))
i = 0
nrb = 0
while i < n:
cap = 0
nrb += 1
while i < n and cap + q[i] <= m:
cap += q[i]
i += 1
print(nrb) |
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.
Constraints
* $2 \leq n \leq 100,000$
* $0 \leq m \leq 100,000$
* $1 \leq q \leq 10,000$
Input
In the first line, two integer $n$ and $m$ are given. $n$ is the ... | 3 | n, m = map(int, input().split())
rootList = [-1 for i in range(n)]
def getRoot(x):
if rootList[x] < 0:
rootList[x] = x
elif rootList[x] != x:
rootList[x] = getRoot(rootList[x])
return rootList[x]
def setSameRoot(x, y):
x = getRoot(x)
y = getRoot(y)
rootList[x], rootList[y] ... |
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and... | 3 | from collections import defaultdict
n=int(input())
a=[int(x) for x in input().split()]
mx=max(a)
dp=[0]*(mx+1)
for i in range(n):
dp[a[i]]+=1
ans=[0,dp[1]]
#print(dp)
for i in range(2,mx+1):
res=max(ans[-1],ans[-2]+i*dp[i])
ans+=[res]
#print(ans)
print(ans[-1]) |
You are given an array a_1, a_2, ..., a_n consisting of n distinct integers. Count the number of pairs of indices (i, j) such that i < j and a_i β
a_j = i + j.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t cases follow.
The first line of each test case contains one int... | 3 | for i in range(int(input())):n=int(input());a=list(map(int,input().split()));print(len([j for j in range(n) for k in range(a[j]-j-2,n,a[j]) if a[j]*a[k]==j+k+2 and j<k])) |
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | def solve(a,n):
x=len(a)
while x!=0:
Count=0
for i in range(0,len(a)):
if x<=a[i]:
Count+=1
if Count==x:
return x
x-=1
return 1
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
... |
Harry is playing a game with is friend. He is given a notebook which has names of their friends written in various lowercase letter from 'a' to 'z'. His task is to find a 'special-letters'. A letter is a 'special-letters' if it occurs at least once in each of their friends name.
Given the list of N names, display the ... | 1 | s=set([chr(i) for i in xrange(97,97+26)])
for _ in xrange(input()):
s=set(list(raw_input())).intersection(s)
print len(s) |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 β€ n β€ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | n=int(input())
if n%2==0:
e=n//2
o=((n-1)//2)+1
else:
e=(n-1)//2
o=(n//2)+1
se=e*(e+1)
so=o**2
print(se-so) |
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two.
You may perform any number (possibly, zero) operations with this multiset.
During each operation you choose two equal integers from s, remove them from s and insert the number eq... | 3 | for _ in range(int(input())):
n = int(input())
a = sorted(list(map(int,input().split())))
a.reverse()
if 2048 in a:
print('YES')
else:
p = 0
for i in range(n):
if a[i]<2048: p = i; break
a = a[p:]
s = 0
for i in range(len(a)):
s += a[i]
if s==2048: print('YES'); break
else: print('NO') |
The door of Snuke's laboratory is locked with a security code.
The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.
You are given the current security code S. If S is hard to enter, print `Bad`; otherwise, print `Good`.
Constraint... | 3 | s=list(str(input()))
print('Bad' if s[0]==s[1] or s[1]==s[2] or s[2]==s[3] else 'Good') |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | tlist=[]
n=int(input())
for i in range(0,n):
ele=input()
tlist.append(ele)
tdict={
"Tetrahedron":4,
"Cube":6,
"Octahedron":8,
"Dodecahedron":12,
"Icosahedron":20
}
t=0
for x in tlist:
t=int(tdict[x])+t
print (t) |
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team.
At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix... | 3 | s = input()
t = input()
np = 0
for c in s:
if np < len(t) and c == t[np]:
np += 1
if np == len(t):
print('automaton')
else:
ds = {}
dt = {}
for c in s:
if c not in ds:
ds[c] = 0
ds[c] += 1
for c in t:
if c not in dt:
dt[c] = 0
dt[c]... |
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 1 | n, m = map(int, raw_input().split())
count = [[0, 0, 0, 0, 0] for i in xrange(m)]
options = ['A', 'B', 'C', 'D', 'E']
for i in xrange(n):
answers = raw_input()
for j in xrange(m):
index = options.index(answers[j])
count[j][index] += 1
max_score = 0
points = map(int, raw_input().split())
for ... |
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot re... | 3 | for _ in range(int(input())):
n=int(input())
s=input()
l=[]
for i in s:
if i not in l:
l.append(i)
if l[-1]==i:
pass
else:
print('NO')
break
else:
print('YES') |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n, k = map(int, input().split())
for _ in range(k):
if str(n)[-1] == "0":
n = str(n)[:-1]
else:
n = int(n) - 1
print(n) |
Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:
* Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).
* The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectiv... | 3 | N,M = map(int,input().split())
A = list(map(int,input().split()))
c = [2,5,5,4,5,6,3,7,6]
A.sort(reverse=True)
dp = [-1 for _ in range(N+1)]
dp[0] = 0
for a in A:
c_ = c[a-1]
for i in range(c_,N+1):
if dp[i-c_] == -1: continue
dp[i] = max(dp[i], dp[i-c_]*10 + a)
print(dp[-1]) |
You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types:
* increase x by 1;
* decrease x by 1.
You are given m queries of the following format:
* query l r β how many distinct values is x assigned to if all the... | 3 | mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.readline
class SegmentTree:
def __init__(self, A, initialize=True, segfunc=min, ident=2000000000):
self.N = len(A)
self.LV = (self.N - 1).bit_length()
self.N0 = 1 << self.LV
self... |
1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:
* the dogs numbered 1,2,\cdots,26 were respectively given the names `a`, `b`, ..., `z`;
* the dogs numbered 27,28,29,\... | 3 | N = int(input())
ans = ''
while(N > 0):
N -= 1
_i = N % 26
ans = chr(ord('a') + _i) + ans
N //= 26
print(ans) |
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 |
t=int(input());
count=0
while(count<t):
n,r=map(int,input().split())
count=count+1;
if(n<=r):
n=n-1
print(int((n*(n+1))//2 +1))
else:
print(int((r*(r+1))//2))
|
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion:
* An 'L' indicates he should move one unit left.
* An 'R' indicates he should move one unit right.
* A 'U' indicates he should move one unit up.
* A 'D' indicates he shoul... | 3 | s=input()
if len(s)%2!=0:
print(-1)
else:
l,r,u,d=0,0,0,0
for i in range(len(s)):
if s[i]=='U':
u+=1
elif s[i]=='D':
d+=1
elif s[i]=='R':
r+=1
else:
l+=1
print((abs(l-r)+abs(u-d))//2)
|
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.
Each player can double his bid any number of times and triple his bid any number of ... | 3 | from math import gcd
nb = int(input())
liste2=[]
liste =[int(x) for x in input().split()]
def pp():
for loop in range(len(liste)):
while liste[loop]%2 ==0 :
liste[loop] //=2
while liste[loop]%3 ==0:
liste[loop] //=3
liste2.append(liste[loop])
if liste2.count(liste... |
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it... | 3 | __author__ = 'pxy'
n=int(input())
g=[int(j) for j in input().split()]
b=0
t=0
for z in g:
if z==1:
if b>=2 and t>0:
t+=1-b
else:
t+=1
b=0
else:
b+=1
if t>0:
t+=1
if t==0:
print(0)
else:
print(t-b)
|
It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.
You are given an integer N. Find the N-th Lucas number.
Here, the i-th Lucas number L_i is defined as follows:
* L_0=2
* L_1=1
* L_i=L_{i-1}+L_{i-2} (iβ₯2)
Constraints
* 1β€Nβ€86
* It is guaranteed that the answer is less than 10^{18}.
... | 3 | n = int(input())
l0, l1 = 2, 1
for i in range(n):
l0, l1 = l1, l0+l1
print(l0) |
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
... | 3 | a=[int(x) for x in input().split()]
a1=(a[0]+a[3])*(a[1]+a[2])
#print(a1)
a2=(a[1]*a[2])
a3=(a[4]*a[5])
#print(a2+a3)
print(a1+a2+a3) |
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then... | 3 | s={input():i for i in range(int(input()))}
print(*[i[0] for i in sorted(s.items(),key=lambda x:x[1],reverse=True)],sep='\n') |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, β¦, a_n, in ... | 1 | from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
from fractions import gcd
import heapq
raw_input = stdin.readline
pr = stdout.write
mod=998244353
def ni():
return int(raw_input())
def li():
return list(map(int,raw_input().split()))
... |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 1 | n = int(raw_input())
a = set(map(int, raw_input().split()))
a.discard(0)
print len(a) |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | t = int(input())
for i in range(t):
a,b = [int(item) for item in input().strip().split()]
if a % b == 0:
print (0)
else:
print (b-(a%b))
|
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pour... | 3 | n,m=map(int,input().split())
from collections import defaultdict
d=defaultdict(list)
for i in range(m):
x,y=map(int,input().split())
x=x-1
y=y-1
d[x].append(y)
d[y].append(x)
ans=1
maxi=0
c=0
vis=[0]*n
for i in range(n):
if not vis[i]:
q=[i]
c= c+1
vis[i]=1
... |
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)
else :
count = 0
flag = 0
while (n!=1) :
if(n%3 == 0 ):
if (n%2 == 0 ):
n = n//6
count += 1
else :
... |
We have a string S of length N consisting of `R`, `G`, and `B`.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
* j - i \neq k - j.
Constraints
* 1 \leq N \leq 4000
* S is a string of length N consisting of... | 3 | n=int(input())
ss=list(input())
res= ss.count('R') * ss.count('G') * ss.count('B')
for i in range(n):
for j in range(i+1,n):
k = 2*j-i
if k >= n:
continue
if all([ss[i] != ss[j],ss[j] != ss[k],ss[k] != ss[i]]):
res-=1
print(res) |
There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.
The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.
Your task is to determine the mi... | 1 | m = [map(int, raw_input().strip()) for _ in range(int(raw_input()))]
z = zip(*m)
ans = 0
for i in z:
ans = max(ans, sum(i))
print ans
|
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".
The field for the new game is a rectangle table of size n Γ m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game la... | 3 | n, m = (int(x) for x in input().split())
st = set()
for i in range(n):
s = input()
g = s.index('G')
s = s.index('S')
if g > s:
print(-1)
exit(0)
st.add(s - g)
print(len(st))
|
You are given n Γ m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:
1. All cells in a set have the same color.
2. Every two cells in a set share row or column.
Input
The first line of input contains integers n and m (1 β€ n, m β€ 50) β the number of ... | 3 | n,m = list(map(int,input().split()))
mat = []
ans = -m*n
for i in range(n):
mat.append(list(map(int,input().split())))
total = sum(mat[-1])
ans+=(2**total-1)
ans+=((2**(m-total))-1)
for i in range(m):
total = 0
for j in range(n):
total+=mat[j][i]
ans+=(2**total-1)
ans+=((2**(n-t... |
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills:
a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.
For example, sequences [1, 5], [10], [5... | 1 | n = int(raw_input())
a = map(int,raw_input().split())
a.sort()
ans = []
if n == 1:
print "-1"
elif n == 2:
ans.append(2*a[0]-a[1])
if a[0] != a[1]:
ans.append(2*a[1]-a[0])
if (a[0]+a[1])%2 == 0:
ans.append((a[0]+a[1])/2)
else:
t = []
for i in range(n-1):
... |
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | def brainPhotos(ar):
x = ['C', 'Y', 'M']
for i in x:
if i in ar:
return "#Color"
return "#Black&White"
n, m = map(int, input().split())
ar = []
for i in range(n):
arr = input().split()
ar += arr
print(brainPhotos(ar)) |
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β₯ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subar... | 3 | n,k = map(int , input().split())
a = list(map(int , input().split()))
ans = a[n-1] - a[0]
diff = []
for i in range(1,n):
diff.append(a[i-1] - a[i])
diff.sort()
for i in range(k-1):
ans+=diff[i]
print(ans) |
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 β€ x β€ a) coins of value n and y (0 β€ y β€ b) coins of value 1, then the total value of taken coins will be S.
You have to answer q independent test cases.
Input
The... | 3 | q=int(input())
for _ in range(q):
a,b,n,s=map(int,input().split(" "))
x=s//n
x1=s%n
if x<=a:
if x1<=b:
print("YES")
else:
print("NO")
elif b>=s:
print("YES")
elif s-a*n<=b:
print("YES")
else:
print("NO") |
You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).
Input
The first line contains the single positive integer n (1 β€ n β€ 105) β the number of integers.
The second line contains n positive integers ... | 3 | import os
import sys
debug = True
if debug and os.path.exists("input.in"):
input = open("input.in", "r").readline
else:
debug = False
input = sys.stdin.readline
def inp():
return (int(input()))
def inlt():
return (list(map(int, input().split())))
def insr():
s = input()
return (list(... |
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c... | 3 | t = int(input())
res = []
suivant = {}
suivant['a'] = 'b'
suivant['b'] = 'c'
suivant['c'] = 'a'
def verifyBeautiful(word):
for j in range(len(word)-1):
if word[j] == word[j+1]:
return False
return True
for i in range(t):
s = input()
new = ""
#First character
if s[0] =... |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n = int(input())
s = ''
while n > 0:
s += input()
n -= 1
print(s.count('00') + s.count('11') + 1) |
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ... | 3 | r = lambda: map(int,input().split())
y,b = r()
j,k,l = r()
print (max(0,(k+3*l)-b) + max(0,(k+2*j)-y))
|
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n ... | 1 | n=input()
s=raw_input().split()
ans=0
for i in range(len(s)):
cnt=0
for j in range(len(s[i])):
if "A"<=s[i][j]<="Z": cnt+=1
ans=max(cnt,ans)
print ans |
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 | def solve(a,b):
if(b>a):
res = (b-a)//10
if(b-a)%10 != 0:
res +=1
return res
else:
a,b = b,a
res = (b-a)//10
if(b-a)%10 != 0:
res +=1
return res
t = int(input())
for _ in range(t):
a,b = map(int,input().split())
print(solve(a,b)) |
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of ... | 3 | n,m=map(int,input().split())
s=[]
st=set()
cst=set()
for i in range(n):
s.append(input())
for j in range(len(s[i])):
if s[i][j]=='#':
st.add((i,j))
for i in range(1,n-1):
for j in range(1,m-1):
if s[i-1][j-1]!='#':
continue
if s[i - 1][j ] != '#':
... |
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 β€ pi β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou... | 3 | n, k = map(int, input().split())
mod = 1000000007
print((pow(k, k-1, mod) * pow(n-k, n-k, mod)) % mod) |
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 | guest = input()
host = input()
all = guest+host
x = input()
if len(guest) + len(host) != len(x):
print('NO')
else:
ss = set(x)
for a in ss:
if all.count(a) != x.count(a):
print('NO')
break
else:
print('YES')
|
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 3 | d1,d2,d3=map(int,input().split())
if d1<d2:
c=d1+min(d1+d2,d3)+min(d3+d1,d2)
else:
c=d2+min(d1+d2,d3)+min(d1,d3+d2)
print(c) |
You have array of n numbers a_{1}, a_{2}, β¦, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| β€ |a_{2} - a_{3}| β€ β¦ β€ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 3 | import math,sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda:int(input())
li = lambda:list(map(int,input().split()))
def case():
n=int(input())
a=li()
a.sort()
d=defaultdict(list)
a.sort()
ans=[]
for i in range(1,n//2+1):
ans.append(a[i-1]... |
You are given a board of size n Γ n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move... | 3 | for _ in range(int(input())):
n=int(input())
if n==1:
print(0)
else:
a=1
s=1
c=8
t=0
while a<n:
t+=s*c
a+=2
s+=1
... |
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using... | 3 | H, N = map(int, input().split())
a = sum(map(int, input().split()))
print("Yes" if a >= H else "No") |
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?
Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime... | 3 | t = int(input())
Q = []
for i in range(t):
Q.append(input())
x = [int(i.split(" ")[0]) for i in Q]
y = [int(i.split(" ")[1]) for i in Q]
def isPrime(x):
if x < 2:
return False
if x % 2 == 0 and x > 2:
return False
if all(x % i != 0 for i in range(2, int(x**.5) + 1)):
return... |
Given an integer n, find the maximum value of integer k such that the following condition holds:
n & (n-1) & (n-2) & (n-3) & ... (k) = 0 where & denotes the [bitwise AND operation.](https://en.wikipedia.org/wiki/Bitwise_operation#AND)
Input
The first line contains a single integer t (1 β€ t β€ 3 β
10^4). Then t test... | 3 | from sys import stdin,stdout
nmbr = lambda: int(input())
lst = lambda: list(map(int, input().split()))
for _ in range(nmbr()):
n=nmbr()
# n,k=lst()
# a=lst()
x=1
if n==1:
print(0)
continue
while x*2+1<n:
x=x*2+1
print(x) |
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and ... | 3 | class CodeforcesTask862BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.tree = []
def read_input(self):
self.n = int(input())
for x in range(self.n - 1):
self.tree.append([int(y) for y in input().split(" ")])
def process_task(self):
... |
Serval is fighting with a monster.
The health of the monster is H.
In one attack, Serval can decrease the monster's health by A. There is no other way to decrease the monster's health.
Serval wins when the monster's health becomes 0 or below.
Find the number of attacks Serval needs to make before winning.
Constrai... | 3 | h,a=map(int,input().split())
n=((h-1)//a)+1
print(n) |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | n = int(input())
counter = 0
if n >= 5:
counter += n//5
n = n%5
for i in range(1,5):
if n == i:
counter += n//i
n = n%i
print(counter) |
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 | n,m,a=map(int, input().split())
import math
math.ceil
z=math.ceil
x=z(n/a)
y=z(m/a)
print(x*y) |
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 β€ fi β€ n and fi β i.
We call a love triangle a situation in which plane A likes plane... | 3 | n = int(input())
if n < 3:
print("NO")
exit(0)
a = [int(i) - 1 for i in input().split()]
for i, x in enumerate(a):
if i == a[a[x]]:
print("YES")
break
else:
print("NO") |
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ... | 1 | def a(vals):
carrying = "X"
lim = 5
times = 0
answer = 0
for val in vals:
if val != carrying:
carrying = val
answer += 1
times = 1
continue
if times == lim:
times = 1
answer += 1
continue
times += 1
return answer
#"""
print a(raw_input())
"""
print a... |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | 3 | from math import ceil
a,b=map(int,input().split())
i=b
while(i<=a):
a=a+1
i=i+b
print(a)
|
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 1 | n = input()
input = raw_input()
s = [0]
for ch in xrange(1,5):
s.append(input.count(str(ch)))
res = 0
res += s[4]
s[4]=0
res += s[3]
s[1] = max(0,s[1]-s[3])
s[3]=0
from math import ceil
res += int(ceil((s[2]*2.+s[1])/4))
print res |
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit c... | 3 | k2, k3, k5, k6 = [int(elem) for elem in input().split()]
summ = min(k2,k5,k6)*256 + min(k3, k2 - min(k2,k5,k6))*32
print(summ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.