problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | import math
import os
import random
import re
import sys
if __name__ == '__main__':
a, b, c = input(), input(), input()
x = [0] * 26
for _ in a:
x[ord(_) % 65] += 1
for _ in b:
x[ord(_) % 65] += 1
for _ in c:
x[ord(_) % 65] -= 1
res = list(filter(lambda i: i != 0, x))... |
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 | sum = input()
x = 1
out=""
while x < 4:
i=0
while i< len(sum):
if sum[i]== "+":
i+=1
elif int(sum[i]) == x:
if len(out) == len(sum)-1:
out = out+ str(x)
i+=1
else:
out = out+ str(x) +"+"
i+=1
else:
i+=1
x+=1
print(out)
|
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.
The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic pr... | 3 | from sys import exit
def iis(): return map(int, input().split())
def ii(): return int(input())
def liis(): return list(map(int, input().split()))
s = input()
todos = {}
for i in range(len(s)):
if s[i] not in todos:
todos[s[i]] = 0
todos[s[i]] += 1
ans = 1
maxi1 = 1
maxi2 = 1
maxi1c = s[0]
for k in todos:
if to... |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | s1,s2=input().lower(),input().lower()
if(s1>s2):
print(1)
elif(s1<s2):
print(-1)
else:
print(0)
|
Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a β
b = d.
Input
The first line contains t (1 β€ t β€ 10^3) β the number of test cases.
Each test case contains one integer d (0 β€ d β€ 10^3).
... | 3 |
t=int(input())
while t>0:
n=float(input())
if n**2-4*n<0: print('N')
elif n==0: print( 'Y',0.,0.)
else:
b=(n+(n**2-4*n)**0.5)/2
a,v=float,float
print( 'Y', b,b/(b-1))
t-=1
|
You are the gym teacher in the school.
There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right.
Since they are rivals, you want to maximize the distance between them. If students a... | 3 | t=int(input())
while(t):
t-=1
n,x,a,b=[int(i)for i in input().split()]
print(min(n-1,abs(a-b)+x)) |
Given 2 integers u and v, find the shortest array such that [bitwise-xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of its elements is u, and the sum of its elements is v.
Input
The only line contains 2 integers u and v (0 β€ u,v β€ 10^{18}).
Output
If there's no array that satisfies the condition, print "... | 1 | u,v=map(int, raw_input().split())
if u>v or u%2!=v%2:
print -1
exit(0)
if u==v:
if u==0:
print 0
else:
print 1
print u
exit(0)
x=(v-u)/2
if x&u:
print 3
print u, x, x
else:
print 2
print u+x, x |
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 = 'AOYEUI'
a1 = a.lower()
for char in input():
if char not in a and char not in a1:
print('.%s'%char.lower(),end='') |
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Input
The ... | 3 |
n, k = map(int, input().split())
r = k // n
d = k - (r * (n - 1))
for i in range(n):
row = []
for j in range(n):
ans = int(j == i) * d + int(j != i) * r
row.append(str(ans))
print (' '.join(row))
|
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.
The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them... | 3 | import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
#sys.setrecursionlimit(10**7)
# OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
mod=10**9 + 7
"""
x_move=[-1,0,1,0,-1,1... |
There is an N-car train.
You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."
Constraints
* 1 \leq N \leq 100
* 1 \leq i \leq N
Input
Input is given from Standard Input in the following format:
N i
O... | 3 | [a,b]=[int(i) for i in input().split()]
print(a-b+1)
|
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal.
The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si... | 3 | T = int(input())
for case in range(T):
n = int(input())
ans = (n + 2) // 2
print(ans) |
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times β at i-th step (0-indexed) you can:
* either choose position pos (1 β€ pos β€ n) and increase v_{pos} by k^i;
* or not choose any posit... | 3 | t = int(input())
fi = float("inf")
bgnm = 10**16
max_pow = 56
for _ in range(t):
#print("test num ", _)
#print("============================")
n, k = map(int, input().split())
arr = list(map(int, input().split()))
x = sum(arr)
pows = [k**i for i in range(max_pow+1, -1, -1)]
#print(pows)
... |
You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k β₯ 0, calculate the expression s_k = f(x) + f(y) β
2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For e... | 3 | I=input
for _ in[0]*int(I()):print(I()[::-1][I()[::-1].find('1'):].find('1')) |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n = int(input())
a = list(map(int, input().split(" ")))
a.sort()
for i in range(n):
print(a[i], end=" ") |
Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge.
Determine whether it is possible to divide the vertices into non-e... | 3 | N = int(input())
S = []
for i in range(N):
Ss = input()
S.append(Ss)
E = [set() for i in range(N)]
D = [[100000]*N for i in range(N)]
for i in range(N):
D[i][i] = 0
for j in range(i+1, N):
if S[i][j] == "1":
#print(i, j)
E[i].add(j)
E[j].add(i)
D[i][j] = 1
D[j][i] = 1
ok = True... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | def ver(l):
d = [0]*len(l)
if d ==l:
return False
else:
return True
def recorrer(p,ref):
n = 0
for ele in p:
if ele>=ref and ele!=0:
n+=1
return n
n_k = [int(x) for x in input().split(" ")]
p = [int(x) for x in input().split(" ")]
k = n_k[1]
re... |
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 1 | n, m = map(int, raw_input().split(" "))
res = 0
while n < m:
if m % 2 == 0:
m /= 2
res += 1
else:
m = (m + 1) / 2
res += 2
res += n - m
print res
|
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 | lst=list(map(int,input().split()))[:3]
lst.sort()
s1=lst[1]-lst[0]
s2=lst[2]-lst[1]
print(s1+s2)
|
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'... | 1 | I = lambda:map(int,raw_input().split())
s,n = I()
t = 1
l = sorted([I() for _ in [0]*n])
lis = zip(*l)
x = lis[0]
y = lis[1]
for i in range(n):
if s>x[i]:
s = s+y[i]
else:
print 'NO'
t = 0
break
if t == 1:
print 'YES' |
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.
Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple tre... | 1 | __author__ = '11x256'
nn = int(raw_input())
p = []
n = []
for i in range(0,nn):
temp = map(int ,raw_input().split())
if temp[0] < 0 :
n.append(temp)
else:
p.append(temp)
n = sorted(n,reverse=True)
p = sorted(p)
count = 0
if len(n) > len(p):
count = n[0][1]
for j in range(0,len(p)... |
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficu... | 3 | r, c = map(int, input().split())
b = [list(input()) for i in range(r)]
for y in range(r):
for x in range(c):
if b[y][x] == '.':
b[y][x] = '0'
ok = True
for Y in range(r):
for X in range(c):
if not b[Y][X].isdigit():
continue
p = 0
for dy in range(-1, 2):... |
Tsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer a_i.
Yui loves sweets, but she can eat at most m sweets each day for health reasons.
Days are 1-indexed (numbered 1, 2, 3, β¦). Eating the sweet i at the d-t... | 3 | n,m=[int(x) for x in input().split(' ')]
alist=[int(x) for x in input().split(' ')]
alist.sort()
slist=[]
mm=[0]*(n+1)
a=[0]*(n+1)
s=0
for i in range(n):
s+=alist[i]
slist.append(s)
for j in range(1,n+1):
t=alist[j-1]
if j-1 >= m:
t+=mm[j-1-m]
mm[j-1]=t
t+=a[j-1]
a[j]=t
print(t,e... |
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
print(re.sub(r'\s+', ' ', input().replace("WUB", " ")).lstrip().rstrip())
|
Valera had two bags of potatoes, the first of these bags contains x (x β₯ 1) potatoes, and the second β y (y β₯ 1) potatoes. Valera β very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater ... | 3 | y, k, n = map(int, input().split())
s = (-y)%k
if s>n-y or (s==0 and s+k>n-y):
print(-1)
else:
while s <= n-y:
if s>0:
print(s)
s += k
|
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.
Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo... | 3 | T = int(input())
while T > 0:
n, m = map(int, input().split())
span = [m,m]
prev_time = 0
sche = True
for i in range(n):
t, l, h = map(int, input().split())
span[0] -= t-prev_time
span[1] += t-prev_time
prev_time = t
span[1] = min(span[1],h)
span[0] = ... |
It is known that each weight of 1 gram, 3 gram, 9 gram, and 27 gram can be weighed from 1 gram to 40 gram in 1 gram increments using a balance. For example, if you put a weight of 3 grams and a weight you want to weigh on one plate of the balance and a weight of 27 grams and 1 gram on the other plate, the weight of the... | 3 | w = int(input())
result = []
chars = '0+-'
n = 0
while w > (3 ** n - 1) // 2:
result.append(chars[(w + (3 ** n - 1) // 2) // (3 ** n) % 3])
n += 1
result.reverse()
print(''.join(result)) |
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.
Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the ... | 3 | # for _ in range(int(input())):
# n = int(input())
# arr1 = list(map(int, input().split(" ")))
# arr2 = list(map(int, input().split(" ")))
# res = "yes"
# if(sorted(arr1) != sorted(arr2)):
# print("no")
# continue
# if n%2 == 1 and arr1[n//2] != arr2[n//2]:
# print(... |
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 | def countLimakGrowth(a, b):
leapYear = 0
while a <= b:
a *= 3
b *= 2
leapYear += 1
return leapYear
def main():
a, b = map(int, input().split())
print(countLimakGrowth(a, b))
if __name__ == "__main__":
main()
|
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a = int(input())
b = int(input())
c = int(input())
ans = [0]*5
ans[0] = a+(b*c)
ans[1] = a*(b+c)
ans[2] = a*b*c
ans[3] = (a+b)*c
ans[4] = a+b+c
maxd = 0
for i in range(5):
if ans[i] > maxd:
maxd = ans[i]
print(maxd)
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n=int(input())
l=list(map(int,input().split()))
l.insert(0,0)
for i in range(1,n+1):
print(l.index(i),end=" ")
|
Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times.
* Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`.
For example, if you perform an operation for the second letter on `aa... | 3 | s=list(input())
k=int(input())
for i in range(len(s)):
c = (ord('z') - ord(s[i]) + 1)%26
if c <= k:
k -= c
s[i] = 'a'
s[-1] = chr(ord('a') + ((ord(s[-1]) - ord('a') + k) % 26))
print(''.join(s)) |
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible... | 3 | n = input()
n2 = int(n)
nstr = input()
nstr2 = nstr.split( )
ns = [0 for i in range(n2)]
for x in range(n2):
ns[x] = int(nstr2[x])
ns2 = sorted(ns)
max_num = min(int(ns2[n2-1])-int(ns2[1]),int(ns2[n2-2])-int(ns2[0]))
print(max_num) |
Let f(x) be the sum of digits of a decimal number x.
Find the smallest non-negative integer x such that f(x) + f(x + 1) + ... + f(x + k) = n.
Input
The first line contains one integer t (1 β€ t β€ 150) β the number of test cases.
Each test case consists of one line containing two integers n and k (1 β€ n β€ 150, 0 β€ k ... | 3 | # 1.Iterate over the last (rightmost) digit
# 2. Iterate over the number of 9s before it.
# 3. Calculate the needed sum of left digits, check it to be non-negative and integer.
# 4. Construct left part greedy to fit that sum.
# And find the minimum value among them. No special cases.
def get(s):
return str(s % 9) + '... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 1 | n=raw_input()
if (n[0]=='-'):
if (n[len(n)-1]>n[len(n)-2]):
n=n[:-1]
print int(str(n))
else:
k=n[len(n)-1]
n=n[:-2]
n=n+k
print int(str(n))
else:
print str(n)
|
Zane the wizard is going to perform a magic show shuffling the cups.
There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.
The problematic bone is initially at the position x = 1. Zane will confuse the audience b... | 3 | n,m,k=map(int,input().split())
holes=set(map(int,input().split()))
ans=1
swaps=[]
for i in range(k):
swaps=list(map(int,input().split()))
if ans in holes:
continue
elif ans==swaps[0]:
ans=swaps[1]
elif ans==swaps[1]:
ans=swaps[0]
print(ans) |
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English... | 3 | n = int(input())
s = input() + '_'
b = False
w = 0
countin = 0
m = 0
for i in s:
if i == '_':
if b:
if w!=0:
countin += 1
else:
m = max(m, w)
w = 0
else:
if i == '(':
b = True
m = max(m, w)
w = 0
... |
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 | #!/usr/bin/env python
n = int(raw_input())
a = map(int,raw_input().split())
a.sort()
me = 0
count = 0
flag = True
while flag:
me += a.pop()
count += 1
if me > sum(a):
flag = False
print count
|
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be deri... | 3 | for _ in range(int(input())):
s = input()
t = input()
d = {}
for x in s:
d[x] = 1
for x in t:
if d.get(x, 0) == 0:
print(-1)
break
else:
dp = [[-1] * 26 for i in range(len(s))]
p = [-1] * 26
for i in range(len(s) - 1, -1, -1):
... |
You are given three integers, A, B and C.
Among them, two are the same, but the remaining one is different from the rest.
For example, when A=5,B=7,C=5, A and C are the same, but B is different.
Find the one that is different from the rest among the given three integers.
Constraints
* -100 \leq A,B,C \leq 100
* A, B ... | 3 | A,B,C = map(int,input().split())
if A == C: print(B)
elif A == B: print(C)
else : print(A) |
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must b... | 3 | '''
http://codeforces.com/contest/550/problem/B
'''
def recursion(index, sub_problem):
if index == len(list_value):
return [sub_problem]
else:
all_sub_problem = []
choosing_index = recursion(index+1, sub_problem + [list_value[index]])
not_choosing_index = recursion(index+1, sub_... |
Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants!
Vlad built up his own playlist. The playlist consists of N songs, each has a unique positi... | 1 | T = int(raw_input())
for _ in range(T):
N = int(raw_input())
arr = [int(x) for x in raw_input().rstrip().split(" ")]
K = int(raw_input())
key = arr[K-1]
pos = 0
for x in arr:
if x <= key:
pos += 1
print pos |
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the ... | 3 | def read(): return list(map(int, input().split()))
n, a, b = read()
city = read()
print(sum(list(min(a * (city[i] - city[i - 1]), b) for i in range(1, n)))) |
Arkady and his friends love playing checkers on an n Γ n field. The rows and the columns of the field are enumerated from 1 to n.
The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set o... | 1 | n,m = map(int,raw_input().strip('\n').split(' '))
ans = 0
for i in range(1,m+1):
for j in range(i,m+1):
if (i**2+j**2)%m == 0:
a = (n-i)/m
b = (n-j)/m
# print i,j,a,b
if i != j:
ans+= 2*(a+1)*(b+1)
else:
ans += (a+1)*(b+1)
print ans |
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 | n = int (raw_input ())
l = [int (i) for i in raw_input ().split ()]
S = sum (l)
L ,ret = [0] * (n + 1), 0
for i in range (n): L [i + 1] = L [i] + l [i]
for i in range (1, n):
if 2 * L [i] == S:
ret += 1
print ret
|
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.
Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,... | 3 | w,h=map(int,input().split())
w1,h1=map(int,input().split())
w2,h2=map(int,input().split())
for i in range(h,-1,-1):
w+=i
if i==h1:
w-=w1
if i==h2:
w-=w2
if w<=0:
w=0
if w<=0:
print(0)
else:
print(w)
|
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k,n,w = (int(i) for i in input().split())
s = 0
for i in range(w):
s += (i+1)*k
if (s<n):
print(0)
else:
print(s-n) |
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()
while '+' in s:
s = s.replace('+',' ')
l = list(s.split())
l.sort()
for i in range(len(l)-1):
print(l[i], end='+')
print(l[-1]) |
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.
You know that you ... | 3 | col=int(input())
for _ in range(col):
n,m=input().split()
n=int(n);m=int(m)
s=input()
ans=[0]*26
L=sorted(list(map(int,input().split())),reverse=True)
temp=s;m=1;k=0
for i in range(len(s)-1,-1,-1):
while k!=len(L) and i+1==L[k]:m+=1;k+=1
ans[ord(s[i])-97]+=m
print(*ans) |
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 | n = int(input())
while True:
n += 1
l = [int(x) for x in str(n)]
if l[0]!=l[1] and l[0]!=l[2] and l[0]!=l[3]:
if l[1]!=l[2] and l[1]!=l[3]:
if l[2]!=l[3]:
print(n)
exit()
else:
continue
else:
continue
els... |
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned... | 3 | a = int(input())
b = set()
c = set()
for i in range(a):
x, y = map(int, input().split())
b.add(x)
c.add(y)
if len(b) == 2 and len(c) == 2:
x1, x2 = b
y1, y2 = c
print(abs((x1 - x2)*(y1 - y2)))
else:
print(-1)
|
Given is a rooted tree with N vertices numbered 1 to N. The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.
Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.
Now, the following Q operations will be performed:
* Operation... | 1 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq
# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7
def solve(f):
n, q = f.read_int_list()
g = collections.defaultdict(list)
for _ in xrange(n-1):
... |
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.
Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.
Every time Polycarp wakes up, he decides if he wants to sleep... | 3 | import math
def task(a, b, c, d):
remaining = a - b
total = b
if remaining <= 0:
print(b)
return
if d >= c:
print(-1)
return
diff = c - d
sleeps = math.ceil(remaining / diff)
total += sleeps * c
print(total)
t = int(input())
for i in range(0, t):
... |
Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers.
Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course... | 3 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.wri... |
You are given an array a of length n consisting of integers. You can apply the following operation, consisting of several steps, on the array a zero or more times:
* you select two different numbers in the array a_i and a_j;
* you remove i-th and j-th elements from the array.
For example, if n=6 and a=[1, 6,... | 1 | from collections import*
for _ in range(input()):n=input();print max(max(Counter(raw_input().split()).values())*2-n,n%2) |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | powers = []
for i in range (2,30):
powers.append (pow(2,i)-1)
T = int(input())
for _ in range (T):
n = int(input())
for p in powers:
if n%p == 0:
print (n//p)
break |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, β¦, a_n, in ... | 3 | # inp = open( 'file.txt' ).readline
inp = input
n = int( inp() )
arr = list( map( int , inp().strip().split(" ") ) )
brr = list( map( int , inp().strip().split(" ") ) )
ops = {}
nps = {}
for i in range(n):
ops[ arr[i] ] = i+1
nps[ brr[i] ] = i+1
lefd = []
ritd = []
for i in range(1,n+1):
... |
Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
* At time 1, the first spectator stands.
* At time 2, the second spectator stands.
* ...
* At time k, the k-th spectator stands.
* At time k + 1, the (k + 1)-th specta... | 3 | n, k, t = map(int, input().split())
if t < k:
print(t)
elif t > n:
print(max(0, k - (t - n)))
else:
print(k) |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | n = int(input())
s = 0
s += n//100
n %= 100
s += n//20
n %= 20
s += n//10
n %= 10
s += n//5
n %= 5
s += n//1
print(s)
|
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 | x = input()
c = 0
for i in range(len(x)):
if x[i] == "4" or x[i] == "7":
c+=1
if c!= 0 and (c==4 or c==7 or c==47 or c==74 or c==447 or c==474 or c==744):
print("YES")
else:
print("NO") |
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an n Γ m table with integers in its cells. The order of meteors in... | 3 | import sys
n, m, k = map(int, input().split())
grid = []
for _ in range(n):
grid.append(list(map(int, next(sys.stdin).split())))
col = [i-1 for i in range(1,m+1)]
row = [i-1 for i in range(1,n+1)]
sol = []
for _ in range(k):
q, x,y = next(sys.stdin).split()
x, y = int(x) -1, int(y) -1
if q == "g":
... |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | 3 | t = int(input())
for testcase in range(t):
n = int(input())
al = list(map(int, input().split()))
pos = al[0] > 0
chunks = []
chunk = []
for x in al:
if x > 0:
if pos:
chunk.append(x)
else:
chunks.append(chunk)
chunk... |
Did you know that there are over 40,000 varieties of Rice in the world ? There are so many dishes that can be prepared with Rice too. A famous chef from Mumbai, Tid Gusto prepared a new dish and named it 'Tid Rice'. He posted the recipe in his newly designed blog for community voting, where a user can plus (+) or minus... | 1 | t =int(raw_input())
while(t):
count=0
n = int(raw_input())
a = {}
for i in range(0,n):
c = list(raw_input())
b = c.pop(-1)
a[''.join(c)]=b
c = a.values()
for i in c:
if i=='+':
count=count+1
elif i=='-':
count=count-1
print coun... |
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | t = int(input())
for _ in range(t):
arr = list(map(int, input().split()))
mx = max(arr[:-1])
sm = sum(mx - a for a in arr[:-1])
if (arr[-1] - sm) >= 0 and (arr[-1] - sm) % 3 == 0:
print("YES")
else:
print("NO") |
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.
A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character... | 3 | from sys import stdin,stdout
from collections import defaultdict as df
import bisect
t=int(input())
for iii in range(t):
s=stdin.readline().rstrip()
sota=set()
ans=float('inf')
if s.count('1')==0 or s.count('2')==0 or s.count('3')==0:
print(0)
else:
d=df(list)
for i in range(... |
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused β what if he decides to rewatch the ... | 3 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writabl... |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 β€ k β€ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | t=int(input())
for i in range(t):
n,k = map(int,input().split())
if(n>k):
print((k*(k+1))//2)
else:
print((n*(n-1))//2+1) |
Mobile phones are equipped with a function that displays input candidates in order to efficiently input texts such as emails. This records frequently used words and presents words that have the entered letters as initial letters as input candidates. For example, if you usually enter the word "computer" a lot, just ente... | 3 | from collections import defaultdict
while True:
n = int(input())
if n==0:
break
initial = defaultdict(set)
cnt = defaultdict(int)
for _ in range(n):
l = list(input().split())
for li in l:
initial[li[0]].add(li)
cnt[li] += 1
... |
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 | b = 0
for i in range(int(input())):
b+=1 if '++' in input() else -1
print(b) |
You are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently ap... | 3 | from itertools import combinations
from functools import reduce
from math import sqrt
n = input()
j = len(n)
key = -1
for _ in range(j, 0, -1):
for i in combinations(n, _):
ld = reduce(lambda x, y: x + y, i)
if sqrt(int(ld)) == int(sqrt(int(ld))) and ld[0] != str(0):
if len(n) - len(ld) ... |
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 | s=list(input())
n=len(s)
while n and s==s[::-1]:
s.pop()
n-=1
print(n) |
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an empty square; if a... | 3 | from sys import stdin
h,w = map(int,stdin.readline().split())
arr = [list(stdin.readline()) for _ in range(h)]
dp = [[0]*w for _ in range(h)]
dp[0][0] = 1
mod = 10**9+7
for i in range(h):
for j in range(w):
if arr[i][j] == '.':
dp[i][j] += (0 if i==0 else dp[i-1][j])+(0 if j==0 else dp[i][j-1])
... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n, k = map(int, input().split()); L = [int(z) for z in input().split()]
m = L[k-1]; x = 0
for n in L:
if n >= m:
x += 1
if len(L) - L.count(0) <= k:
x = len(L) - L.count(0)
print(x) |
A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.
The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each r... | 3 | n = int(input())
across = [ list(map(int, input().split())) for i in range(2) ]
down = list(map(int, input().split()))
path = down[0] + sum(across[1])
costs = [ path ]
for i, top in enumerate(across[0]):
bottom = across[1][i]
path = path - down[i] - bottom + down[i + 1] + top
costs.append(path)
costs.sort()
pri... |
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 | from math import ceil
a=input().split()
b=input().split()
n=int(input())
if ceil((int(a[0])+int(a[1])+int(a[2]))/5)+ceil((int(b[0])+int(b[1])+int(b[2]))/10) > n:
print('NO')
else:
print('YES')
|
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of... | 3 | n, m, a, b = map(int, input().split())
print(min(n // m * b + min((n % m != 0) * b, n % m * a), n * a)) |
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 | # Soldier and Bananas
a, b = input().split()
a = int(a)
b = int(b)
y = 0
while a <= b:
a *= 3
b *= 2
y += 1
print(y) |
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 | import math
n,k=input().split()
n,k=[int(n),int(k)]
odd=math.ceil(n/2)
even=n-odd
if k<=odd:
print(k*2-1)
else:
m=k-odd
print(m*2)
# |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
l = list(map(int,input().split()))
a = [1]*n
for i in range(1,n):
if l[i-1]<=l[i]:
a[i]=a[i-1]+1
print(max(a)) |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | s=str(input())
upper=0
lower=0
for i in s:
if i.isupper():
upper+=1
else:
lower+=1
if(lower>=upper):
print(s.lower())
else:
print(s.upper()) |
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that:
gcd(sum(S_1), sum(S_2)) > 1
Here sum(S) denotes the sum of all elements present in set S and gcd means the[greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
Ev... | 3 | a = int(input())
if a <= 2:
print('No')
else:
print('Yes')
print(2, end=' ')
print('1 %d' % a)
print(a-2, end=' ')
for i in range(2, a):
print(i, end='')
if not i == a - 1:
print(' ', end='')
print('') |
Create a program that takes two dates as input and outputs the number of days between the two dates.
Date 1 (y1, m1, d1) is the same as or earlier than date 2 (y2, m2, d2). Date 1 is included in the number of days, not date 2. Also, take the leap year into account when calculating. The leap year conditions are as foll... | 1 | import datetime as D
while 1:
a,b,c,d,e,f=x=map(int,raw_input().split(" "))
if min(x)<0: break
print (D.date(d,e,f)-D.date(a,b,c)).days |
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans... | 3 | s = input()
s = ''.join(s.split())
d1 = 'AEIOUY'
d2 = 'BCDFGHJKLMNPQRSTVWXZ'
if s[-2].upper() in d1:
print('YES')
else:
print('NO')
|
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:
<image> The cell with coordinates (x, y) is at the intersection of x-th row ... | 3 | t = int(input())
for _ in range(t):
x1,y1,x2,y2 = list(map(int,input().split()))
xd = x2-x1
yd = y2-y1
print(xd*yd+1) |
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integ... | 3 | import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
... |
Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.
Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue ente... | 3 | n,p,t=map(float,input().split())
n,t=int(n),int(t)
dp=[[0 for i in range(t+1)] for j in range(t+1)]
dp[0][0]=1
for i in range(1,t+1):
for j in range(i+1):
if j>=1:
dp[i][j]=p*dp[i-1][j-1]+(1-p)*dp[i-1][j]
else:
dp[i][j] = (1 - p) * dp[i - 1][j]
s=0
s1=sum(dp[t])
s2=0
for j... |
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four... | 3 | t = int(input())
for _ in range(t):
a, b, c = [int(x) for x in input().split()]
print(a + b + c - 1) |
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 3 | from sys import stdin
input=stdin.readline
def A():
t=int(input())
for __ in range(t):
l,r=map(int,input().split())
if 2 * l > r:
print("YES")
else:
print("NO")
def B():
t=int(input())
for __ in range(t):
_=0
def C():
t=int(input())
for ... |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | n, k = map(int, input().split())
y = sorted(map(int, input().split()))
sol = 0
for i in y:
if k <= (5-i):
sol +=1
print(sol//3) |
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 | t=int(input())
while t>0:
n,k=list(map(int,input().split()))
a=sorted(list(map(int,input().split())))
b=sorted(list(map(int,input().split())),reverse=True)
i=0
while i<k:
if b[i]>a[i]:
temp=a[i]
a[i]=b[i]
b[i]=temp
else:
break
i... |
AquaMoon had n strings of length m each. n is an odd number.
When AquaMoon was gone, Cirno tried to pair these n strings together. After making (n-1)/(2) pairs, she found out that there was exactly one string without the pair!
In her rage, she disrupted each pair of strings. For each pair, she selected some positions... | 3 | from sys import stdin, stdout
from heapq import heapify , heappush , heappop
import sys
from collections import Counter
from copy import deepcopy
import math
from itertools import permutations
sys.setrecursionlimit(10 ** 5)
mod = 10 **9 + 7
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,... |
When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.
Constra... | 3 | N = input()
print(N[0:3]) |
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 | for i in range(int(input())):
a,b=map(int,input().split())
c=0
while a!=b and a!=0:
c+=1
if a<b:
if a*8<=b:
a=a*8
elif a*4<=b:
a=a*4
elif a*2<=b:
a=a*2
else:
c=-1
b... |
One important contest will take place on the most famous programming platform (Topforces) very soon!
The authors have a pool of n problems and should choose at most three of them into this contest. The prettiness of the i-th problem is a_i. The authors have to compose the most pretty contest (in other words, the cumul... | 1 | def calc(X, Y):
if len(Y) == 3: return sum(Y)
for x in X:
for y in Y:
if y % x == 0: break
else:
return calc([i for i in X if i != x], sorted(Y+[x])[::-1])
return sum(Y)
for _ in range(int(raw_input())):
N = int(raw_input())
A = sorted(set([int(a) for a in raw... |
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 | a=int(input())
b=list(input())
i=0
c=0
while i+c<a:
print(b[i+c],end='')
c+=1
i+=c
print() |
You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it.
Constraints
* The length of S is 2 or 3.
* S consists of lowercase English letters.
Input
Input is given from Standard Input i... | 3 | s = input()
print(s if len(s) == 2 else s[2]+s[1]+s[0]) |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | a= int (input())
a=int (a)
i=0
while a>0:
x,y,z=input().split(" ")
x=int (x)
y=int(y)
z=int(z)
a-=1
if x+y+z>=2:
i+=1
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 | def watermelon(n):
if n > 3 and n % 2 == 0:
print("YES")
else:
print("NO")
if __name__ == "__main__":
w = int(input())
watermelon(w)
|
We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
The square (i, j) has two numbers A_{ij} and B_{ij} written on it.
First, for each square, Takahashi paints one of the written numbers red and the other blue.
Then... | 3 | h,w=map(int,input().split())
a=[list(map(int,input().split()))for _ in range(h)]
b=[list(map(int,input().split()))for _ in range(h)]
dp=[w*[0]for _ in range(h)]
dp[0][0]=(1<<(80+(a[0][0]-b[0][0])))|(1<<(80+(b[0][0]-a[0][0])))
for i in range(h):
for j in range(w):
if i!=0:
dp[i][j]|=dp[i-1][j]<<(80+(a[i][j]-... |
The only difference between easy and hard versions is the length of the string.
You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without chang... | 3 | import sys
def input():
return sys.stdin.readline().rstrip()
def slv():
S = input()
T = input()
n = len(T)
needcntl = [0]*(n + 1)
needcntr = [0]*(n + 1)
idx = 0
i = 0
while i < n:
if T[i] == S[idx]:
needcntl[i + 1] = idx + 1
i += 1
idx += 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.