problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a, b = map(int, input().split())
i=0;
while True:
a=a*3;
b=b*2;
i=i+1;
if (a>b):
break;
print(i); |
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 | input = int(input())
if input%2 == 0:
if input!= 2:
print("YES")
else:
print("NO")
else:
print("NO") |
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 | def ans(n,nums):
e1 = 0
e2 = 0
o1 = 0
o2 = 0
for i in range(0,n):
if(nums[i]%2==0):
e1 = i
e2+=1
elif(nums[i]%2!=0):
o1 = i
o2+=1
if(e2==1):
return e1+1
return o1+1
n = int(input())
nums = list(map(int,input().split... |
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ... | 3 | import math
a,b=map(int,input().split())
c=list(map(int,input().split()))
d,j=0,0
for i in range(len(c)):
e= math.ceil(c[i]/b)
if e>=d:
d=e
j=i
print(j+1)
|
Boboniu gives you
* r red balls,
* g green balls,
* b blue balls,
* w white balls.
He allows you to do the following operation as many times as you want:
* Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the b... | 3 | n = int(input())
for i in range(n):
r, g, b, w = map(int, input().split())
f = 0
if (r*g*b == 0):
f = 1
r = r % 4
g = g % 4
b = b % 4
w = w % 4
if ((((r*r + g*g + b*b + w*w - 2) % 4) == 0) or (f == 1 and (((r*r + g*g + b*b + w*w) % 4) >= 2))):
print('No')
else:
... |
You came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface.
The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m.
There is a camera on the cei... | 1 | '''input
5 6
3 3 3 3 3
'''
from collections import defaultdict as df
from bisect import bisect_left as bl
import sys
n,m=[int(x) for x in raw_input().split()]
A=[int(x) for x in raw_input().split()]
A=sorted(A)
cur = 0
le=0
cubes=0
for i in range(n-1):
if A[i]>=1:
le+=1
if A[i]>cur:
cur+=1
#print cur,l... |
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
... | 3 | import math
a = [int(input()) for i in range(11)][::-1]
for i in a:
p = i ** 3 * 5 + math.sqrt(abs(i))
if p >= 400.:
print("f({}) = MAGNA NIMIS!".format(i))
else:
print("f({}) = {:.2f}".format(i, p))
|
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas... | 3 | x=input()
B=0
u=0
l=0
b=0
a=0
s=0
r=0
for i in x:
if i == "B":
B+=1
elif i == "u":
u+=1
elif i == "l":
l+=1
elif i == "b":
b+=1
elif i == "a":
a+=1
elif i == "s":
s+=1
elif i == "r":
r+=1
# Bulbasaur
pokemons=0
while B>=1 and u>=2 and l... |
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:
* No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t... | 3 | q = int(input())
for i in range(q):
n = int(input())
a = list(map(int, input().split()))
a.sort()
ans = 1
for j in range(1, n):
if a[j] - a[j - 1] == 1:
ans = 2
break
print(ans)
|
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger tha... | 1 | #br = open('c.in')
f = lambda: map(int, raw_input().strip().split())
a = [[0, 2]]
n = f()[0]
a.extend([[i, 0] for i in f()])
m = f()[0]
a.extend([[i, 1] for i in f()])
a = sorted(a, key = lambda x: x[0])
a.append([max(v[0] for v in a) + 1, 2])
def solve(q=None):
c, i, N, dif, r, ma = [0, 0], len(a) - 1, len(a), -1e1... |
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.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | n = input()
numln = n.count('4')+n.count('7')
numln = str(numln)
if numln.count('4')+numln.count('7')==len(numln): print("YES")
else: print("NO") |
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 | x = int(input())
y = [""] * 100
y[0] = "I hate "
for i in range(1, x):
if i % 2 == 0:
y[i] = "that I hate "
elif i % 2 == 1:
y[i] = "that I love "
z = ""
for i in range(x):
z += y[i]
print(z + "it")
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 3 | a='qwertyuiopasdfghjkl;zxcvbnm,./'
i=input
d=1-(i()>'L')*2
for c in i():
print(a[a.find(c)+d],end='') |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | # -*- coding: utf-8 -*-
"""
@author: c_py
"""
import sys
if __name__ == "__main__":
for _ in range(int(input())):
N = int(input())
if ((N//2)%2==1):
print("NO")
else:
print("YES")
for i in range(1,(N//2)+1):
print(2*i,end=" ")
... |
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t... | 3 | import math
a=int(input())
for i in range(0,a):
b=int(input())
arr=list(map(int,input().split()))
arr.sort()
c=1
for i in range(0,len(arr)):
if(i+1>=arr[i]):
c=i+2
if(c==1):
print(1)
else:
print(c)
|
You are given three integers A, B and C. Determine whether C is not less than A and not greater than B.
Constraints
* -100β€A,B,Cβ€100
* A, B and C are all integers.
Input
Input is given from Standard Input in the following format:
A B C
Output
If the condition is satisfied, print `Yes`; otherwise, print `No`.
... | 3 | a,b,c=map(int,input().split());print("Yes" if c>=a and c<=b else "No") |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | for _ in range(int(input())):
n, m = map(int, input().split())
total_square = n*m
lights = total_square//2
lights += total_square%2
print(lights) |
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participan... | 3 | for _ in range(int(input())):
n = int(input())
r = bin(n).replace("0b","").count('1')
k = 2*n-r
print(k) |
AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):
* She chooses two indices i and j (1 β€ i, j β€ n), then decreases the i-th element ... | 3 | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
arr=[0]*n
pos,neg=[],[]
for i in range(n):
if a[i]==b[i]:
arr[i]=0
else:
arr[i]=b[i]-a[i]
if arr[i]>0:
pos.extend([i+... |
You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it.
You can perform the following operation any number of times (possibly zero):
* Choose any two adjacent cells and multiply the values in them b... | 3 | for _ in range(int(input())):
n, m = map(int, input().split())
lst = [list(map(int, input().split())) for _ in range(n)]
tot = 0
zer = 0
for i in lst:
if 0 in i:
zer = 1
break
if zer == 1:
for i in lst:
for e in i:
tot += abs(e)
print(tot)
else:
minv = abs(lst[0][0])
ans = []
tot = 0
... |
You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
Input
The first line contains two integers n and m (1 β€ n, m β€ 9) β the length... | 3 | a, b = map(int, input().split())
c = input().split()
d = input().split()
res1 = [0] * 10
res2 = [0] * 10
for i in range (a):
res1[int(c[i])] = 1
for i in range (b):
res2[int(d[i])] = 1
for i in range (10):
if res1[i] == res2[i] and res1[i] == 1:
print(i)
exit(0)
min1 = 9
for i in range (a)... |
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q... | 3 | n,ice=map(int,input().split())
sad=0
for i in range(n):
s,x=input().split()
x=int(x)
if s=='+':
ice+=x
else:
if ice<x:
sad+=1
else:
ice-=x
print(ice,sad)
|
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 | import math
for _ in range(int(input())):
a,b=map(int,input().split())
x=a
y=b
while(True):
if a%2==0:
a//=2
if b%2==0:
b//=2
if a%2!=0 and b%2!=0:
break
#print(a,b)
if a!=b:
prin... |
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j β i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
print(*sorted(a, reverse=True)) |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | s = input().lower()
b = []
for i in range (len(s)):
if s[i] not in ("o","y","i","u","a","e") :
b.append("." + s[i])
print( ''.join(b)) |
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
import math
inp = sys.stdin.read()
lines = inp.splitlines()
a = list(map(int, lines[0].split()))
b = list(map(int, lines[1].split()))
n = int(lines[2])
cups = sum(a)
medals = sum(b)
if math.ceil(cups/5) + math.ceil(medals/10) > n:
print("NO")
else:
print("YES")
|
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 | n=int(input())
s=input()
rs=''
i=Count=0
while i<n:
rs+=s[i]
Count+=1
i+=Count
print(rs) |
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem... | 3 | m,k = [int(x) for x in input().split()]
n = m
if m%2 == 1:n-=1
if m == 1:
if k == 0:print(1)
else : print(-1)
elif k < n//2 : print(-1)
else:
x = k - (n//2 - 1)
ans = [str(x),str(2*x)]
i = 1
while len(ans) < m:
if i not in [x,2*x]:ans.append(str(i))
i+=1
print(' ... |
You have array a1, a2, ..., an. Segment [l, r] (1 β€ l β€ r β€ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 β€ i β€ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).
Your task is to find a ... | 1 | I=lambda:map(int, raw_input().split())
n = input()
a = I()
if n <= 2: print n;exit()
cnt, ans = 2, 0
for i in xrange(2, n):
if a[i] == a[i-1] + a[i-2]: cnt += 1
else: cnt = 2
ans = max(ans, cnt)
print ans
|
There is a plane like Figure 1 with 8 vertical and 8 horizontal squares. There are several bombs on that plane. Figure 2 shows an example (β = bomb).
| β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘
--- | --- | --- | --- | --- | --- | --- | ---
β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘
β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘
β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘ | β‘
β‘... | 3 | def dfs_bomb(A,x,y):
X = [ 1, 0,-1, 0, 2, 0,-2, 0, 3, 0,-3, 0]
Y = [ 0, 1, 0,-1, 0, 2, 0,-2, 0, 3, 0,-3]
A[x][y] = "0"
for i in range(12):
xx = x + X[i]
yy = y + Y[i]
if 0 <= xx < 8 and 0 <= yy < 8:
if A[xx][yy] == "1":
dfs_bomb(A,xx,yy)
if __name__ == '__main__':
cnt = int(input())
for i in r... |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 |
a,b,c,d=map(int,input(' ').split(' '))
s=0
s=max(a,max(b,max(c,d)))
m=s-a
n=s-b
p=s-c
q=s-d
if m==0:
print('%s %s %s' %(n,p,q))
elif n==0:
print('%s %s %s'%(m,p,q))
elif p==0:
print('%s %s %s'%(m,n,q))
else:
print('%s %s %s' %(m, n, p))
|
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 | m,n,a = map(int,raw_input().split(" "))
#a = int(raw_input("Enter the size of the square"))
def squares(length, width, square):
nl = 0
nw = 0
if length % square == 0:
nl = length//square
else:
nl = length//square + 1
if width % square == 0:
nw = width//square
else:
... |
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 β
n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | 3 | import math
for _ in range(int(input())):
n=int(input())
if n==2:
print('%.9f' %1)
else:
a=360/(n*4)
#print(a)
ar=(a*math.pi)/180
#b=0.5/(math.sin(ar))
b=0.5/math.tan(ar)
print('%0.9f' %(2*b))
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | b=[]
c=0
a = int(input())
for i in range(0,a) :
b.append(str(input()))
if b[i] == "Tetrahedron":
c=c+(4)
if b[i] == "Cube":
c=c+(6)
if b[i] == "Octahedron":
c=c+(8)
if b[i] == "Dodecahedron":
c=c+(12)
if b[i] == "Icosahedron":
c=c+(20)
print(c) |
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,... | 1 | from sys import stdin,stdout,setrecursionlimit,maxint,exit
#setrecursionlimit(2*10**5)
def listInput():
return map(long,stdin.readline().split())
def printBS(li):
for i in xrange(len(li)-1):
stdout.write("%d "%li[i])
stdout.write("%d\n"%li[-1])
def sin():
return stdin.readline().rstrip()
MOD=10**9+9
n,m,k=listInp... |
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 collections import defaultdict as dd
import math
import sys
input=sys.stdin.readline
def nn():
return int(input())
def li():
return list(input())
def mi():
return map(int, input().split())
def lm():
return list(map(int, input().split()))
q=nn()
for _ in range(q):
n = nn()
s = input()
z=0
o=n-1
an... |
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | 3 | n = int(input())
t = list(map(int,input().split()))
if n == 1 and t[0] != 0 and t[0] != 15:
print(-1)
elif t[n-1] == 15:
print('DOWN')
elif t[n-1] == 0:
print("UP")
elif t[n-1] > t[n-2]:
print("UP")
else:
print("DOWN")
|
We have N bricks arranged in a row from left to right.
The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.
Among them, you can break at most N-1 bricks of your choice.
Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of t... | 1 | N = input()
a = map(int, raw_input().split())
t = 0
for i in range(N):
if a[i]==t+1:
t += 1
print N-t if t>0 else -1
|
You are given nonnegative integers a and b (a β€ b), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x?
Constraints
* 0 β€ a β€ b β€ 10^{18}
* 1 β€ x β€ 10^{18}
Input
The input is given from Standard Input in the following format:
a b x
Output
Print the number of th... | 1 | ini=map(int, raw_input().split())
if ini[0]%ini[2]==0:
print ini[1]/ini[2]-ini[0]/ini[2]+1
else:
print ini[1]/ini[2]-ini[0]/ini[2] |
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!
More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw... | 1 | mod=10**9+7
#import resource
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.stack_size(2**27)
import sys
#sys.setrecursionlimit(10**6)
#fact=[1]
#for i in range(1,100001):
# fact.append((fact[-1]*i)%mod)
#ifact=[0]*100001
#ifact[100000]=pow(fact[100000]... |
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
z = set(list(x[1:]) + list(y[1:]))
if z == set(range(1, n + 1)):
print("I become the guy.")
else:
print("Oh, my keyboard!") |
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 β€ i β€ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the b... | 1 | n, m = map(int, raw_input().split())
lst = map(int, raw_input().split())
ans = 0
for i in range(0, n - 1):
ans = max(ans, lst[i] - lst[i + 1] - m)
print ans |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | # CodeForces task 118A
# Andrey Pompeev 20.06.2017
forbidden_letters = ("a", "o", "y", "e", "u", "i")
string = input().lower()
result_string = ''
for i in string:
if i in forbidden_letters:
pass
else:
result_string += ('.' + i)
print(result_string)
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 1 | shoes = map(int,raw_input().split())
ans=0
for i in set(shoes):
ans += shoes.count(i)-1
print ans |
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.
Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print `Yes`; if it cannot, print `No`.
Constraints
* 1 \leq N \leq 100
* N is an int... | 3 | n=int(input())
ans="No"
for i in range(1,10):
if(n/i==n//i and n//i<10):
ans="Yes"
print(ans) |
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 | days = input()
offices = input()
current = offices[0]
f_to_s=s_to_f=0
for _ in offices[1:]:
if current == 'F' and _ == 'S':
f_to_s +=1
elif current == 'S' and _ == 'F':
s_to_f += 1
current = _
if s_to_f > f_to_s :
print('YES')
else: print('NO')
# print(days)
# print(offices)
|
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... | 1 | from __future__ import division
n = raw_input().split()
l = []
for i in range(len(n)):
l.append(int(n[i]))
h = l[0] * l[1]
j = int(h/2)
print(j)
|
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
string = input()
pattern = r'(WUB)+'
string = re.sub(pattern, ' ', string)
string = string.strip()
print(string) |
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al... | 3 | (x1, y1, x2, y2) = [int(x) for x in input().split()]
xmin = min(x1, x2)
xmax = max(x1, x2)
ymin = min(y1, y2)
ymax = max(y1, y2)
if xmin == xmax and ymin == ymax:
print(-1)
elif xmin == xmax:
a = ymax - ymin
print(xmin + a, ymin, xmin + a, ymax)
elif ymin == ymax:
a = xmax - xmin
print(xmin, ymin + a, xmax, ymin ... |
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w... | 3 | t=int(input())
for ii in range(t):
n,k=[int(i) for i in input().split()]
s=list(input())
a=0
b=0
flag=True
for i in range(n-k):
if s[i]!='?' and s[i+k]=='?':
s[i+k]=s[i]
for i in range(k):
if s[i]=='0':a+=1
else:
if s[i]=='1':b+=1
if a>(k//2) ... |
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... | 1 | w = int(input())
if w<=2:
print("NO")
elif w%2 == 0:
print("YES")
else:
print("NO") |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 1 | t=raw_input()
vowels=['a','e','i','o','u','A','E','I','O','U','y','Y']
l=[]
for i in range(len(t)):
if t[i] not in vowels:
if ((t[i].isupper())):
l.append(t[i].lower())
continue;
l.append(t[i])
s=""
q=[]
for i in range(len(l)):
q.appe... |
Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key
Note... | 3 | n=int(input())
a=list(map(int,input().split()))
print(*a)
for i in range(1,n):
num=a[i]
j=i-1
while j>=0 and a[j]>num:
a[j+1]=a[j]
j-=1
a[j+1]=num
print(*a)
|
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ... | 3 | n,m=map(int,input().split())
if m>=n-1 and m<= 2*(n+1):
m-=n-1
if(m==0):
print("0"+"10"*(n-1))
elif(m<=n+1):
print("110"*(m-1)+"10"*(n-m+1))
else:
print("110"*n + "1"*(m-n-1))
else:
print(-1)
|
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa... | 3 | t = int(input())
for i in range(t):
n,k = [int(i) for i in input().split()]
l = [int(i) for i in input().split()]
if set(l) == {0}:
print(0)
else:
z = sorted(l)
z.reverse()
s = z[0]
for i in range(1,k+1):
s = s + z[i]
print(s)
... |
A programming competition site AtCode provides algorithmic problems. Each problem is allocated a score based on its difficulty. Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points. These p_1 + β¦ + p_D problems are all of the problems available on AtCode.
A user... | 3 | import sys
def f(g, d, P, C):
if d <= 0:
return float('inf')
n = min(g//(100*d), P[d-1])
s = 100*d*n
if n == P[d-1]:
s += C[d-1]
if g > s:
n += f(g-s, d-1, P, C)
return min(n, f(g, d-1, P, C))
def main():
input = sys.stdin.readline
D, G = map(int, input().split())
P = []
C... |
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 | a, b = [int(x) for x in input().split()]
c = 2
res = (a * b) // 2
print (res) |
Foo was not amongst the most brilliant students of his class. So, he has some pending exams to clear. As the exams are approaching, this time he vowed to pass in all of them. This will only happen if he is not under stress. Foo's stress can be calculated using a simple function called Foo_function which depends upon th... | 1 | t=int(raw_input())
def calc(x):
global a
s=0
for i in xrange(3,-1,-1):
s+=(x**i)*a[3-i]
return s
def b_s(a,high):
low=0
#high=10**6
mid=(high+low)//2
#t=False
while low<=high:
#print mid
jk=calc(mid)
jkl=calc(mid+1)
if jk<=a[-1] and jkl>a[-1]:
... |
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps... | 3 | from sys import stdin as fin
# fin = open("ecr6a.in", "r")
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
sx, sy = abs(x1 - x2), abs(y1 - y2)
print(min(sx, sy) + abs(sx - sy)) |
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.
Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance... | 3 | n = int(input().strip()) - 1
arr = list(map(int, input().strip().split(" ")))
big = arr.index(max(arr))
little = arr.index(min(arr))
distance = max([abs(big),abs(n-big),abs(little),abs(n-little)])
print(distance)
|
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec... | 3 | import re
input()
print(re.sub('(?<=[aeiouy])[aeiouy]+', '', input())) |
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 |
num = int(input())
if(num<=2):
print("NO")
elif(num%2==0):
print("YES")
else:
print("NO") |
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.
Everybody knows that the Wo... | 3 | n = int(input())
ranges_map = {}
keys_list = list()
for _ in range(n):
a, b = list(map(int, input().split()))
keys_list.append(a)
ranges_map[a] = b
keys_list.sort()
res = 0
cur_max = ranges_map[keys_list[0]]
for i in range(n):
if (cur_max > ranges_map[keys_list[i]]):
res += 1
else:
cur_max = ranges_map[... |
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | t = int(input())
for test in range(t):
n = int(input())
seq = list(input())
ans,k = 0,0
for br in seq:
if br=='(':
ans+=1
elif ans>0:
ans-=1
else:
k+=1
print(k)
|
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 β€ l_i β€ r_i β€ m) β coordinates of the left and of the right endpoints.
Consider... | 3 | I=lambda:map(int,input().split())
n,m=I()
ar=[i for i in range(1,m+1)]
for i in range(n):
a,b=I()
for _ in range(a,b+1):
try:
ar.remove(_)
except:continue
print(len(ar))
print(*ar) |
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ
m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each... | 3 | k = int(input())
n = -1
m = -1
s = "aoeiu" * 2000
res = ""
for i in range(5, k):
if k % i == 0:
n = k // i
m = k // n
break
if n < 5 or m < 5:
print(-1)
else:
for i in range(n):
res += s[i: i + m]
print(res)
|
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | a=int(input())
for i in range(a):
b,c=map(int,input().split())
if(b<=2):
print("1")
else:
print((b-3)//c+2) |
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ... | 3 | import heapq
n, m = map(int, input().split())
s = [set() for i in range(n)]
ans = []
used = [False] * n
for i in range(m):
fro, to = map(int, input().split())
fro -= 1
to -= 1
s[fro].add(to)
s[to].add(fro)
ss = []
heapq.heappush(ss, 0)
used[0] = True
while len(ss) > 0:
v = heapq.heappop(ss)
... |
You are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0.
You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 Γ 2, and replace every element in the chosen sub... | 3 | from collections import defaultdict as dc
import sys
import math
def inp():
p=sys.stdin.readline()
return p
n,m=list(map(int,inp().split()))
p=[]
for _ in range(n):
q=list(map(int,inp().split()))
p.append(q)
q=[[0 for i in range(m)] for i in range(n)]
r=[]
for i in range(n-1):
for j in range(m-1):
... |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | 3 | n=int(input())
for i in range(n):
a=sorted(list(map(int,input().split())))
if(len(set(a))==1):
print(0)
elif(len(set(a))==2):
if(max(a)-min(a)>=2):
print((max(a)-min(a))*2-4)
else:
print((max(a)-min(a))*2-2)
else:
print(a[1]-a[0] + a[2]-a[1] + a[2]-a[0]-4) |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | n = int(input())
lst = list(map(int,input().split()))
for element in lst:
print(element - (element%2==0),end=' ') |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | a=int(input())
b=list(input())
c=[]
for i in range(len(b)):
if(i==0):
c.append(b[i])
else:
if((b[i] is c[len(c)-1])==False):
c.append(b[i])
print(len(b)-len(c)) |
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.
One day Petya was delivered a string s, containing only digits. He needs to find a string that
* ... | 1 | s = raw_input()
fours = s.count('4')
sevens = s.count('7')
if fours == 0 and sevens == 0:
print -1
else:
if fours >= sevens:
print 4
else:
print 7
|
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 β€ i β€ j β€ n) and flips all values ak for which their positions are in range [i, j] (that is i β€ k β€ j)... | 3 | global dp, arr
dp = [[-101 for i in range(100)] for j in range(100)]
def delta(i,j):
global arr, dp
if (dp[i][j]!=-101): return dp[i][j]
dp[i][j] = j-i+1-2*arr[i:(j+1)].count(1)
return dp[i][j]
n = int(input())
arr = list(map(lambda i:int(i) ,input().split()))
maxchange = delta(0,0)
for i in range(0,n):
for j in... |
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter β its complexity. The complexity of the i-th chore equals hi.
As Petya is older, he wants to take the chores with complexity larger... | 3 | from sys import stdin, stdout
n, a, b = map(int, stdin.readline().split())
values = sorted(list(map(int, stdin.readline().split())))
stdout.write(str(values[b] - values[b - 1])) |
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive.
Input
Input contains one integer number n (1 β€ n β€ 3000).
Output
Output the amount ... | 3 | import math
n = int(input().strip())
is_prime = [False, False] + [True] * (n - 1)
prime_list = list()
almost_prime = list()
for i in range(n + 1):
if is_prime[i]:
prime_list.append(i)
for j in range(i * 2, n + 1, i):
is_prime[j] = False
def find_factors(n):
if n < 2:
retur... |
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.
Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colo... | 3 | n=int(input())
s=input()
for i in range(n-1):
if(s[i]==s[i+1] and s[i]!='?'):
print("No")
exit()
if(s[0]=='?' or s[n-1]=='?'):
print("Yes")
exit()
for i in range(1,n-1):
if (s[i]=='?'):
if(s[i-1]=='?' or s[i+1]=='?'):
print("Yes")
exit()
elif(s[i-1... |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | #!/usr/bin/env python
# coding: utf-8
# In[204]:
# # n = int(input())
# # line = list(map(int, input().split()))
# # line = list(str(input()))
# In[81]:
from collections import Counter
# In[43]:
line1 = list(map(int, input().split()))
line2 = list(map(int, input().split()))
# In[89]:
demand, supply = lin... |
You are given a number k and a string s of length n, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:
* The first character '*' in the original string should be replaced with 'x';
* The last character '*' in the... | 3 | In=input
lin=lambda : map(int,In().split())
for _ in range(int(In())):
_,k=lin()
m=In()
j=1
i=m.index('*')
while i<m.rfind('*'):
i=m.rfind('*',i,i+k+1)
j+=1
print(j) |
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned ... | 1 | def ToyCars():
collision = []
n = int(raw_input())
cars = []
for i in range(n):
current = list(map(int,raw_input().split()))
cars.append(current)
for i in range(n):
for j in range(n):
if cars[i][j] == 1 or cars[i][j] == 3:
break
if ca... |
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())
m=0
x=0
for i in range(n):
a,b=map(int,input().split())
x=x-a+b
if x>m:
m=x
print(m) |
Ehab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?
A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (pos... | 1 | if __name__ == '__main__':
t = int(raw_input())
for _ in range(t):
n = int(raw_input())
arr = map(int, raw_input().split())
print(len(set(arr)))
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1... | 1 | m, n = map(int, raw_input().split())
t = [map(int, raw_input().split()) for _ in range(m)]
for a in range(1, n):
t[0][a] += t[0][a - 1]
for p in range(1, m):
t[p][0] += t[p - 1][0]
for p in range(1, m):
for a in range(1, n):
t[p][a] += max(t[p][a - 1], t[p - 1][a])
for p in range(m):
print t[p][-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 | import itertools
import math
import sys
import heapq
from collections import Counter
from collections import deque
from fractions import gcd
from functools import reduce
sys.setrecursionlimit(4100000)
INF = 1 << 60
MOD = 10 ** 9 + 7
# γγγγζΈγε§γγ
t = int(input())
for i in range(t):
a, b = map(int, input().split())
... |
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deletin... | 3 | from sys import stdout
from sys import stdin
def get():
return stdin.readline().strip()
def getf():
return [int(i) for i in get().split()]
def put(a, end = "\n"):
stdout.write(str(a) + end)
def putf(a, sep = " ", end = "\n"):
stdout.write(sep.join(map(str, a)) + end)
def main():
n = int(get())
... |
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 | n = int(input())
st = list(input())
d = {}
for i in range(n - 1):
wk1 = st[i] + st[i + 1]
if not wk1 in d:
d[wk1] = 0
d[wk1] += 1
most = 0
for i in d:
if d[i] > most:
most = d[i]
ans = i
print(ans) |
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ... | 3 | n = int(input())
l = list(map(int,input().split()))
maxPlay = max(l)
sum = 0
for i in range(n):
l[i] = maxPlay - l[i]
sum+=l[i]
if(sum>=maxPlay):
break
if(sum>=maxPlay):
print(maxPlay)
else:
t = (maxPlay-sum)//n
while(t!=0):
maxPlay+=t
sum+=(n*t)
t = (maxPlay-sum)//n
t+=1
print(maxPlay+t) |
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.
The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as ... | 1 | a = input()
b = raw_input()
g = 0
maxSequence = 0
prevSequence = 0
actSequence = 0
for t in b:
if t == 'G':
g += 1
actSequence += 1
else:
maxSequence = max(maxSequence, prevSequence + actSequence + 1)
prevSequence = actSequence
actSequence = 0
maxSequence = max(maxSequ... |
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n ... | 3 | input()
s=input().split()
k=0
maxk=0
q="QWERTYUIOPASDFGHJKLZXCVBNM"
for i in s:
k=0
for j in i:
if j in q:k+=1
if k>maxk:maxk=k
print(maxk)
|
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 | g = int(input())
if (g == 2):print('NO')
elif g%2==0:print('YES')
else:print('NO') |
Phoenix is playing with a new puzzle, which consists of n identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.
<image> A puzzle piece
The goal of the puzzle is to create a square using the n pieces. He is allowed to rotate and move the pieces around, but none of them can overlap an... | 1 | from __future__ import division,print_function
from heapq import*
import sys
le = sys.__stdin__.read().split("\n")[::-1]
af=[]
def f(n):
if n%2:
return "NO"
n//=2
if int(n**0.5)**2==n:
return "YES"
if n%2:
return "NO"
n//=2
if int(n**0.5)**2==n:
return "YES"
r... |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | n1=input().lower()
n2=input().lower()
if n1>n2:
print(1)
elif n1==n2:
print(0)
else:
print(-1)
|
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.
More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the ci... | 1 | num = int(raw_input())
#cons = 10^9+7
cons = 1
for i in range(0, 9):
cons *= 10
cons += 7
total = 1
good = 0
for i in range(1, num+1):
good = good * 27 + (total - good) * 20
total *= 27
total %= cons
good %= cons
print good
|
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is ... | 3 | import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
class UF_tree:
def __init__(self, n):
self.root = [-1] * (n + 1)
self.rank = [0] * (n + 1)
def find(self, x):
if self.root[x] < 0:
return x
else:
self.root[x] = self.find(self.r... |
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fasten... | 1 | def button():
n = input()
a = raw_input().split()
a = [int(x) for x in a]
if n > 1:
if (n-sum(a)) == 1:
print('YES')
else:
print('NO')
else:
if sum(a) == 1:
print('YES')
else:
print('NO')
... |
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s... | 3 | n= int(input(""))
a=list(map(int, input().split()))
a.sort()
b=list(map(int, input().split()))
b.sort()
c=list(map(int, input().split()))
c.sort()
for i in b:
a.remove(i)
for j in c:
b.remove(j)
print(a[0])
print(b[0]) |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 1 | # Starts here
import sys
def Execute(inputStream):
sys.stdin = inputStream
numGroups = int(sys.stdin.readline())
groupSizes = { '1': 0, '2': 0, '3': 0, '4': 0 }
groups = sys.stdin.readline().split()
for group in groups:
groupSizes[group] += 1
result = groupSizes['4'] + groupSizes['3']
... |
Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ m metres. Bob had planks of three types: a planks 1 Γ 2 meters, b planks 2 Γ 1 meters, and c planks 2 Γ 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, f... | 1 | import string
str = raw_input().strip().split()
n, m, a, b, c = [ int(str[i]) for i in range(5) ]
res = [ [-1 for j in range(m+3)] for i in range(n+3)]
step = [(-1, 0), (0, -1), (-1, 1), (1, -1), (0,2), (2, 0)]
sum = 2*a + 2*b + 4*c
col = string.lowercase
if sum < n*m: print 'IMPOSSIBLE'
elif n&1 and m&1: print 'IMPO... |
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 β€ i < j < k < l β€ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The first line of each test case contains a single integer n (4 β€ n β€ ... | 3 | def solve():
n=int(input())
l=list(map(int,input().split()))
left=[0]*(3002)
ans=0
for i in range(n):
right=[0]*(3002)
for j in range(n-1,i,-1):
ans+=right[l[i]]*left[l[j]]
right[l[j]]+=1
left[l[i]]+=1
print(ans)
for _ ... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | s=input()
a=list(s)
for i in range(int((len(a)-1)/2)):
a.remove("+")
a.sort()
b=""
for i in range(len(a)):
if(i!=len(a)-1):
b=b+a[i]+"+"
elif(i==len(a)-1):
b=b+a[i]
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.