problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | #fin = open("D:\Python\Test.inp", "r")
#fout = open("D:\Python\Test.out", "w")
a, b = map(int,input().split())
#fin.close()
for i in range(b):
if (a%10==0):
a=a/10
else:
a=a-1
print(str(int(a)));
#fout.close()
|
In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.
It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not cov... | 3 | a, b = map(int, input().split())
print(((b-a)+1)*(b-a)//2-b)
|
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | n=3
a = list(map(int,input().strip().split()))[:n]
a.sort()
print(a[1]-a[0]+a[2]-a[1])
|
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ... | 3 | from sys import stdin
def main():
liste=[int(x) for x in stdin.readline().split()]
a=liste[0]
b=liste[1]
teves=[int(x) for x in stdin.readline().split()]
give=[]
suma=0
cont=1
may=0
pos=0
while cont <=b:
for i in range(a):
if teves[i] < may:
m... |
Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".
Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. ... | 3 | from operator import itemgetter
n = int(input())
limits = input().split(' ')
limits = [int(i) for i in limits]
if sum(limits) < len(limits)-1:
print(-1)
elif limits[0] == 0:
print(-1)
else:
ANSWER = []
is_know = [True] + (len(limits) - 1) * [False]
indices = [i[0] for i in sorted(enumerate(limits)... |
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 3 | from sys import stdin, stdout
import math
n = int(stdin.readline())
for i in range(n):
arr = [int(x) for x in stdin.readline().split()]
ele = [int(x) for x in stdin.readline().split()]
odd_count = 0
even_count = 0
yes = 0
for j in ele:
if (j%2 == 0):
even_count += 1
... |
Write a program which calculates the area and circumference of a circle for given radius r.
Constraints
* 0 < r < 10000
Input
A real number r is given.
Output
Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-... | 3 | import math
a = float(input())
print(math.pi*a*a,math.pi*2*a)
|
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, _, _] = map(int, raw_input().split())
if n1 > n2:
print 'First'
else:
print 'Second'
|
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
c = 0
for i in range(n):
if a[i] == 0:
a[i] += 1
c += 1
print(c + (1 if sum(a) == 0 else 0)) |
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.
They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.
Let th... | 1 | def splitting_pile_2():
n = int(raw_input())
nums = list(map(int, raw_input().split(" ")))
total_sum = sum(nums)
left_sum = nums[0]
ans = abs(total_sum-left_sum*2)
for i in range(1, n-1):
left_sum = left_sum + nums[i]
ans = min(ans, abs(total_sum-left_sum*2))
print ans
if __name__ == "__main__":
splittin... |
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».
The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | 3 | n, m, k = map(int, input().split())
d = []
for i in range(m + 1):
d.append(int(input()))
a = d.pop()
def to_binary(s, n):
c = []
while s:
c.append(s % n)
s = s // n
return c[::-1]
cnt = 0
for i in d:
b = a ^ i
if sum(to_binary(b, 2)) <= k:
cnt += 1
print(cnt) |
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But t... | 1 |
n, s = map(int, raw_input().split())
sugar = []
res = 0
ok = False
for i in xrange(n):
dollar, cent = map(int, raw_input().split())
if dollar*100 + cent <= s*100:
ok = True
if cent > 0:
res = max(res, 100-cent)
if not ok:
print -1
else:
print res
|
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho... | 3 | g=input()
def func(g):
if (len(g)==1):
return 51
sum=(len(g)+1)*26-len(g)
return sum
print(func(g))
|
Today is Sid’s birthday and he is very excited about this as he is giving a special birthday party to all his friends. In this party they are going to play a game for which Sid have to arrange all his friends in a row such that no two boys should be present which are adjacent to each other. There are total M girls and ... | 1 | a = int(raw_input())
def fact(m):
j=1
t=1
for i in range(0,m):
t=t*j
j=j+1
return t
for i in range(a):
l=raw_input()
c=l.split(' ')
m=int(c[0])
n=int(c[1])
if n-m>1:
print -1
else:
ans=((fact(m)*fact(m+1))/fact(m-n+1))%1000000007
print ans |
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:
Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the ... | 3 | n = int(input().strip())
if n<=5:
print(-1)
else:
for i in range(2,n-1):
print(1,i)
for i in range(n-1,n+1):
print(2,i)
for i in range(1,n):
print(i,i+1) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | a = int(input())
a = a + 1
while(len(str(a)) != len(set(str(a)))):
a+=1
print(a) |
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two.
You may perform any number (possibly, zero) operations with this multiset.
During each operation you choose two equal integers from s, remove them from s and insert the number eq... | 3 | t=int(input())
while(t>0):
n=int(input())
l=[int(i) for i in input().split()]
f=0
l.sort()
q=1
while(q):
q=0
if(2048 in l):
f=1
break
else:
for i in range(0,len(l)-1):
if(l[i]==l[i+1]):
x=l.pop(i... |
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed h... | 3 | def rain(arr,y):
res=0
yy=arr[y:]
for i in range(0,len(yy)-1):
test1,test2=yy[i],yy[i+1]
if test1>=test2:
res +=1
else:
break
x=arr[:y+1]
# x.reverse()
for i in range(len(x)-1,0,-1):
if x[i]>=x[i-1]:
res +=1
else:
... |
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 | for _ in " "*int(input()):
a=int(input())
b=list(map(int,input().split()));z=[]
for i in b:
if i not in z:z+=[i]
print(*z) |
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.
LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
O... | 3 |
def nod(a, b):
while a > 0 and b > 0:
if a > b:
a %= b
else:
b %= a
return max(a, b)
m = 10 ** 13
q1 = -1
i1 = -1
x = int(input())
sqrtx = int(x ** 0.5)
for i in range(1, sqrtx + 1):
if x % i == 0:
q = x // i
if nod(q, i) * x == i * q and m > max(q... |
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase.
A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD... | 3 | a = input().split()
a = [int(i) for i in a]
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string = input()
alphabet = alphabet[:a[1]]
table = dict()
for i in alphabet:
table[i] = 0
for i in string:
table[i] += 1
s = table[min(table, key = table.get)] * a[1]
print(s) |
Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:
* The sum of the digits in base ten is a multiple of D.
Constraints
* All values in input are integers.
* 1 \leq K < 10^{10000}
* 1 \leq D \leq 100
Input
Input is given from Standard Input in the following ... | 3 | #intじゃ無理
K=str(input())
D=int(input())
N=len(K)
P=10**9+7
#DP[i][smaller][j]=上からi(1<=i<=len(K))桁目までで桁総和modDがj(0<=j<=D-1)の個数
DP=[[[0]*(D) for index1 in range(2)] for index2 in range(N+1)]
#i=0に関しては初期値として与える
DP[0][0][0]=1
#桁DP:O(ND)
for i in range(1,N+1):
for j in range(D):
for k in range(10):
... |
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 | w,h,sx,sy = map(int,input().split())
for x in range(sx, w+1):
for y in range(sy, h+1):
print(x,y)
for y in range(1, sy):
print(x,y)
sy = y
for x in range(1, sx):
for y in range(sy, h+1):
print(x,y)
for y in range(1, sy):
print(x,y)
sy = y
|
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | def main():
T = int(input())
for _ in range(T):
N, K = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = sorted(a)
b = sorted(b)
gain = 0
for k in range(K):
if a[k] < b[-1 -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 | import sys
import io, os
input = sys.stdin.buffer.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
if sum(A) != sum(B):
print(-1)
continue
... |
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that:
* 1 ≤ a ≤ n.
* If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has... | 3 | if __name__ == '__main__':
print(('Mahmoud', 'Ehab')[int(input()) % 2]) |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 1 | import os
def readInts(): return map(int,raw_input().split())
n=readInts()[0]
arr=readInts()
#print arr,n
arr=sorted(arr)
def getCoinCount(arr1,arr2,minCoins):
#print arr1,arr2,minCoins
if len(arr1)>1:
#print arr1,arr2
if sum(arr1)==sum(arr2):
#print "check1"
if minCoins ... |
You have a given integer n. Find the number of ways to fill all 3 × n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
<image> This picture describes when n = 4. The left one is the shape and the right one is 3 × n tiles.
Input
The only line cont... | 3 | n = int(input())
if n % 2 == 1:
print(0)
exit(0)
else:
ans = int(1)
for i in range(n):
if i % 2 == 0:
ans *= 2
print(ans)
|
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 | word1 = str(input())
word2 = str(input())
if word1.lower() == word2.lower():
print(0)
else:
for i in range(len(word1)):
if word1[i].lower() < word2[i].lower():
print(-1)
break
elif word1[i].lower() > word2[i].lower():
print(1)
break |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | n,k=map(int,input().split())
if(n%2==0):
n1=n//2
else:
n1=n//2 + 1
if(k<=n1):
print(2*k-1)
else:
k=k-n1
print(2*k) |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n,h= input().split()
n=int(n)
h=int(h)
hei=[int(x) for x in input().split()]
s=0
for i in hei:
if i<=h:
s=s+1
else:
s=s+2
print(s)
|
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 3 | a, b, c = map(int, input().split())
print(min(a+b+c, 2*(a+b), 2*(a+c), 2*(b+c)))
|
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be... | 1 | n,k = map(int, raw_input().split())
s = [float(x) for x in raw_input().split()]
a = 0.0
b = sum(s)/n
while b-a >= 10**-9:
mid = (a+b)/2
y = z = 0
for x in s:
y += max(0, (x-mid)*0.01*(100-k))
z += max(0, mid-x)
if y >= z:
a = mid
else:
b = mid
print a
|
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 | import sys
s = list(input())
t = list(input())
if len(s)!=len(t):
print('NO')
sys.exit()
i = 0
j = len(s)-1
while j>=0 :
if s[i]!=t[j]:
print('NO')
break
else:
i += 1
j -= 1
else:
print('YES') |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 1 | a=raw_input()
bl=[]
list = {}
for letter in a:
list[letter] = list.get (letter, 0)+1
if(len(list)%2==0):
print "CHAT WITH HER!"
else:
print "IGNORE HIM!"
|
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.
<image> English alphabet
You are given a... | 3 | class CodeforcesTask691BSolution:
def __init__(self):
self.result = ''
self.word = ''
def read_input(self):
self.word = input()
def process_task(self):
symetric_chars = [("A", "A"), ("b", "d"), ("I", "I"), ("o", "o"), ("O", "O"), ("X", "X"), ("x", "x"),
... |
Let S(n) denote the sum of the digits in the decimal notation of n. For example, S(123) = 1 + 2 + 3 = 6.
We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.
Given an integer K, list the K smallest Snuke numbers.
Constraints
* 1 \leq K... | 3 | K = int(input())
def S(n):
m = n
s = 0
while m > 0:
s += m % 10
m //= 10
return s
# the number of 9s
n9 = 0
e = 10 ** n9
count = 0
upper = 1
while count < K:
n = (upper + 1) * e - 1
s = S(upper) + 9 * n9
if n <= e * s:
print(n)
upper += 1
count += ... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | num = 0
for i in range(int(input())):
a = input()
if a =="X++" or a=="++X":
num +=1
elif a =="X--" or a=="--X":
num -=1
print(num) |
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | n=int(input())
a=[]
ans=0
for i in range(n):
a.append(input())
for i in range(1,n-1):
for j in range(1,n-1):
if(a[i][j]=='X' and a[i-1][j-1]==a[i][j] and a[i-1][j+1]==a[i][j] and a[i+1][j-1]==a[i][j] and a[i+1][j+1]==a[i][j]):
ans+=1
print(ans)
|
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | n=int(input())
s=input()
na=s.count("A")
nd=s.count("D")
if na>nd:
print( "Anton")
elif na<nd:
print("Danik")
elif nd==na:
print( "Friendship") |
The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is.
Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given ... | 1 | p = input()
cnt = 0
for x in range(p):
if (pow(x, p - 1, p) - 1) % p:
continue
cnt += all((pow(x, y, p) - 1) % p for y in range(1, p - 1))
print(cnt)
|
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte... | 3 | l = int(input())
n = int(input())
min_sum = -1
n_str = str(n)
l = len(n_str) // 2
r = (len(n_str) + 1) // 2
while True:
if n_str[l] == '0' and n_str[r] == '0':
l -= 1
r += 1
continue
elif n_str[l] != '0' and n_str[r] != '0':
a = int(n_str[:l]) + int(n_str[l:])
b = int(... |
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).
Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with ... | 3 | q=input().split()
x=int(q[0])
k=int(q[1])
def po(a,p,m):
if p==0:
return 1
x=po(a,p//2,m)%m
x=(x%m*x%m)%m
if p%2==1:
x=(x%m*a%m)%m
return int(x)
m=1000000007
if x==0:
print(0)
else:
print(((po(2,k+1,m)%m*x%m)%m-(po(2,k,m)%m-1)%m)%m) |
Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b.
Constraints
* 0 < a, b ≤ 2,000,000,000
* LCM(a, b) ≤ 2,000,000,000
* The number of data sets ≤ 50
Input
Input consists of several data sets. Each data set contains a and b separated by a single spa... | 1 | while True:
try:
a = map(int,raw_input().split())
n = [a[0],a[1]]
while True:
if a[0] < a[1]:
tmp = a[0]
a[0] = a[1]
a[1] = tmp
a[0] = a[0] - a[1]
if a[0] == 0:
break
b = n[0]*n[1]/a[1]
print "%d %d" % (a[1],b)
except EOFE... |
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 | import collections
n = int(input())
s = input()
d = collections.defaultdict(int)
for i in range(n-1):
d[s[i:i+2]] += 1
d = list(d.items())
d.sort(key=lambda x: x[1])
print(d[-1][0])
|
Recently Petya walked in the forest and found a magic stick.
Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:
1. If the chosen number a is even, then the spell will turn it into 3a/2;
2. If t... | 3 | test_case=int(input())
for i in range(test_case):
x,y=map(int,input().split())
if x==y:
print("yes")
elif (x==3 or x==2) and y>x:
if y==3:
print('yes')
else:
print('no')
elif x>y:
print('yes')
elif y>x and x>1 :
print('yes')
else:
... |
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui... | 3 | n, t, k, d = map(int, input().split())
g = int((n + k - 1) / k)
o1, o2 = 0, d
i = 0
while i < g:
if o1 <= o2:
o1 += t
else:
o2 += t
i += 1
if max(o1, o2) < g * t:
print("YES")
else:
print("NO") |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | def ismin(l,i):
k=0
while k<=i:
if l[i]>=l[k] and i!=k:
return 0
k+=1
return 1
def ismax(l,i):
k=0
while k<=i:
if l[i]<=l[k] and i!=k:
return 0
k+=1
return 1
n=int(input())
l=[int(x) for x in input().split()]
i=1
cnt=0
while i<n:
if... |
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 | n = input()
if n % 2 == 0 and n > 3:
print 'YES'
else:
print 'NO' |
To become the king of Codeforces, Kuroni has to solve the following problem.
He is given n numbers a_1, a_2, ..., a_n. Help Kuroni to calculate ∏_{1≤ i<j≤ n} |a_i - a_j|. As result can be very big, output it modulo m.
If you are not familiar with short notation, ∏_{1≤ i<j≤ n} |a_i - a_j| is equal to |a_1 - a_2|⋅|a_1 ... | 3 | n,m = list(map(int,input().split()))
arr = list(map(int,input().split()))
if n>m:
print(0)
else:
cnt = 1
for i in range(n):
for j in range(i+1,n):
cnt = (cnt*(abs(arr[i]-arr[j])%m))%m
print(cnt) |
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 | def Main():
n = int(input())
maxt = 0
train = 0
for i in range(n):
outt, inn = map(int, input().split())
train -= outt
train += inn
if maxt < train:
maxt = train
print(maxt)
if __name__ == "__main__":
Main()
|
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 | a,b,c = input().split(" ")
a, b, c = int(a), int(b), int(c)
if a % c == 0 and b % c == 0:
print((a//c) * (b//c))
elif a % c != 0 and b % c != 0:
print((a//c + 1)*(b//c+1))
elif a % c != 0 and b % c == 0:
print((a // c + 1) * (b // c))
elif a % c == 0 and b % c != 0:
print((a // c) * (b // c + 1)) |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | a=list(map(int,input().split()))
a,b=a[0],a[1]
ar=list(input())
while(b):
b-=1
i=0
while(i<a-1):
if(ar[i]=='B' and ar[i+1]=='G'):
ar[i],ar[i+1]=ar[i+1],ar[i]
i=i+1
i+=1
print("".join(ar))
|
Arkady is playing Battleship. The rules of this game aren't really important.
There is a field of n × n cells. There should be exactly one k-decker on the field, i. e. a ship that is k cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if... | 3 | n, m = (int(i) for i in input().split())
result = [[0 for i in range(n)] for j in range(n)]
p = []
for i in range(n):
p += [input()]
for i in range(n):
for j in range(n-m+1):
flag = True
for k in range(m):
if p[i][j+k] == '#':
flag = False
if flag:
... |
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di... | 3 | x=int( input())
i=0
if x <= 9:
print(0)
else:
while True:
res = [int(x) for x in str(x)]
z = sum(res)
i+=1
x=z
if z<=9:
break
print(i) |
Samu is in super market and in a mood to do a lot of shopping. She needs to buy shirts, pants and shoes for herself and her family. There are N different shops. Each shop contains all these three items but at different prices. Now Samu has a strategy that she won't buy the same item from the current shop if she had alr... | 1 | for k in range(int(raw_input())):
n=int(raw_input())
table=[[0 for x in range(3)] for x in range(n)]
table[0][0],table[0][1],table[0][2]=map(int,raw_input().split())
for i in range(1,n):
p,q,r=map(int, raw_input().split())
table[i][0]=min(table[i-1][1],table[i-1][2])+p
table[i][1]=min(table[i-1][0],table[i-1]... |
People in the Tomskaya region like magic formulas very much. You can see some of them below.
Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:
<image><image>
Here, "mod" means the operation of taking the residue after dividing.
The expression <image> ... | 3 | import sys
import string
import math
import heapq
from collections import defaultdict
from functools import lru_cache
from collections import Counter
from fractions import Fraction
def mi(s):
return map(int, s.strip().split())
def lmi(s):
return list(mi(s))
def tmi(s):
return tuple(mi(s))
def mf(f, s):
... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | s=int(input())
c=0
while c==0:
s+=1
t=str(s)
j=[]
for i in t:
if i not in j:
j.append(i)
if len(j)==4:
c=1
print(s)
break |
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | 3 | print(bin(int(input())).count('1'))
####################### |
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine th... | 3 | import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
a = ... |
Write a program that reads the coordinates of the vertices of a convex n-sided polygon (a polygon whose internal angles are less than 180 degrees, that is, a polygon that is not dented) and outputs its area. The vertices are named Vertex 1, Vertex 2, Vertex 3, ... Vertex n according to the order of edge connections.
H... | 3 | # AOJ 0079 Area of Polygon
# Python3 2018.6.17 bal4u
def calc_area(p):
n, s = len(p), 0
p.append(p[0])
for i in range(n):
s += (p[i].real-p[i+1].real)*(p[i].imag+p[i+1].imag)
return abs(s)/2
p = []
while True:
try: x, y = list(map(float, input().split(',')))
except EOFError: break
p.append(complex(x, y))
pri... |
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substring s[l … r] (1 ≤ l ≤ r ≤ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_... | 3 | def antipal (s) :
if s != s[::-1] :
return len(s)
else:
while s[::-1] == s and len(s) != 1:
s = s[:-1]
if len(s) == 1:
return 0
else:
return len(s)
s = input()
print (antipal(s))
|
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | 3 |
T = int(input().strip())
for t in range(T):
n, k = list(map(int, input().split()))
n, k = min(n,k), max(n,k)
if n > 2:
print('NO')
elif n == 2:
if k == 2:
print('YES')
else:
print('NO')
else:
print('YES')
|
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 | def solve(a,b):
p=b/a
if p % 1 != 0 or (p / 2) % 1 != 0:
return -1
c=0
while b>a and b%2==0:
b=b//2;c+=1
if b==a:
if c%3==0:
return c // 3
else:
return (c//3)+1
return -1
for _ in range(int(input())):
a,b=sorted(map(int,input().split())... |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | Dict = {}
S,N = [int(_) for _ in input().split()]
for i in range(N):
X = [int(_) for _ in input().split()]
if X[0] in Dict:
Dict[X[0]]+=X[1]
else:
Dict[X[0]] = X[1]
List = list(Dict.keys())
List.sort()
for i in List:
if S>i:
S+=Dict[i]
else:
print("NO")
break
... |
Let's call an array a_1, a_2, ..., a_m of nonnegative integer numbers good if a_1 + a_2 + ... + a_m = 2⋅(a_1 ⊕ a_2 ⊕ ... ⊕ a_m), where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2⋅ 6 = 2⋅ (1⊕ 2 ⊕ 3 ⊕ 6). A... | 3 | from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
debugging = False
def dprint(*args):
if debugging:
print(*args)
else:
pass
# Code
t = intp... |
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 | stop_count = int(input())
current_pas = 0
pas_list = list()
for i in range(stop_count):
pas = input().split()
(ex, en) = (int(pas[0]), int(pas[1]))
current_pas += en - ex
pas_list.append(current_pas)
pas_list.sort(reverse=True)
print(pas_list[0]) |
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to at most once discard two or three cards wi... | 1 | c = map(int, raw_input().split())
s = sum(c)
e = 0
q = 0
for x in c:
if c.count(x) >=3:
e = x*3
elif c.count(x) == 2:
q = max(q, x*2)
print s-max(e,q)
|
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | def sumOfDigits(n):
ans=0
while (n):
ans += n % 10
n = n // 10
return ans
for i in range(int(input())):
n, s = map(int, input().split())
steps = 0
p=10
while (sumOfDigits(n) > s):
steps += (p - n % p)
n += p -n%p
p*=10
print(steps) |
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | 1 | from sys import stdin
n = int(stdin.readline())
a = map(int, stdin.readline().split(' '))
a.sort()
for i in range(1, n+2):
if not i in a:
print i
break |
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the Ox axis from west to east, and th... | 3 | n = int(input())
points = []
for _ in range(n):
x, y = map(int, input().split())
points.append([x, y])
point_count = 0
for i in range(len(points) - 1):
pre_point = points[i-1]
point = points[i]
next_point = points[i+1]
if pre_point[0] == point[0] and next_point[1] == point[1]:
if point[0... |
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.
Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.
Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.
You are given str... | 3 | for _ in range(int(input())):
s=input()
n=len(s)
ans=n-2
g={i:[]for i in '0123456789'}
for i in range(n):g[s[i]].append(i)
for a in'0123456789':
for b in'0123456789':
cs=0
i=j=0
aa=g[a]
bb=g[b]
ans=min(ans,n-len(aa))
... |
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 | s=input()
if s.find('0'*7)==-1 and s.find('1'*7)==-1:
print('NO')
else:
print('YES') |
In some other world, today is Christmas.
Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:
* A level-0 burger is a patty.
* A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) b... | 3 | n, x = map(int, input().split())
a, p = [1], [1]
for i in range(n):
a += [a[i] * 2 + 3]
p += [p[i] * 2 + 1]
def f(n, x):
if n == 0:
return 1 - (x <= 0)
elif x <= 1 + a[n-1]:
return f(n-1, x-1)
else:
return p[n-1] + 1 + f(n-1, x-2-a[n-1])
print(f(n, x)) |
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | 3 | n=int(input())
count=0
s=list(map(int, input().strip().split(" ")))
for i in range(n-2):
if(s[i+1]<s[i] and s[i+1]<s[i+2]) or (s[i+1]>s[i] and s[i+1]>s[i+2]):
count+=1
print(count) |
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a n... | 3 | def f(n):
i = 2
primfac = []
while i * i <= n:
if n % i == 0:
primfac.append([i, 0])
while n % i == 0:
primfac[-1][1] += 1
n //= i
i += 1
if n > 1:
primfac.append([n, 1])
return primfac
def main():
n, b1 = map(int, input().split())
ans = ... |
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers.
Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves:
1. move right — go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n.
2. mo... | 3 | import os
import sys
from io import BytesIO, IOBase
import math
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mo... |
In the snake exhibition, there are n rooms (numbered 0 to n - 1) arranged in a circle, with a snake in each room. The rooms are connected by n conveyor belts, and the i-th conveyor belt connects the rooms i and (i+1) mod n. In the other words, rooms 0 and 1, 1 and 2, …, n-2 and n-1, n-1 and 0 are connected with conveyo... | 3 | import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n=int(input())
path=list(map(str,input().strip()))
All=0
co=0
if ('>' not in path) or ('<' not in path):
All=1
returnable=[0]*(n)
for i in range(n):
if(path[i]=='-'):
returnable[(i+1)%n]=1
... |
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... | 1 | from __future__ import division, print_function
# import threading
# threading.stack_size(2**27)
# import sys
# sys.setrecursionlimit(10**7)
from sys import stdin, stdout
import bisect #c++ upperbound
import math
import heapq
i_m=9223372036854775807
def modinv(n,p):
return pow(n,p-2,p)
def cin():
ret... |
There are N piles of stones. The i-th pile has A_i stones.
Aoki and Takahashi are about to use them to play the following game:
* Starting with Aoki, the two players alternately do the following operation:
* Operation: Choose one pile of stones, and remove one or more stones from it.
* When a player is unable to do t... | 3 | INF=10**18
def calc(a,b,xor):
if (a,b,xor) in memo:
return memo[(a,b,xor)]
if (a&1)^(b&1)!=(xor&1):
return INF
if xor==0:
if a<b:
return INF
else:
return (a-b)//2
x=2*calc(a//2,b//2,xor//2)
y=2*calc((a-1)//2,(b+1)//2,xor//2)+1
memo[(a,b,xor)]=min(x,y)
return memo[(a,b,xor)]
n=... |
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b.
For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | 3 | from math import sqrt
for _ in range(int(input())):
n,k=list(map(int,input().split()))
if n%2==0:
print(n+k*2)
else:
i=n
for i in range(3,int(sqrt(n))+1)[::2]:
if n%i==0:
break
else:
i=n
print(n+i+2*(k-1)) |
This problem is actually a subproblem of problem G from the same contest.
There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di... | 3 | q = int(input())
for _ in range(q):
n = int(input())
gifts = map(int, input().split())
candyDict = {}
for i in gifts:
try:
candyDict[i] += 1
except:
candyDict[i] = 1
xd = list(candyDict.values())
xd.sort()
toCheck = max(xd)
total = 0
for i in r... |
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number.
For example, let's say that Vitaly's favourite digits are ... | 1 | def main():
ay,st,pp = any,str,pow
a,b,n = map(int,raw_input().split())
f,res,mod = [1]*(n+1),0,10**9+7
sta,stb = st(a),st(b)
for i in xrange(1,n+1):
f[i] = f[i-1]*i
f[i] %= mod
for i in xrange(n+1):
sum = a*i+b*(n-i)
check = 1
while sum:
digit = sum%10
if digit != a and digit != b:
check = ... |
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auct... | 3 | input()
l=list(map(int,input().split()))
ll=sorted(l,reverse=True)
print(l.index(ll[0])+1," ",ll[1]) |
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, an... | 1 | # Stripe
n = int(raw_input())
s = [int(x) for x in raw_input().split()]
c = 0
l,r = 0,sum(s)
for i in xrange(n-1):
l += s[i]
r -= s[i]
if l == r:
c += 1
print c
|
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n = int(input())
arr = []
for i in range(int(n)):
x=str(input())
arr.append(x)
i = 0
sum = 0
while i<len(arr):
if arr[i]=="X++"or arr[i]=="++X":
sum+=1
elif arr[i]=="X--"or arr[i]=="--X":
sum-=1
i+=1
print(sum)
|
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.
Future students will be asked just a single question. They are given a sequen... | 3 | n = int(input())
nums = [int(i) for i in input().split()]
res = 0
prev = 0
edge = False
for i in range(1, n):
if nums[i - 1] == nums[i]:
edge = True
break
if nums[i - 1] == 1:
if nums[i] == 2:
res += 3
if prev == 3:
res -= 1
if nums[i] ==... |
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 | #266A
n = int(input())
color = str(input())
color_seq = []
move = 0
if len(color) == n:
for i in range(len(color)):
color_seq.append(color[i])
else:
pass
for i in range(len(color_seq)):
if i == 0:
pass
else:
if color_seq[i] == color_seq[i-1]:
move +=1
else:
pass
print(move)
|
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | 3 | t = int(input())
for i in range(t):
n = int(input())
f = (n - 2) * "3"
if n == 1:
print(-1)
else:
print("23" + f) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s = input()
s1 = ""
for i in range(len(s)):
if s[i] == "h":
if "h" in s1:
continue
else:
s1+=s[i]
if s[i] == "e":
if "he" in s1:
continue
else:
if "h" in s1:
s1+=s[i]
else:
continue
... |
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 | a = input()
for x in a.lower():
if x != 'a' and x !='o' and x !='e' and x !='y' and x !='u' and x !='i':
print('.', x, end ='', sep ='') |
N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament. For some reasons, the tournament may not be "fair" for all the contestants. That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The struct... | 3 | import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n = int(input())
a = [None]*(n-1)
from collections import defaultdict
c = defaultdict(list)
for i in range(n-1):
num = int(input())
c[num].append(i+2)
### 行きがけ順DFS
def d... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | for i in range(int(input())):
n = int(input())
a = [int(j) for j in input().split()]
e,o = 0,0
for j in a:
if(j%2==0):
e = 1
else:
o = 1
if(sum(a)%2!=0 or (e==1 and o==1)):
print('YES')
else:
print('NO')
|
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of ope... | 3 | n = int(input())
s = input()
L = []
n_B = 0
n_W = 0
ans = []
for c in s:
if c == 'W':
n_W += 1
x = 1
else:
n_B += 1
x = 0
L.append(x)
is_possible = True
if n_B % 2 and n_W % 2:
is_possible = False
if n_W == 0 or n_B == 0:
print(0)
elif is_possible:
for i in range... |
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 | original_words = input()
lower_words = original_words.lower()
vowels = ['a','e','i','o','u','y']
consonants=[]
for words in lower_words :
if words not in vowels:
consonants.append('.')
consonants.append(words)
print("".join(consonants))
|
Petya and Vasya are competing with each other in a new interesting game as they always do.
At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≤ K ≤ S.
In order to win, Vasya ha... | 3 | from sys import stdin
N, S = map(int, stdin.readline().split())
if S/N >= 2:
print("YES")
L = [2]*(N-1)
L.append(S-2*N+2)
print(" ".join(map(str, L)))
print(1)
else:
print("NO")
|
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in whi... | 3 | import sys
from collections import deque
sys.setrecursionlimit(10**9)
from copy import deepcopy
def maxH(curr,adjacent_arr):
global memo
if curr in memo:
return memo[curr]
adjacent_nodes = adjacent_arr[curr]
#print(curr,adjacent_nodes,'curr adj nodes')
ans = -float('inf')
if len(adjacent... |
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg... | 1 | n = int(raw_input())
a = []
s1 = 0
s2 = 0
mx = 0
pos = -1
for i in range(0,n):
a.append(map(int, raw_input().split(' ')))
s1 += a[i][0]
s2 += a[i][1]
mx = abs(s1-s2)
for i in range(0,n):
if mx<abs(s1-s2 - 2*a[i][0]+2*a[i][1]):
mx = abs(s1-s2 - 2*a[i][0]+2*a[i][1])
pos = i
print(pos+1) |
Homer has two friends Alice and Bob. Both of them are string fans.
One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.
In a move, a player must choose an index i (1 ≤ i ≤ n) ... | 1 | t=int(raw_input())
for _ in range(t):
s=list(raw_input())
for i in range(len(s)):
if i%2==0:
if s[i]!='a':
s[i]='a'
else:
s[i]='b'
else:
if s[i]!='z':
s[i]='z'
else:
s[i]='y'
print... |
Problem :
Chotu's father is the owner of a Vada Pav shop. One Sunday, his father takes him to the shop. Father tells him that at the end of the day, Chotu has to give him a list consisting of the names of all the customers on that day who bought Vada Pav(s) from the shop. The list should not have the names of any of t... | 1 | t=input();d=set();i=0
while i<t:d.add(raw_input());i+=1
print len(d)
d=sorted(d)
for i in d:
print i |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.