problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c... | 3 | a,b=map(int,input().split())
a,b=max(a,b),min(a,b)
i=0
if a<=1:
print(0)
else:
while a-b!=1 and a!=b:
a-=2
b+=1
a,b=max(a,b),min(a,b)
i+=1
if a==b:
print(i+a+b-3)
else:
print(i+a+b-2) |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | a ,b= input().split(' ')
a=int(a)
b=int(b)
ar = list(map(int, input().strip().split(' ')))
sum=0
i=0
while a!=i:
if ar[i]>b:
sum+=2
else:
sum+=1
i+=1
print(sum) |
We have A balls with the string S written on each of them and B balls with the string T written on each of them.
From these balls, Takahashi chooses one with the string U written on it and throws it away.
Find the number of balls with the string S and balls with the string T that we have now.
Constraints
* S, T, and ... | 3 | S, T = input().split()
A, B = map(int, input().split())
U = input()
print(A-1 if U==S else A, B-1 if U==T else B) |
Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.
In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".
The current time is A o'clock, and a contest will begin in exactly B hours. When will the contest begin? Answer in 24-hour time.
Constrain... | 3 | a,b=map(int,input().split())
print(a+b-(a+b>=24)*(24)) |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | n = int(input())
s = input().strip()
s1 = 0
s2 = 0
for i in range(1, len(s)):
if s[i] != s[i - 1]:
if s[i - 1] == 'S':
s1 += 1
else:
s2 += 1
if s1 > s2:
print("YES")
else:
print("NO") |
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 | o,d=map(int,input().split())
u=0
res=0
for i in range(d):
a=int(input())
if (a*9)+1==10**o :
if u<res:
u=res
res=0
elif (a*9)+1<10**o :
res+=1
if u<res:
u=res
print(u)
|
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 | x=int(input())
if x%2==0 and not x == 2:
print('YES')
else:
print('NO')
|
There are N dishes, numbered 1, 2, \ldots, N. Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it.
Taro will perform the following operation repeatedly until all the pieces of sushi are eaten:
* Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, a... | 3 | import sys
from collections import Counter
sys.setrecursionlimit(10000)
N = int(input())
a = list(map(int, input().split()))
dp = [[[-1 for i in range(N+1)] for j in range(N+1)] for k in range(N+1)]
def rec(i, j, k):
if dp[i][j][k] >= 0:
return dp[i][j][k]
if i == 0 and j == 0 and k == 0:
retu... |
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha... | 3 | # Silent Classroon
def classroom(names):
letters = {}
for i in names:
if i[0] in letters:
letters[i[0]] += 1
else:
letters[i[0]] = 1
di = {}
ans = 0
for i in letters.values():
if i & 1 == 1:
m = i // 2
l = m + 1
if m... |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | s = input()
word = []
k = ''
if len(s) % 2 == 0:
word.append(s[-1])
s = s[0: len(s) - 1]
for i in range(0, len(s) // 2):
word.append(s[len(s) - i - 1] + s[i])
word.append(s[len(s) // 2])
else:
for i in range(0, len(s) // 2):
word.append(s[len(s) - i - 1] + s[i])
word.append(s[le... |
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 | r=int(input())
for i in range (r):
a,b=map(int,input().split())
if (b>a ):
a,b=b,a
if(a==b):
nbre=0
else:
nbre=-1
if (a%b==0 and (a//b)%2==0):
dv=a//b
n=0
while(dv%2==0 and dv!=1 ):
dv=dv//2
n+=1
... |
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter... | 1 | igra=raw_input()
morjey=int(igra.split(' ')[0])
fishek=int(igra.split(' ')[1])
result=0
while fishek>0:
for i in range(1,morjey+1):
if fishek<i:
result=fishek
fishek=0
break
fishek-=i
print result |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | input()
i = input()
ans = ''
a, iter = 1, 1
while a <= len(i):
ans += i[a-1]
a += iter
iter+=1
print(ans) |
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:
... | 3 | import sys
import os
from io import IOBase, BytesIO
# import heapq
import math
# import collections
# import itertools
# import bisect
mod = 10 ** 9 + 7
pie = 3.1415926536
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
# import threading
# threading.stack_size(2**27... |
Given N space separated integers. Your task is to arrange them such that the summation M of the absolute differences between every two adjacent numbers is maximum.
Input:
First line of the input contains an integer N.
Second line contains N space separated integers A_i.
Output:
Print the above described ... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
T=int(raw_input())
arr=map(int,raw_input().strip().split(" "))
arr.sort()
i=0
j=len(arr)-1
sum1=0
count=0
while i<j:
sum1+=arr[j]-arr[i]
count+=1
if count%2==1:
i+=1
else:
j-=1
... |
It is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically.
After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off t... | 3 | n = int(input())
s = list(input())
a = []
b = []
max_active = 0
prev = [0] * n
for i in range(n):
prev[i] = int(s[i])
x, y = map(int, input().split())
a.append(x)
b.append(y)
active = sum(prev)
max_active = max(active, max_active)
for i in range(1, 1000):
for j in range(n):
if i >= b[j]:
... |
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 | from collections import deque
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = set()
b = deque([], k)
for i in a:
if(i not in s):
if(len(b) >= k):
x = b.popleft()
s.remove(x)
b.append(i)
s.add(i)
print(len(b))
print(*(list(b)[::-1])) |
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels!
There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle...
Everybody was upset. The beautiful ... | 3 | H, M = [int(x) for x in input().split(':')]
H = H % 12
hAngle = 360 / 12
hmAngle = hAngle / 60
mAngle = 360 / 60
print(H * hAngle + M * hmAngle, end=' ')
print(M * mAngle)
|
Agent 47 attacks OO7 during the mission and uses Beretta M9 pistol (Semi Automatic). The pistol uses a 1mm bullet. The pistol bullet keeps changing the caliber after each consecutive fire. As the 1st round is fired, caliber of bullet triples and during 2nd round it's caliber increases by 2mm and then the trend repeats.... | 1 | t=input()
while t!=0:
t-=1
x=input()
if x>120:
print "UNABLE TO FIRE"
else:
a=1
for i in range(1,x+1):
if i%2!=0:
a*=3
else:
a+=2
print a |
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he und... | 3 | from bisect import bisect_right
from operator import itemgetter
s, b = map(int, input().split())
A = list(map(int, input().split()))
DG = [list(map(int, input().split())) for _ in range(b)]
DG.sort(key=itemgetter(0))
cumG = [0]
for d, g in DG:
cumG.append(cumG[-1]+g)
D = list(map(itemgetter(0), DG))
Ans = []
for a in... |
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop — 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the se... | 3 | n = int(input())
for i in range(n):
(a, b1, c2) = map(int, input().split())
sum = 0
if 2*b1 > c2:
sum += (a//2)*c2
if a % 2 == 1:
sum += b1
else:
sum += a*b1
print(sum)
|
There are K pieces of cakes. Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.
There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.
Eating the same type of cake two days in a row would be no fun, so Mr. Takahashi would like to decide the order for eating ... | 1 | #import string,itertools,fractions,heapq,re,array,bisect
#from math import *
#from collections import Counter
def rl(s): return xrange(len(s))
INF = 2147483647
import sys
stdin = sys.stdin
K, T = map(int, stdin.readline().strip().split())
aa = map(int, stdin.readline().strip().split())
aa.sort()
m = aa[-1]
can_... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with... | 1 | def main():
n = int(raw_input())
if n < 4:
print -1
return
res = ''
while n > 0 and n % 7 != 0:
res += '4'
n -= 4
if n < 0:
print -1
return
res += '7' * (n / 7)
print res
main() |
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:
* f(0) = 0;
* f(2·x) = f(x);
* f(2·x + 1) = f(x) + 1.
Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤... | 1 | def F(x):
if(x==0):
return 0
return F(x//2)+x%2
import sys
n=int(sys.stdin.readline())
L=list(map(int,sys.stdin.readline().split()))
for i in range(n):
L[i]=F(L[i])
L.sort()
cnt=1
p=L[0]
ans=0
for i in range(1,n):
if(L[i]==p):
cnt+=1
else:
ans+=(cnt*(cnt-1))//2
cnt... |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 |
def tran(n):
return int((n+1)/2)
if __name__ == '__main__':
t = int(input())
ans=[]
for i in range(t):
n=int(input())
p=tran(n)
ans.append(p)
for i in ans:
print(i)
|
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years.
The dormitory consists of n rooms and a single mouse! Girls decided to set mouse tra... | 3 | #yeh dil maange more
n = int(input())
c = [0]+(list(map(int,input().split())))
a = [0]+(list(map(int,input().split())))
vis = [0] * (n+1)
ans = 0
for i in range(1,n+1):
x = i
while vis[x] == 0:
vis[x] = i
x = a[x]
if vis[x] != i:
continue
v = x
mn = c[x]
#print("v = "... |
There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.
Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it. The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and... | 3 | H, W=map(int, input().split())
S=[input() for _ in range(H)]
tate=[[0]*W for _ in range(H)]
yoko=[[0]*W for _ in range(H)]
for i in range(W):
j=0
while j<H:
x=0
while j+x<H and S[j+x][i]=='.':
x+=1
if x==0:
tate[j][i]=0
j+=1
else:
for t in range(x):
tate[j+t][i]=x
... |
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of... | 3 | def solve():
a, b = [int(x) for x in input().split()]
print(int((b * (b - 1) // 2) * (a * (a + 1) * b // 2 + a) % (10**9 + 7)))
if __name__ == '__main__':
solve()
|
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m... | 1 | n = int(raw_input())
a = map(int, raw_input().split())
m = dict()
s = 0
for i, x in enumerate(a):
if x in m:
s += i - m[x] - 1
else:
m[x] = i
for x in xrange(1, n + 1):
index = m[x] + 1
between = set()
next_el = a[index]
while next_el != x:
if next_el not in between and ... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | s = input()
upL = 0
loL = 0
for ch in s:
if ch.islower():
loL = loL + 1
if ch.isupper():
upL = upL + 1
if upL > loL:
print(s.upper())
elif loL > upL:
print(s.lower())
else:
print(s.lower())
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | x= int(input())
for i in range(x):
y = input().lower()
if len(y) <= 10:
print(y)
else:
k = len(y)
z = k - 2
print(y[0] + str(z) + y[-1])
|
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | s1 = 'I hate '
s2 = 'I love '
s3 = 'that '
s4 = 'it'
n = int(input())
s = ''
for i in range(n):
if i % 2 == 0:
s += s1
else:
s += s2
if i < n - 1:
s += s3
else:
s += s4
print(s) |
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | def main():
for _ in range(int(input())):
n, m = map(int, input().split())
flag = 0
for _ in range(n):
a, b = map(int, input().split())
c, d = map(int, input().split())
if b == c:
flag = 1
if not m & 1 and flag == 1:
... |
Chef and his girlfriend are going to have a promenade. They are walking along the straight road which consists of segments placed one by one. Before walking Chef and his girlfriend stay at the beginning of the first segment, they want to achieve the end of the last segment.
There are few problems:
At the beginning ... | 1 | t=int(raw_input())
for i in range(t):
m=0
k=int(raw_input())
s=raw_input().split()
sh=[int(s[j]) for j in range(k)]
for j in range(k):
if m<sh[j]+j:
m=sh[j]+j
print m |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n=int(input())
x=0
for i in range(0,n):
s=input()
if s=="X++":
x=x+1
if s=="++X":
x=x+1
if s=="--X":
x=x-1
if s=="X--":
x=x-1
print(x)
|
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 | #!/usr/bin/env python
# coding: utf-8
# In[99]:
n=int(input())
reit=input()
x=reit.count('A')
if n-x==x:
print('Friendship')
elif x>n-x:
print('Anton')
else:
print('Danik')
# In[ ]:
# In[ ]:
|
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | 3 | n=int(input())
k=[]
l=[]
for i in range(n):
x,y=map(int,(input().split()))
k.append(x)
l.append(y)
c=0
for i in range(n):
for j in range(n):
if(l[i]==k[j] and i!=j):
c+=1
print(c)
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 1 | s=raw_input()
ans=s.replace('WUB',' ')
print ans
|
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons... | 3 | s1=input()
s2=input()
if len(s1) !=len(s2):
print("NO")
else:
z=0
v=['a','e','i','o','u']
c=['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
for i in range(len(s1)):
if (s1[i] in v and s2[i] in c) or (s1[i] in c and s2[i] in v):
z=-1
... |
You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string.
In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet f... | 3 | import re
n=int(input())
s=input()
for i in range(122,97,-1):x=chr(i)+'*';y=chr(i-1);s=re.sub(x+y+x,y,s)
print(n-len(s)) |
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 | #!/usr/bin/python3
# import sys
# input = sys.stdin.buffer.readline
T = int(input())
for _ in range(1, T + 1):
str = input()
answer = []
lastletter = str[-1]
answer.append(str[0])
str = str[1:-1]
for i in range(0, len(str), 2):
answer.append(str[i])
answer.append(lastletter)
pr... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n = int(input())
arr = sorted(list(map(int, input().split())), reverse=True)
agg = sum(arr)
reqagg, count = 0, 0
while reqagg <= (agg//2):
reqagg += arr[count]
count += 1
print(count) |
You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds:
* 1 x : Assign to a_x the value 1 - a_x.
* 2 k : Print the k-th largest value of the array.
As a reminder, k-th largest value of the array b is defined as following:
... | 3 | n,q=map(int,input().split())
l1=list(map(int,input().split()))
num=0
#num用来统计1的个数
for _ in l1:
if _==1:num+=1
for i in range(q):
t,x=map(int,input().split())
if(t==1 and (1-l1[x-1])==0):
num-=1
l1[x-1]=0
elif(t==1 and (1-l1[x-1]==1)):
num+=1
l1[x-1]=1
elif(t==2 and x<... |
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write
mp = lambda: list(map(int, cin().split()))
t, = mp()
for _ in range(t):
n, = mp()
s = cin()[:-1]
#one = zero = f = -1
one = s.find('1')%n
zero = s.rfind('0')
'''
for i in range(n):
if s[i] == '1' and f == -1:
one = i
f = 1
elif s... |
Ringo Mart, a convenience store, sells apple juice.
On the opening day of Ringo Mart, there were A cans of juice in stock in the morning. Snuke buys B cans of juice here every day in the daytime. Then, the manager checks the number of cans of juice remaining in stock every night. If there are C or less cans, D new can... | 3 | # -*- coding: utf-8 -*-
import sys
from fractions import gcd
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in ... |
Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an... | 3 | import sys
cups = sum(list(map(int, input().split())))
medals = sum(list(map(int, input().split())))
n = int(input())
answer = 'NO'
if( cups % 5 == 0):
cups_place = cups // 5
else:
cups_place = cups // 5 + 1
if( medals % 10 == 0):
medals_place = medals // 10
else:
medals_place = medals // 10 + 1
places = cups_... |
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 watermelon(n):
ct, count = 1, 0
while(ct < n):
if ct % 2 == 0 and ((n - ct) % 2) == 0:
count += 1
ct += 1
if count >= 1 :
return "YES"
else :
return "NO"
print(watermelon(int(input()))) |
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.
Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments com... | 3 | #!/usr/bin/python3
from itertools import product, combinations
def process(case):
regiment = map(rotate, homes, positions, case)
return sum(case) if is_square(regiment) else float('inf')
def is_square(regiment):
dists = list(map(lambda arg: dist_sq(*arg), combinations(regiment, 2)))
dists.sort()
... |
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.
Polar bears Alice and Bob each have caught some fish, and they are g... | 1 | '''
Created on 2013-5-2
URL : http://codeforces.com/contest/298/problem/D
@author: zhxfl
'''
n,m,k = map(int, raw_input().split());
x = map(int, raw_input().split());
y = map(int, raw_input().split());
if n>m:
print "YES"
else:
x.sort();y.sort();
yi = 0;
ans = "NO";
i = n - 1;
j = m - 1;
... |
Your friend Max has written a string S in your textbook. The string consists of lowercase latin letters. The problem is that Max is not good at writing at all! Especially, you never know if he wanted to write "w" or two consecutive "v". Given the string S, return the minimum and maximum length of a word which can be re... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
n=input();
stri=raw_input()
q1=stri.replace('w',"vv") # w->vv
mx=len(q1)
q2=q1.replace("vv",'w') # vv->w
mn=len(q2)
print mn,mx |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | a=input()
b=0
for i in a:
if(i != "4" and i!="7" and int(a)%4!=0 and int(a)%7!=0 and int(a)%47!=0 and int(a)%74 and int(i)%447!=0 and int(i)%444!=0 and int(i)%474!=0 and int(i)%777!=0 and int(i)%747!=0 and int(i)%774!=0 and int(i)%44!=0 and int(i)%77!=0):
print("NO")
b=1
break
if(b==0):
... |
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t... | 3 | import math
n=int(input())
t=list(map(int,input().split()))
maxl=0
add=0
for i in t:
maxl=max(maxl,i)
add+=i
print(max(math.ceil((add*2+1)/n),maxl))
|
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the mini... | 3 | s = input()
m = 10**18
for i in range(len(s)-2):
m = min(abs(int(s[i:i+3])-753), m)
print(m) |
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.
The shop sells N kinds of cakes.
Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.
Th... | 1 | N,M = map(int, raw_input().split())
x = [0]*N
y = [0]*N
z = [0]*N
for i in range(N):
x[i],y[i],z[i] = map(int, raw_input().split())
ans = -10000000000*N
for xs in [-1,1]:
for ys in [-1,1]:
for zs in [-1,1]:
T = []
for i in range(N):
T += [[x[i]*xs+y[i]*ys+z[i]*zs, x[i]*xs, y[i]*ys, z[i]*zs]... |
In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.
It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not cov... | 3 | a, b = map(int, input().split())
n = b-a
h = n*(n+1)//2-b
print(h) |
This is the hard version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: 2 ≤ k ≤ n.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in... | 3 | import sys
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input().rstrip()))
def inlt():
return(list(map(int,input().rstrip().split())))
def insr():
s = input().rstrip()
return(s[:len(s) - 1])
def invr():
return(map(int,input().rstr... |
Somnath is a Grammar Nazi. He keeps pointing out others’ grammatical mistakes. However, for a given sentence, he tries to remember all the unique words only so that he can be more efficient with his annoying habit. You wish to join his team to help him with his obsession for Queen’s Language. Given a sentence S, find t... | 1 | t = input();
while(t > 0):
print len(set(raw_input().split())); t -= 1; |
Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.
Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:
1. to orient each undirected edge in one of two possible directions to maximize... | 1 | '''input
6 6 3
2 2 6
1 4 5
2 3 4
1 4 1
1 3 1
2 2 3
'''
import sys
sys.setrecursionlimit(10000000)
from collections import deque
def readint():
return int(raw_input())
def readints():
return map(int, raw_input().split())
def readstr():
return raw_input()
def readstrs():
return raw_input().split()
... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | import sys
def main():
# sys.stdin = open("in.txt", "r")
t = int(input())
for x in range(t):
s = input()
n = len(s)
if (n <= 10):
print(s)
else:
print(s[0], end = '')
print(n - 2, end = '')
print(s[n - 1])
if __name__ == "__m... |
Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.
There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.
What is the minimum amount of money with which he can bu... | 3 | n, m = map(int, input().split())
x = [list(map(int, input().split())) for _ in range(n)]
x.sort()
s = 0
for a, b in x:
if m > b:
s += a * b
m += -b
else:
s += a * m
break
print(s) |
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please hel... | 3 | def power(base, exp):
res = 1
while(exp > 0):
if(exp%2 == 1):
res = res*base%10
base=base*base%10
exp//=2
return res
n = int(input())
print(power(8,n)) |
Recently Petya walked in the forest and found a magic stick.
Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:
1. If the chosen number a is even, then the spell will turn it into 3a/2;
2. If t... | 1 | n = int(raw_input())
for _ in xrange(n):
x, y = map(int, raw_input().split())
if x >= y or (x == 2 and y == 3):
print "YES"
continue
if x <= 3:
print "NO"
continue
print "YES"
|
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.
The city consists of n squares connected by n-1 roads in such a way that it is possible to reach any square from any other square. The square number 1 is the main square.
After Sunday walk all the roads were changed to one-way ro... | 3 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.wri... |
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 _ in range(int(input())):
# n = int(input())
# arr = list(map(int, input().split()))
n, k = map(int, input().split())
if n % 2 == 0 and k % 2 == 0:
arr = [1] * (k - 1) + [n - (k - 1)]
if min(arr) <= 0:
print('NO')
else:
print('YES')
print(*... |
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq... | 3 | n , k = map(int, input().split())
res = 0
while k % 2 == 0:
k /= 2
res += 1
print(res + 1) |
Problem
Given the integer n, output the smallest m such that nCm (the number of combinations that choose m out of n different ones) is even.
Constraints
The input satisfies the following conditions.
* 1 ≤ n ≤ 1018
Input
The input is given in the following format.
n
Output
Output the minimum m such that nCm i... | 3 | n = int(input())
print((n+1) &- (n+1)) |
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the numb... | 3 | n=int(input())
l=[int(i) for i in input().split()]
l1=[0]*1000
for i in range(n):
l1[l[i]-1]+=1
j=max(l1)
s=0
c=0
for i in range(1000):
if(l1[i]==j and c==0):
k=i
c=1
continue
else:
s+=l1[i]
if(l1[k]>=s+2):
print("NO")
else:
print("YES") |
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | 3 | import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
input = sys.stdin.readline
class Block:
# A - 0
# B - 1
letter: int
size: int
def __init__(self, letter, size):
self.letter = letter
self.size = size
AORD = ord('A')
T = int(input())
def add_block(b, letter, size):
i... |
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 | import sys
input = sys.stdin.readline
def fastio():
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue(... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n = int(input())
r = ""
for i in range(0, n):
s = input()
l = len(s)
if l > 10:
r += s[0] + str(l - 2) + s[l - 1] + "\n"
else:
r += s + "\n"
print(r) |
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 3 | number = int(input())
elem = []
a = input()
b = a.split(' ')
for i in range(number):
elem.append(int(b[i]))
elem.append(0)
m = 1
c = 1
for i in range(number):
if elem[i] < elem[i + 1]:
m += 1
if c < m:
c = m
else:
m = 1
print(c)
|
Given is a string S consisting of digits from `1` through `9`.
Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:
Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.
Constraints
* 1 ≤ |S| ≤ 200000
* S is a string c... | 3 | S = input()
cnt = [0]*2019
cnt[0] = 1
n = 0
t = 1
for i in reversed(S):
n += int(i)*t
n %= 2019
cnt[n] += 1
t *= 10
t %= 2019
print(sum(i*(i-1)//2 for i in cnt)) |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 1 | def lucky(x):
s=str(x)
for i in range(len(s)):
if s[i]=='4' or s[i]=='7':
continue
else:
return False
return True
def almost_lucky(x):
for i in range(4,x+1):
if x%i==0 and lucky(i):
return 'YES'
return 'NO'
n=int(raw_input())
print almost_lucky(n)
|
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 | import math
x = int(input())
for _ in range(x):
print(math.ceil(int(input())/2)-1)
|
Given a set of integers (it can contain equal elements).
You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).
Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:
* m... | 3 | t=int(input())
while t:
arr=[0]*102
t-=1
n=int(input())
l=list(map(int,input().split()))
for i in l:
arr[i]+=1
a=-1
b=-1
#print(l)
for i,v in enumerate(arr):
if v==1 and a==-1:
a=i
if v==0:
b=i
if a==-1:
a=i... |
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi... | 1 | str = raw_input()
isFindedOne = False
numberOfZero = 0
for c in str:
if isFindedOne:
if c == '0':
numberOfZero = numberOfZero + 1
else:
if c == '1':
isFindedOne = True
if numberOfZero >= 6:
print "yes"
else:
print "no"
|
"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=input().split()
n=int(x[0])
k=int(x[1])
lis=input().split()
lis2=lis[k-1:]
if lis[k-1]=="0":
rumber=lis.count("0")
if rumber==n:
add = 0
else:
add =len(lis)-rumber
else:
add=k-1+lis2.count(lis[k-1])
print(add) |
Rose loves to play games. This problem is about a game he recently played. In the game there are N locations, numbered 0 through N-1. Each location has one entrance and one exit. You are given an array aka A with N elements.For each i, A[i] describes the exit from location i. If A[i] is a number between 0 and N-1, incl... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n = int(raw_input())
for each in range(n):
size = int(raw_input())
arr = map(int, raw_input().strip().split())
c = int(size)
i = 0
flag = 0
while c >= 0:
# print "Entering while... |
After the huge success of Hero ISL this season our friend is planning to play in the next season. He already has a team which contains some good players but they not so good. He wants his team to qualify for the next season but the coach is worried as they don't have a good player.
Being a huge a fan of Lionel Messi h... | 1 | M=10**9+7
def power(a,b,M):
if b==0: return 1
if b==1: return a
halfn=power(a,b/2,M)
if(b%2==0):
return ( halfn * halfn ) % M;
else:
return ( ( ( halfn * halfn ) % M ) * a ) % M;
x=raw_input()
x=int(x)
for i in xrange(0,x):
a,b=raw_input().spl... |
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ... | 3 | import sys
input=sys.stdin.readline
t=int(input())
for i in range(t):
n=int(input())
grid=[[0,0]]
for i in range(n):
grid.append([int(i) for i in input().split()])
grid.sort()
#print(grid)
output=[]
ok=True
for i in range(1,len(grid)):
if (grid[i][0]-grid[i-1][0])>=0:
... |
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(" "))
sum=0
for i in range(1,w+1):
sum=sum+(k*i)
output=sum-n
if(output<0):
print(0)
else:
print(output)
|
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should... | 3 | """
http://codeforces.com/contest/433/problem/B
"""
def get_prefix_arr(array):
prefix_arr = []
for i in range(len(array)):
prefix_arr.append(array[i] if i == 0 else array[i] + prefix_arr[i - 1])
return prefix_arr
def sum_range(pre_arr, i, j):
if i == 0:
return pre_arr[j]
return p... |
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ... | 3 | temp = list(map(int, input().split()))
number_of_laterns = temp[0]
length_of_street = temp[1]
latern_locations = list(map(int, input().split()))
latern_locations = sorted(latern_locations)
#print(latern_locations)
radius = 0
temp_max = 0
final_max = 0
for element in range(len(latern_locations)-1):
temp_max... |
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | 3 | n=int(input())
l=list(map(int,input().split()))
odd=0
even=0
for i in range(len(l)):
if l[i]%2==0:
even+=1
else:
odd+=1
print(min(odd,even)) |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | import math
import sys
import collections
from collections import defaultdict
from sys import stdin, stdout
MOD = 10**9 + 7
def take_root(num):
return math.ceil(math.sqrt(num))
def sieve():
limit = 86028121
isprime=[1]*(86028122)
isprime[0]=0
isprime[1]=0
for i in range(2,take_root(limit+1)):... |
We have a grid with N rows and M columns of squares. Initially, all the squares are white.
There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attach... | 3 | N,M,K=map(int,input().split())
flag=False
for n in range(N+1):
for m in range(M+1):
if (N-n)*m+(M-m)*n==K:
flag=True
print("Yes" if flag else "No") |
Find the number of sequences of length K consisting of positive integers such that the product of any two adjacent elements is at most N, modulo 10^9+7.
Constraints
* 1\leq N\leq 10^9
* ~~1~~ 2\leq K\leq 100 (fixed at 21:33 JST)
* N and K are integers.
Input
Input is given from Standard Input in the following forma... | 3 | from math import sqrt
from itertools import accumulate
def inpl(): return list(map(int, input().split()))
MOD = 10**9 + 7
N, K = inpl()
p = 0
X = []
for i in range(1, int(sqrt(N))+1):
X.append(N//i)
A = [1]*len(X)
B = [X[-2-i] - X[-1-i] for i in range(len(X)-1)]
if sum(A) + sum(B) < N:
C = A + [N-sum(A)-su... |
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.
<image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1]
Polycarpus has bought a posh piano... | 1 | import sys
n,k=map(int,raw_input().split())
l=list(map(int,raw_input().split()))
if k==1:
print l.index(min(l))+1
sys.exit()
elif n==k:
print 1
sys.exit()
ans=sum(l[:k])
q=[ans]
a=0
b=k-1
while(1):
ans=ans-l[a]+l[b+1]
q.append(ans)
a+=1
b+=1
if a==n-k:
break
print q.i... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | x = list(map(int,input().split()))
s = input()
cost = 0
for i in s:
cost += x[int(i)-1]
print(cost) |
Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n × m cells and a robotic arm. Each cell of the field is a 1 × 1 square. The robotic arm has two lasers po... | 1 | T = input()
for t in xrange(T):
N, M, x1, y1, x2, y2 = (int(i) for i in raw_input().split())
up = min(y1, y2) - 1
down = M - max(y1, y2)
left = min(x1, x2) - 1
right = N - max(x1, x2)
res = M*N - 2*(up+down+1)*(left+right+1)
ret1 = (y1-up, x1-left, y1+down, x1+right)
ret2 = (y... |
Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first k Latin letters and not contain... | 3 | import sys, string
k = int(input())
pal = list(input().strip())
n = len(pal)
center = (n-1)//2
for i in range(center+1):
j = n-1-i
if pal[i] == pal[j]:
continue
if pal[i] == '?':
pal[i] = pal[j]
elif pal[j] == '?':
pal[j] = pal[i]
else:
print('IMPOSSIBLE')
sys.exit()
need = []
for ch in string.ascii_lett... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
flag=0
if(len(set(a))==1):
print("YES")
else:
a.sort()
for i in range(len(a)-1):
if(a[i+1]-a[i]>1):
flag=1
break
else:
pas... |
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 j in range(int(input())):
u = [0] * 2
j = input()
for i, v in enumerate(map(int, input().split())):
u[i & 1] += (i & 1) != (v & 1)
print(u[0] if u[0] == u[1] else -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 | line = input().split(" ")
size = int(line[0]) * int(line[1])
print(int(size/2) if size > 1 else 0) |
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.
As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.
It's guaranteed that the solution always exists. If ther... | 3 | # import sys
# sys.stdin = open("test.in","r")
# sys.stdout = open("test.out","w")
for i in range(int(input())):
print(1,int(input())-1) |
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice t... | 1 | import sys
import bisect
import heapq
def solve(L, cuts):
n = len(cuts)
sorted_cuts = [0] + sorted(cuts) + [L]
next_cut = [i + 1 for i in range(len(sorted_cuts))]
prev_cut = [i - 1 for i in range(len(sorted_cuts))]
max_cut = 0
for i in range(len(sorted_cuts) - 1):
diff = sorted_cut... |
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose t... | 3 | n=int(input())
l=input().split()
i=0
t=0
while(i<=n//2-1):
t=l[i]
l[i]=l[-(i+1)]
l[-(i+1)]=t
i=i+2
print(' '.join(l)) |
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose an... | 3 | n,m,k=map(int,input().split())
A=[]
for i in range(n):
A.append([0]*m)
dic=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0]]
C=[]
T=0
for item in range(k):
C.append(list(map(int,input().split())))
for u in C:
T+=1
i,j=u[0]-1,u[1]-1
A[i][j]=1
for d in range(3):
if i+dic[d][0]... |
Link to Russian translation the problem
You are given a number N. How many zeroes does N! end on?
Input
The first line contains one integer T - number of test cases.
The following T lines contain one integer each - N.
Output
For each test case output one integer per line - the answer for this question.
Constraints
... | 1 | def Count_Zeros(num):
ctr=0;
x=5;
while num/x > 0:
ctr+=num/x
x*=5
return ctr
def main():
t=input()
for i in xrange(t):
val=input()
print Count_Zeros(val)
if __name__ == '__main__' :
main() |
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 | s=input()
h=0
q=0
n=0
p=0
for i in s:
if i=='H':
h+=1
if i=='Q':
q+=1
if i=='9' :
n+=1
if i=='+' :
p+=1
if h>=1 or q>=1 or n>=1 :
print("YES")
else :
print("NO") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.