problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak... | 3 | n,k = [int(a) for a in input().split()]
wh = n // k
r = wh % 2
if r == 0:
print('NO')
else:
print('YES')
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
a = list(map(int, input().split()))
even = []
odd = []
for i in range(n):
if a[i]%2==0:
even.append(i+1)
else:
odd.append(i+1)
print(even[0]) if len(even) == 1 else print(odd[0]) |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | list1= []
n1 = int(input())
for i in range(n1):
list1.append(list(map(int,input().split())))
passengers = 0
min_capacity = []
for i in list1:
passengers -= i[0]
passengers += i[1]
min_capacity.append(passengers)
min_capacity.sort(reverse=True)
print(min_capacity[0])
|
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl... | 3 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 09:54:56 2018
@author: Nikita
"""
L, R, A = map(int, input().split())
if L <= R:
if A < R - L:
print(2 * (L + A))
else:
A -= (R - L)
print(2 * (R + A // 2))
else:
if A < L - R:
print(2 * (R + A))
else:
A -= (L - R)
print(2 * (L + A // 2... |
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | 3 | n=int(input())
x=list(map(int,input().split()))
a=0
s=0
for i in x:
if(i>a):
a=i
for i in x:
s=s+(a-i)
print(s)
|
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | 3 | n=int(input())
last=0
#purvikaurraina
for a in sorted(list(map(int,input().split()))):
if last>a:
n-=1
else:
last=max(last+1,a-1)
print(n)
|
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this w... | 3 | """
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for th... |
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ... | 3 | import math
r, x1, y1, x2, y2 = map(int, input().split())
l = math.sqrt((x2-x1)**2 + (y2-y1)**2)
if x1 == x2 and y1 == y2:
print(0)
else:
print(math.ceil(l / (2.0 * r)))
|
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 β€ n β€ 105) β size of the given array. The second line contains n ... | 3 | n = int(input())
arr = list(map(int, input().split()))
d = dict()
mn = min(arr)
prev = None
ans = float('inf')
for i in range(n):
if arr[i] == mn:
if not prev:
prev = i+1
else:
ans = min(ans, i - prev+1)
prev = i+1
if ans != float('inf'):
print(ans)
else:
... |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | from sys import stdin, stdout
import sys
INF=1e11
import bisect
def get_int(): return int(stdin.readline().strip())
def get_ints(): return map(int,stdin.readline().strip().split())
def get_array(): return list(map(int,stdin.readline().strip().split()))
def get_string(): return stdin.readline().strip()
def op(c): retur... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | import re
s = input()
s = re.sub("WUB", " ", s).strip()
print(s) |
Constraints
* All values in input are integers.
* 1\leq N, M\leq 12
* 1\leq X\leq 10^5
* 1\leq C_i \leq 10^5
* 0\leq A_{i, j} \leq 10^5
Input
Input is given from Standard Input in the following format:
N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{... | 3 | from itertools import combinations
n,m,x = map(int, input().split())
ca = [list(map(int, input().split())) for _ in range(n)]
ans = 10**9
for i in range(1, n+1):
for j in combinations(ca, i):
t = [0]*(m+1)
for k in j:
for l in range(m+1):
t[l] += k[l]
if all(t[a] >= x for a in range(1,m+1))... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | t=int(input())
for _ in range(t):
a,b=map(int,input().split())
c=abs(a-b)
if(c%10==0):
print(int(c/10))
else:
print(int(c/10)+1)
|
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 β€ t β€ 1000) β the ... | 3 | t=int(input())
for i in range(t):
n1,k1=input().split(" ")
n=int(n1)
k=int(k1)
if (k % (n-1)==0):
print(n*(k // (n-1))-1)
else:
print(n*(k // (n-1))+(k % (n-1))) |
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.
You are a new applicant for his company. Boboniu will test you with the following chess question:
Consider a nΓ m grid (rows are numbered from 1 to n, and columns are nu... | 3 | def cover(sx,sy):
x,y = sx,sy
while y!=1:
y -= 1
ans.append((x,y))
if sy!=m:
y = sy
while y!=m:
y += 1
ans.append((x,y))
return [x,y]
n,m,sx,sy = map(int,input().split())
x,y = sx,sy
ans = []
end = [sx+1,sy]
while len(ans)<n*m:
while end!=[1,1] and end!=[1,m]:
end[0] -= 1
ans.append(end)
end =... |
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid.
A 1-st order rhombus is just a square 1 Γ 1 (i.e just a cell).
A n-th order rhombus for all n β₯ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ... | 1 | n = int(raw_input())
res = 1
if n > 1:
res = (n-1)*2+1
x = 1
t = 0
for _ in range(n-1):
t += x
x += 2
res += 2*t
print res
|
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen... | 1 | mod = 100000000
dp=[[[0 for i in xrange(2)]for j in xrange(101) ]for k in xrange(101)]
n1,n2,k1,k2=map(int,raw_input().split())
for i in xrange(n1+1):
for j in xrange(n2+1):
if i ==0 and j==0:
dp[0][0][0]=1
dp[0][0][1]=1
else:
for k in xrange(1,min(i+1,k1+1)):
... |
Given an integer x, find 2 integers a and b such that:
* 1 β€ a,b β€ x
* b divides a (a is divisible by b).
* a β
b>x.
* a/b<x.
Input
The only line contains the integer x (1 β€ x β€ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | n = int(input())
if (n < 2):
print(-1)
else:
print(n, n) |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | money = int(input())
banknotes = {
100: 0,
20: 0,
10: 0,
5: 0,
1: 0
}
count = 0
for i in banknotes:
banknotes[i] = money // i
count += banknotes[i]
money %= i
print(count)
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | word = input()
rev=input()
if(rev==word[::-1]):
print("YES")
else:
print("NO") |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | # http://codeforces.com/problemset/problem/61/A
aStr = input()
length = len(aStr)
a = int(aStr, 2)
b = int(input(), 2)
print(format(a ^ b, f'0{length}b'))
|
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(""))
for i in range(n):
w = input("")
l = len(w)-2
print([w,w[0]+str(l)+w[-1]][l>8]) |
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'... | 1 | from math import ceil
n, m, a = map(float, raw_input().split())
ans = ceil(n/a) * ceil(m/a)
print(int(ans))
|
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 | def isevev(d):
return d % 2 == 0
t = int(input())
for i in range(t):
n = int(input())
li = [x for x in map(int,input().split())]
ew = 0
ow = 0
for i in range(0,n,2):
if isevev(li[i]) == False:
ew+=1
for i in range(1,n,2):
if isevev(li[i]) == True:
ow+=... |
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals.
The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them.
The positions of the strawberries are given to you as H \times W ch... | 3 | h, w, k = map(int, input().split())
s = [input() for _ in range(h)]
ans = [[0]*w for _ in range(h)]
num = 1
for i in range(h):
if "#" not in s[i]:
if i != 0:
ans[i] = ans[i-1]
continue
first = True
for j in range(w):
if s[i][j] == '#':
if first:
... |
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.
Limak, a polar bear, lives on the N... | 3 | if __name__ == '__main__':
n = int(input())
v = 0
f = True
for i in range(n):
t, d = str(input()).split()
t = int(t)
if d == 'South':
if v == 20000:
f = False
break
v += t
elif d == 'North':
if v == 0:
... |
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.
Initially S... | 3 | s=input()
i=0
for c in input(): i+=(s[i] == c)
print(i+1) |
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).
You are given a sequence a consisting of n integers.
You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the... | 3 | n=int(input())
a=map(int,input().split())
a=list(a)
l=0
r=n-1
ans=[]
la=0
while (l<=r):
if (a[l]<=la and a[r]<=la): break
if (l==r):
ans.append('L')
break
if (a[l]==a[r] and a[l]>la):
al=1
ar=1
ll=l+1
rr=r-1
while (ll<=r and a[ll]>a[ll-1]):
ll+=1
al+=1
while (rr>=l and a[rr]>a[rr+1]):
rr-=... |
There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.
Snuke will perform the following operation zero or more times:
* Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.
Find the number of possible final s... | 3 | MOD = 10 ** 9 + 7
n = int(input())
c = [int(input()) for _ in range(n)]
l = [c[0]]
for i in range(1, n):
if c[i] != c[i - 1]:
l.append(c[i])
n = len(l)
p = [-1] * (max(c) + 1)
q = [-1] * n
for i, x in enumerate(l[::-1]):
q[n - i - 1] = p[x]
p[x] = n - i - 1
dp = [0] * (n + 1)
dp[0] = 1
for i in rang... |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 |
def sol(a,n):
ans=[]
dd=a[0]
vstd=[0]
for i in range(1,n):
if a[i]!=dd:
ans.append([1,i+1])
vstd.append(i)
if len(ans)==0:
return -1
w=ans[0]
tm=w[1]-1
for i in range(n):
if (i not in vstd ) and a[i]!=a[tm]:
ans.append([w[1],i+1])
return ans
t=int(input())
while t:
n=int(input())
... |
You are given a string S of length 3 consisting of `a`, `b` and `c`. Determine if S can be obtained by permuting `abc`.
Constraints
* |S|=3
* S consists of `a`, `b` and `c`.
Input
Input is given from Standard Input in the following format:
S
Output
If S can be obtained by permuting `abc`, print `Yes`; otherwis... | 1 | import sys
words = list(raw_input().strip())
key = ['a', 'b', 'c']
if sorted(words) == key:
print("Yes")
else:
print("No") |
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | 3 | #!/usr/bin/env python3
'''
Author: andyli
Time: 2020-07-17 22:38:49
'''
import os
from io import BytesIO, IOBase
import sys
def main():
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
vis = [False for i in range(n)]
ans = []
for i in ran... |
You are given strings S and T consisting of lowercase English letters.
You can perform the following operation on S any number of times:
Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.
Determine if S and T can ... | 3 | from collections import Counter
s = Counter(input())
t = Counter(input())
s_n = sorted([x for x in s.values()])
t_n = sorted([x for x in t.values()])
print("Yes" if s_n==t_n else "No") |
There are three airports A, B and C, and flights between each pair of airports in both directions.
A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.
Consider a route where we start at one of th... | 3 | a,b,c=map(int,input().split());print(a+b+c-max(a,b,c)) |
Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.
A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with lengt... | 3 | # python3
def read_project_name():
name, version = input().split()
return (name, int(version))
def read_project():
project = read_project_name()
deps_size = int(input())
deps = [read_project_name() for __ in range(deps_size)]
return (project, deps)
def main():
dependencies = dict()
... |
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which
* two planks of length at least k+1 β the base of the ladder;
* k planks of length at least 1 β the steps of the ladder;
Note that neither the base planks, nor the steps planks are required to be equal.
For example... | 3 | # A. DIY Wooden Ladder
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=1)
k=min(a[:2])-1
print(min(k,n-2)) |
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.
Big Banban is hesitating over the amount ... | 3 | n=int(input())
if(n>36):
print(-1)
else:
print(*['8'*(n//2)+'9'*(n%2)]) |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | def findNumber(contestents,place):
minVal=contestents[place]
num=0
for x in contestents:
if x>=minVal and x>0 :
num+=1
else :
return num
return num
def main() :
n,k=map(int,input().split())
allcontestents=list(map(int,input().split()))
if n>=k:
number=findNumber(allcontestents,k-1)
else :
pri... |
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | 3 | n = int(input())
n = -1 * n if n < 0 else n
if n < 128:
print("byte")
elif 127 < n <= 32767:
print("short")
elif 32767 < n <= 2147483647:
print("int")
elif 2147483647 < n <= 9223372036854775807:
print("long")
else:
print("BigInteger") |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | n = int(input())
max = 0
x = 0
for i in range(n):
a,b = input().split()
a = int(a)
b = int(b)
x = x - a + b
if x>max: max = x
print(max) |
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis... | 3 | t=int(input())
for i in range(t):
n=int(input())
lst=[6,2,5,4,5,6,3,7,6]
s=''
if n%2==0:
s='1'*(n//2)
else:
s+='7'
s+='1'*((n//2)-1)
print(int(s)) |
Write a program which reads a list of student test scores and evaluates the performance for each student.
The test scores for a student include scores of the midterm examination m (out of 50), the final examination f (out of 50) and the makeup examination r (out of 100). If the student does not take the examination, t... | 3 | while True:
m,f,r = list(map(int, input().split()))
if (m == -1 and f == -1 and r == -1):
break
elif ((m == -1) or (f == -1)) or (m + f < 30):
print("F")
elif (80 <= m + f):
print("A")
elif (65 <= m + f) and (m + f < 80):
print("B")
elif (50 <= m + f) and (m + f < 65) or (50 <= r):
print("C")
elif (30 ... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | l=[0,0,0]
for i in range(int(input())):
a,b,c=map(int,input().split())
l[0]+=a
l[1]+=b
l[2]+=c
if l==[0,0,0]:print("YES")
else:print("NO") |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 1 | cache = {}
def solve(n, a, m, b):
a.sort()
b.sort()
return trial(n, a, m, b, 0, 0)
def trial(n, a, m, b, i, j):
if i >= n or j >= m: return 0
if (i, j) in cache: return cache[(i, j)]
if a[i]-b[j] > 1:
res = trial(n, a, m, b, i, j+1)
elif a[i]-b[j] < -1:
res = trial(n, a, m,... |
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 | x=input("")
x=x.split(" ");
for y in x:
y=int(y)
#print(y)
n=int(x[0])
m=int(x[1])
a=int(x[2])
count=0;
if n%a!=0:
q=n//a+1
elif(n%a==0):
q=n//a
if m%a!=0:
w=m//a+1
elif(m%a==0):
w=m//a
print(int(q*w)) |
Tanmay is a legendary spammer - everyone in the spamming world knows and admires his abilities to spam anyone, anytime, anywhere. He decided to guide one of his mentors, named Arjit, as part of the Apex body of spamming.
Tanmay has no doubts on his skills of teaching and making his mentor, Arjit, learn about the art ... | 1 | for i in range(input()):
n = input()
vals = sorted(list(map(int, raw_input().split())))
mx = vals[-1]
mn = vals[0]
neg = sorted(list(filter(lambda x: x < 0, vals)))
pos = sorted(list(filter(lambda x: x > 0, vals)))
v = None
for x in pos:
if v == None:
v = x
... |
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 i in range(k):
if n % 10 != 0:
n -= 1
else:
n = n // 10
print(n) |
N people are waiting in a single line in front of the Takahashi Store. The cash on hand of the i-th person from the front of the line is a positive integer A_i.
Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer P indicating its price, and shows this product... | 3 | n = int(input())
a = [int(input()) for _ in range(n)]
cnt = a[0] - 1
a[0] = 1
t = 1
for x in a:
if x == t: t += 1
if x < t: continue
if x%t == 0:
x -= t+1
cnt += 1
cnt += x//t
print(cnt) |
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, an... | 3 | def gcd(a,b):
while b:
a,b=b,a%b
return a
a,b,x,y= [int(x) for x in input().split()]
g=gcd(x,y)
x=x//g
y=y//g
print(min(a//x,b//y)) |
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second β... | 1 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 4 18:50:39 2017
@author: sai
"""
c,v0,v1,a,l=map(int,raw_input().split())
day=1
c=c-v0
while c>0:
if v0+day*a<=v1:
c=c-v0-day*a+l
else:
c=c-v1+l
day+=1
print day |
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`.
Constraints
* 2 β€ N β€ 200000
* 1 β€ A_i β€ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
If the elements... | 3 | n = int(input())
a = set(input().split())
if n-len(a):
print("NO")
else:
print("YES") |
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals.
The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them.
The positions of the strawberries are given to you as H \times W ch... | 3 | h, w, k = map(int, input().split())
cake = [input() for _ in range(h)]
cnt = 1
ans = [[0]*w for _ in range(h)]
for i in range(h):
cnt_berry = 0
for j in range(w):
if cake[i][j] == '#':
cnt_berry += 1
if 2 <= cnt_berry:
cnt += 1
ans[i][j] = cnt
if cnt... |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 1 | a = []
for i in range(3,1000):
x = (i-2)*180
if x%i == 0:
a.append(x/i)
t = input()
for _ in range(t):
n = input()
if n in a:
print "YES"
else:
print "NO" |
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be ... | 3 | n=int(input())
a=list(map(int,input().split()))
b=a[:]
b.sort()
for i in range(n//2):
c=a.index(b[i])
a[c]=-1
d=a.index(b[n-1-i])
a[d]=-1
print(c+1,d+1)
|
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 1 | n1, n2, k1, k2 = map(int, raw_input().strip().split())
if n1 > n2:
print "First"
else:
print "Second"
|
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
Find three indices i, j and k such that:
* 1 β€ i < j < k β€ n;
* p_i < p_j and p_j > p_k.
Or say that there are no such indices.
Input
The first lin... | 3 | from sys import stdin
input = stdin.readline
T = int(input())
for case in range(T):
n = int(input())
perm = [*map(int,input().split())]
flag=False
for i in range(1,n-1):
if perm[i-1]<perm[i] and perm[i]>perm[i+1]:
flag=True
break
if flag:
print('YES')
... |
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase... | 3 | s = input()
# print(s[:-1])
if len(s) != 26:
for c in range(ord('a'), ord('z')+1):
c = chr(c)
if not c in s:
print(s+c)
exit()
s = list(s)
t = []
while s:
for c in t:
if c > s[-1]:
print(''.join(s[:-1])+c)
exit()
t.append(s.pop())
prin... |
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.
Mike has n sweets with sizes a_1, a_2, β¦, a_n. All his sweets have different sizes. That is, there is no such pair ... | 3 | n=int(input())
l=[int(i) for i in input().split()]
l=sorted(l)
d=dict()
for i in range(len(l)-1):
for j in range(i+1,len(l)):
a=l[i]+l[j]
if a in d.keys():
d[a]=d[a]+1
else:
d[a]=1
print(max(d.values()))
|
Input Format
N K
a_1 a_2 a_3 ... a_N
Output Format
Print the minimum cost in one line. In the end put a line break.
Constraints
* 1 β€ K β€ N β€ 15
* 1 β€ a_i β€ 10^9
Scoring
Subtask 1 [120 points]
* N = K
Subtask 2 [90 points]
* N β€ 5
* a_i β€ 7
Subtask 3 [140 points]
* There are no additional constraint... | 3 | N,K = map(int,input().split())
A = list(map(int,input().split()))
res = float('inf')
for i in range(1<<N):
a = A[::]
paint = 0
cur = 0
add = 0
for j in range(N):
if (i>>j)&1:
paint += 1
if a[j] <= cur:
add += (cur+1) - a[j]
a[j] = cur+1
cur = max(cur, a[j])
else:
... |
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())
while n:
n-=1
s=input()
if(len(s)>10):
k=len(s)-2
s=s[0]+str(len(s)-2)+s[-1]
print(s) |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | n,k = list(map(int, input().split()))
odd = n//2
if n % 2 != 0:
odd += 1
if k <= odd:
ans = 1 + (k-1)*2
else:
k -= odd
ans = 2 + (k-1)*2
print(ans) |
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ... | 1 | import math
r, x, y, xp, yp = map(float, raw_input().split(" "))
def dist(x1, y1, x2, y2):
return math.sqrt((x1-x2)**2.0 + (y1 - y2)**2.0)
distance = dist(x, y, xp, yp)
steps = int(distance/(2.0*float(r)))
if abs(float(steps)*2.0*float(r) - distance) > 0.000001:
steps = steps + 1
print steps |
You are given n strings s_1, s_2, β¦, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | t = int(input())
while t:
t -= 1
n = int(input())
S = []
for i in range(0, n):
S += input()
cmap = {}
for si in S:
if cmap.get(si) is None:
cmap[si] = 1
else:
cmap[si] += 1
ans = True
for count in cmap.values():
if count%n:
... |
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it β
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1..... | 3 | import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sy... |
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and... | 3 | n = int(input())
a = list(map(int, input().split(' ')))
code, sport = [0]*n, [0]*n
for i in range(n):
code[i] = max(code[i], a[i]%2)
sport[i] = max(sport[i], a[i]//2)
for j in range(i+1, n):
if a[j]%2:
code[j] = max(code[j], sport[i] + 1)
if a[j]//2:
sport[j] = max(sp... |
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ... | 3 | n = int(input())
arr = [0] + list(map(int, input().split())) + [0]
m = int(input())
for i in range(m):
x, y = map(int, input().split())
arr[x-1] += y - 1
arr[x+1] += arr[x] - y
arr[x] = 0
print('\n'.join(map(str, arr[1:-1])))
|
After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number.
A token is placed in one of the cells. They take alternating turns of mo... | 3 | # -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 11/22/18
"""
import collections
N = int(input())
A = [int(x) for x in input().split()]
grev = collections.defaultdict(set)
g = collections.defaultdict(set)
degree = collections.defaultdict(int)
for i in range(N):
d = 0
for j in range(i+A[i], N, A[i... |
After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhantβs sentences, Yash determined a new cipher technique.
For a given sentence, the ciphe... | 3 | import sys
p = sys.stdin.read().split()
n, t = int(p[0]), p[1][::-1]
d = {q.lower(): q for q in p[3:]}
k, s = 0, []
l = sorted(set(map(len, d)))
while n:
k -= 1
if len(l) + k < 0: k, n = s.pop()
elif n >= l[k] and t[n - l[k]:n] in d:
s.append((k, n))
n -= l[k]
k = 0
print(*[d[t[n - l... |
Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:
* A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.
* Bob won some programming competition and got a 2x MB memory ... | 1 | n = int(raw_input())
dp = [-1] * 2001
best = 0
for i in xrange(n):
s, p = raw_input().split()
p = int(p)
if s[0] == 'w':
dp[p] = best
elif dp[p] != -1:
best = max(best,dp[p] + (1 << p))
print best
|
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k β₯ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | s = int(input(), 2)
ans = 0
k = 1
while k<s:
ans+=1
k*=4
print(ans)
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | rememberedColor = None
a = list(input())
t=0
fl = True
for i in range(len(a)):
if t>=7:
break
if a[i] == rememberedColor:
t+=1
if t>=7:
break
elif a[i] != rememberedColor:
t+=1
if t>=7:
break
t=0
rememberedColor = a[i]
while fl: ... |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly... | 3 | number_test_cases = int(input())
for _ in range(number_test_cases):
number_gifts = int(input())
candies = [int(n) for n in input().split()]
oranges = [int(n) for n in input().split()]
min_candies = min(candies)
min_oranges = min(oranges)
moves = 0
for n in range(number_gifts):
moves... |
You are given strings s and t, consisting of lowercase English letters. You will create a string s' by freely rearranging the characters in s. You will also create a string t' by freely rearranging the characters in t. Determine whether it is possible to satisfy s' < t' for the lexicographic order.
Constraints
* The ... | 3 | S = sorted(input())
N = sorted(input())
N.reverse()
print("Yes" if S < N else "No") |
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f... | 3 | def soma(n):
soma = 0
for i in range(1, n + 1):
soma += i
return soma
a = int(input())
b = int(input())
dist = abs(a - b)
paraCada = dist // 2
if dist % 2 == 0:
ans = soma(paraCada) * 2
else:
ans = soma(paraCada) + soma(paraCada + 1)
print(ans)
|
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ... | 3 | n,k=map(int,input().split())
a=list(map(int,input().split()))
vals=[]
for i in range(0,200001):
vals.append([])
for i in range(0,len(a)):
x=a[i]
curr=0
while (x>0):
vals[x].append(curr)
x=x//2
curr=curr+1
ans=1e9
for i in range(0,200001):
if (len(vals[i])>=k):
va... |
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 | input()
max_s = -1
min_s = 10001
counter = -2
for n in map(int, input().split()):
if n > max_s:
max_s = n
counter += 1
if n < min_s:
min_s = n
counter += 1
print(counter)
|
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | x = 0
for i in range(1,6):
arr = list(map(int,input().split()))
for j in range(0,5):
if(arr[j] == 1):
x, y = i , j+1
break
if(x != 0):
break
print(abs(x-3) + abs(y-3)) |
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch... | 3 | for u in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
out=[[]]
for i in range(n):
if(a[i]!=i+1):
out[-1].append(i)
else:
out.append([])
k=len(out)-out.count([])
if(k<=1):
print(k)
else:
print(2) |
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | 3 | string1 = list(map(int,input().split(':')))
string2 = list(map(int,input().split(':')))
#print(string1)
#print(string2)
time = 60*(string1[0]+string2[0]) + string2[1]+string1[1]
time //= 2
x1 = (time // 60)
if x1 < 10:
x1 = "0"+str(x1)
else:
x1 = str(x1)
x2 = (time%60)
if x2 < 10:
x2 = "0"+str(x2)
else:
... |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | def get_max_value():
a = int(input())
b = int(input())
c = int(input())
numbers = [a, b, c]
max_val = get_max(numbers)
return max_val
def get_max(numbers):
if len(numbers) == 0:
return 0
ls = list()
indexes = list([0])
indexes.append(len(numbers) - 1)
for i in index... |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ... | 3 | #codeforces_977B_live
n = int(input())
line = input()
occ = {}
for k in range(n-1):
temp = line[k:k+2]
occ[temp] = 0
for j in range(n-1):
if line[j:j+2] == temp:
occ[temp] += 1
#print(occ)
ma = line[0:2]
for e in occ:
if occ[e] > occ[ma]:
ma = e
print(ma) |
You are given a string S as input. This represents a valid date in the year 2019 in the `yyyy/mm/dd` format. (For example, April 30, 2019 is represented as `2019/04/30`.)
Write a program that prints `Heisei` if the date represented by S is not later than April 30, 2019, and prints `TBD` otherwise.
Constraints
* S is... | 3 | print('TBD'if int(input().split('/')[1])>4 else 'Heisei') |
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | t = int(input())
for i in range(t):
h, m = (int(i) for i in input().split())
print(1440 - (60 * h + m)) |
Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: `a`, `e`, `i`, `o` and `u`.
Constraints
* c is a lowercase English letter.
Input
The input is given from Standard Input in the following format:
c
Output
If c is a vowel, print `vowel`. Oth... | 3 | c=str(input())
if c in "aiueo":
print("vowel")
else:
print("consonant") |
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 | num = input()
lucky = []
for i in range(int(num)+1):
if '4' in str(i) or '7' in str(i):
if '0' in str(i) or '1' in str(i) or '2' in str(i) or '3' in str(i) or '5' in str(i) or '6' in str(i) or '8' in str(i) or '9' in str(i):
continue
else:
lucky.append(i)
nearly_lucky = []
for elements in lucky:
... |
Pasha has two hamsters: Arthur and Alexander. Pasha put n apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamste... | 3 | class CodeforcesTask421ASolution:
def __init__(self):
self.result = ''
self.n_a_b = []
self.a = []
self.b = []
def read_input(self):
self.n_a_b = [int(x) for x in input().split(" ")]
self.a = [int(x) for x in input().split(" ")]
self.b = [int(x) for x in ... |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 1 | #!/usr/bin/python2
from sys import stdin
i = int(stdin.readline())
l = []
n = 0
m = 1
while n <= 10**9:
l.append(n)
t = n + m
n = m
m = t
if i == 1:
print "1 0 0"
elif i == 2:
print "1 1 0"
elif i == 0:
print "0 0 0"
else:
print l[l.index(i) - 1], l[l.index(i) - 3], l[l.index(i) - 4]... |
You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.
In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 β€ a β€ b < x β€ y β€ |s| and substrings s[a... b], s[x... y] are palindromes.
A pal... | 3 | """
Author - Satwik Tiwari .
4th Oct , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import Bytes... |
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.
To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the follo... | 3 | n=int(input())
print((n+1)*3+1)
c=0
for i in range(n+1):
print(i,i)
print(i+1,i)
print(i,i+1)
c=i
print(i+1,i+1) |
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 = list(input())
if s[0].isupper():
print("".join(s))
else:
s[0] = chr(ord(s[0])-32)
print("".join(s)) |
Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.
Input
The first line contains two integers n and k (2 β€ n β€ 100000, 1 β€ k β€ 20).
Output
If it's impossible to find the representation of n as a product of k... | 3 | from collections import defaultdict
def isPrime(N):
return (False if any([not N % i for i in range(2, N)]) else True)
MyDict, X , Number = defaultdict(int) , list(map(int, input().split())), 2
if X[1] == 1:
print(X[0])
exit()
while X[0] != 1:
if isPrime(Number):
while X[0] % Number == 0:
... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 1 | import sys
has = sys.stdin.readline().strip()
choices = [int(h) for h in (has, has[:-1], has[:-2] + has[-1])]
print max(choices)
|
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en... | 1 | from math import *
from Queue import *
from sys import *
from random import *
def is_bad(s):
res = False
if s[0] != '1':
res = True
if len(s) > 1 and int(s[1:]) != 0:
res = True
return res
n = int(raw_input())
a = raw_input().split()
if '0' in a:
print 0
exit(0)
s = 0
bad = ... |
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | 3 | t = int(input())
for i in range(t):
n = int(input())
print('YES' if n % 4 == 0 else 'NO')
|
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())
k=0
while n%3==0:
if n%2:
n*=2
k+=1
n//=6
k+=1
if n!=1:
k=-1
print(k)
|
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 β€ x,y,z β€ n), a_{x}+a_{y} β a_{z} (not necessarily distinct).
You are given one integer ... | 3 | l=int(input())
for i in range(l):
n=int(input())
for i in range(n):
print("1 ",end="")
print() |
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 | def transform(word):
return ('{}{}{}'.format(word[0], len(word)-2, word[-1])
if len(word) > 10
else word)
def main():
n = int(input())
for _ in range(n):
print(transform(input()))
main()
|
Codeforces user' handle color depends on his rating β it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color of hi... | 3 | from sys import exit
n = int(input())
for _ in range(n):
s, a, b = input().split()
a = int(a)
b = int(b)
if a >= 2400 and a < b:
print('YES')
exit(0)
print('NO')
|
Snuke loves working out. He is now exercising N times.
Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.
Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.
Constraints
* 1 β€ N β€ 10... | 3 | import math
N = int(input())
p = math.factorial(N)
print(int(p%(10**9+7))) |
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai β€ bi).
Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
Input
The first line of the input contains one integer n (2 β€ n β€ 100 000) β number of cola... | 3 | def main():
_ = input()
l = (int(i) for i in input().split(' '))
s = [int(i) for i in input().split(' ')]
s.sort()
print('YES' if (sum(s[-2:])>=sum(l)) else 'NO')
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.