problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha).
The house has a staircase and an elevator. If Masha u... | 3 | x,y,z,t1,t2,t3 = map(int,input().split())
y=abs(y-x)
if abs(z-x)*t2+y*t2+3*t3 <= y*t1 :
print('YES')
else:
print('NO')
|
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 | a=input().split("WUB")
x=len(a)
while "" in a:
a.remove("")
print(' '.join(a)) |
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this stri... | 3 | P = 10**9+7
fa = [1]
for i in range(1, 50000):
fa.append(fa[-1] * i % P)
fainv = [pow(fa[-1], P-2, P)]
for i in range(1, 50000)[::-1]:
fainv.append(fainv[-1] * i % P)
fainv = fainv[::-1]
p2 = [1]
for _ in range(1, 50000):
p2.append(p2[-1] * 2 % P)
def F(a, b):
if a < 0 or b < 0: return 0
return fa[a... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i... | 3 | n = int(input())
print(("abcd" * (n // 4 + 1))[:n])
|
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the ... | 3 | n, m = map(int, input().split())
chests = list(map(int, input().split()))
keys = list(map(int, input().split()))
odd_c = 0
even_c = 0
for c in chests:
if c % 2 == 1:
odd_c += 1
else:
even_c += 1
odd_k = 0
even_k = 0
for c in keys:
if c % 2 == 1:
odd_k += 1
else:
even_k += 1
print(min(odd_c, ev... |
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 | a = input()
total = a.count("4")
total += a.count("7")
total = str(total)
if len(total) == (total.count("7")+total.count("4")):
print("YES")
else:
print("NO") |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | n, m = list(map(lambda x: int(x), input().split()))
a = sorted(list(map(lambda x: int(x), input().split())))
print(min(a[i + n - 1] - a[i] for i in range(m - n + 1)))
|
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation:
Choose one of these numbers and add or subtract 1 from it.
In particular, we can apply this operation to the same number several times.
We want to make the product of all these numbers equal to 1, in other wo... | 3 | from sys import stdin,stdout
from collections import Counter
from itertools import permutations
import bisect
import math
I=lambda: map(int,stdin.readline().split())
I1=lambda: stdin.readline()
#(a/b)%m =((a%m)*pow(b,m-2)%m)%m
l=int(I1())
a=list(I())
c,z,ans=0,0,0
for x in a:
if x==1:
pass
elif x>0:
... |
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.
String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way... | 3 | # Anuneet Anand
n = int(input())
S = []
for i in range(n):
x = input()
S.append([x,len(x)])
S.sort(key = lambda x: x[1],reverse=True)
#print(S)
F = "YES"
for i in range(n):
for j in range(i+1,n):
if S[i][0].count(S[j][0])<1:
F = "NO"
break
S = S[::-1]
print(F)
if F=="YES":
for x in S:
print(x[0]) |
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.
To make a toast, each friend needs nl ... | 1 | [n, k, l, c, d, p, nl, np] = map(int, raw_input().split())
print min(k*l/nl, c*d, p/np)/n |
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the... | 3 | n=int(input());d={25:0,50:0,100:0}
a=list(map(int,input().split()));k=0
for i in range(n):
if a[i]==25:
d[25]+=1
elif a[i]==50:
if d[25]>0:
d[25]-=1
else:
k=1
break
d[50]+=1
else:
if d[50]>0 and d[25]>0:
d[50]-=1
d[25]-=1
elif d[25]>2:
d[25]-=3
else:... |
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation:
Choose one of these numbers and add or subtract 1 from it.
In particular, we can apply this operation to the same number several times.
We want to make the product of all these numbers equal to 1, in other wo... | 3 | # cook your dish here
n=int(input())
x=[int(n) for n in input().split()]
s=[]
ctr=0
c=0
z=0
for i in range(n):
if x[i]>1:
c+=x[i]-1
x[i]=1
elif x[i]<=-1:
c+=-1-x[i]
x[i]=-1
ctr+=1
elif x[i]==0:
z+=1
c+=1
x[i]=1
if ctr&1:
if z==0:
c+... |
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 | s = input().split()
n = int(s[0])
m = int(s[1])
a = int(s[2])
b = int(s[3])
c = n*a
for i in range(1, int(n/m)+1):
if c > b*i + a*(n-m*i):
c = b*i + a*(n-m*i)
if b*(int(n/m)+1) < c:
c = b*(int(n/m)+1)
print(c) |
From "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons?
The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as r... | 3 | n=int(input());
a = list(map(int, input().split(' ')))
print(2 + (min(a) ^ a[2])) |
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... | 1 | def main():
n = int(raw_input())
lilist = list(map(int, raw_input().split()))
lililist = [0] * n
for i in xrange(len(lilist)):
lililist[lilist[i] - 1] = i + 1
print ' '.join(map(str, lililist))
main()
|
Find the minimum area of a square land on which you can place two identical rectangular a Γ b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 β€ a, b β€ 100) β positive integers (you are given ... | 3 | t=int(input())
for i in range(t):
a,b=list(map(int,input().split()))
if a==b:
print((2*a)**2)
else:
if a>b:
if a>2*b:
print(a**2)
else:
print((2*b)**2)
elif a<b:
if b>2*a:
print(b**2)
els... |
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.
When ZS the Coder is at level k, he can :
1. Pr... | 3 | ###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ... |
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) β€ 3 β
10^5 and (r - l) is always odd.
You want to split these numbers into exactly (r - l + 1)/(2) pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one o... | 3 | a,s=map(int,input().split())
n=a
print("YES")
for i in range(((s-a)+1)//2):
print(n,n+1)
n+=2 |
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | 3 | T=int(input())
for _ in range(T):
x1,x2,y1,y2=map(int,input().split())
x,y,a,b,c,d=map(int,input().split())
x,y,a,b,c,d=0,0,a-x,b-y,c-x,d-y
flag=0
#print(a,b,c,d)
if(a==0 and c==0 and (x1!=0 or x2!=0)):
flag=1
if(b==0 and d==0 and (y1!=0 or y2!=0)):
flag=1
if ((x2-x1)<a):... |
Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.
There are N... | 3 | L, N = map(int, input().split())
X = []
for i in range(N):
X.append(int(input()))
X = sorted(X)
ma = 0
for k in range(2):
if k == 1:
X = [L-X[-i] for i in range(1, N+1)]
s = X[0]
for i in range(1, N):
if i % 2 == 1:
s += L - X[-(i//2)-1] + X[i//2]
else:
... |
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.
During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s... | 3 | K, D, T = map(int, input().split())
ivl = D * ((K + D - 1) // D)
fp = float(K)/float(ivl)
sp = 1.0-fp
a = 0.0
b = 2.0*T
for ii in range(300):
t = 0.5*(a+b)
ivls = t // ivl
cooked = ivls * ivl * (2.0*fp + sp)
rt = t - ivls*ivl
rft = min(fp*ivl, rt)
rsp = max(0.0, rt - rft)
cooked += 2.0*rft +... |
You're given an array a_1, β¦, a_n of n non-negative integers.
Let's call it sharpened if and only if there exists an integer 1 β€ k β€ n such that a_1 < a_2 < β¦ < a_k and a_k > a_{k+1} > β¦ > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:
* The arrays [4], [0, 1], [... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
p=0
q=n-1
while p<n and a[p]>=p:
p+=1
while q>=0 and a[q]>=n-q-1:
q-=1
if p>q+1:
print("Yes")
else:
print("No") |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | r = input ()
n = input ()
print ('HARD' if any([s == '1' for s in n]) else 'EASY')
|
The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows.
1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used.
2. Extract a vertex v from the head of the qu... | 3 | import sys
from collections import deque
n=int(input())
visited=[False for i in range(n+1)]
dp=[0 for i in range(n+1)]
l=[[] for i in range(n+1)]
for i in range(n-1):
a,b=map(int,input().split())
l[a].append(b)
l[b].append(a)
b=list(map(int,input().split()))
s=[1]
visited[1]=True
c=1
t=True
for j in range(n... |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 1 | from operator import add
m = reduce(add, (raw_input().split() for _ in xrange(5)), [])
i = m.index('1')
print abs(i / 5 - 2) + abs(i % 5 - 2)
|
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 = set()
b = input()
b = int(b) + 1
a.update(str(b))
while len(a) != 4:
b = int(b) + 1
a = set()
a.update(str(b))
print(b)
|
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String t is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin... | 3 | S=input()
T=S.strip('0')
T1=T[::-1]
if(T1==T):
print("YES")
else:
print("NO")
|
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.
The variance Ξ±2 is defined by
Ξ±2 = (βni=1(si - m)2)/n
where m is an average of si. The standard deviation of the scores is the square root of their variance.
Constraints
* n β€ 1000
* 0 β€ si β€ 100
Inpu... | 3 | while True:
n=int(input())
if n==0:
exit()
*a,=map(int,input().split())
m=sum(a)/len(a)
s=(sum([(m-ai)**2 for ai in a])/len(a))**0.5
print(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 | n=input()
b=False
while b!=True:
c=0
n=str(int(n)+1)
for x in n:
if n.count(x)!=1:
c+=1
if c==0:
print(n)
break
|
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo... | 3 | import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import math
n = int(input())
a = list(map(int,input().split()))
v = max(a)
a = [v-i for i in a if (v-i)!=0]
hcf = a[0]
for i in a[1:]:
hcf = math.gcd(hcf,i)
z = hcf
y = sum([i//z for i in a])
print(y,z) |
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) β
maxDigit(a_{n}).$$$
Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes.
Your task is calculate a_{K} for given a_{1} and K.
Input
The ... | 3 | for _ in range(int(input())):
s = list(input().split())
a1, k = s[0], s[-1]
for i in range(int(k)-1):
if min(a1) != '0':
a1 = str(int(a1)+int(max(a1))*int(min(a1)))
else:
break
print(a1)
|
Given an integer N. Find out the PermutationSum where PermutationSum for integer N is defined as the maximum sum of difference of adjacent elements in all arrangement of numbers from 1 to N.
NOTE: Difference between two elements A and B will be considered as abs(A-B) or |A-B| which always be a positive number.
Inpu... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
t = input()
for loop in range(t):
n = input()
if n == 1:
print 1
else:
if n % 2 == 0:
print ((n * n) - 2) / 2
else:
#(n + 1) * (n / 2)
print ((n * n) - 3) / 2 |
This is the hard version of this problem. The only difference is the constraint on k β the number of gifts in the offer. In this version: 2 β€ k β€ n.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β today the offer "k of goods for the price of one" is held in... | 1 | for _ in range(input()):
n,c,k=[int(i) for i in raw_input().split()]
a=[int(i) for i in raw_input().split()]
a.sort()
dp=[-1 for i in range(n)]
for i in range(n):
if i>k-1:
dp[i]=dp[i-k]+a[i]
elif i==0 or i==k-1:
dp[i]=a[i]
else:
dp[i]=dp[i... |
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two... | 3 | cost, res = {}, []
t = int(input())
for i in range(t):
arr = list(map(int, input().split()))
if len(arr) == 4:
_, u, v, w = arr
while u != v:
if u > v:
cost[u] = cost.get(u, 0) + w
u //= 2
else:
cost[v] = cost.get(v, 0) + w
... |
Ehab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?
A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (pos... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
t = int(input())
for _ in range(t):... |
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | 3 | import math
import random
def encryption(s):
s=s.replace(" ","")
tamanho=len(s)
raiz=math.sqrt(tamanho)
rows=math.floor(raiz)
columns=math.ceil(raiz)
matrizPalavras=[]
counter=0
sFinal=""
if rows*columns<tamanho:
rows+=1
for i in range(rows):
sBuffer=""
f... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 1 | import string
num_test = int(raw_input())
for i in range(0, num_test):
result = ""
data = str(raw_input())
if len(data)>10:
print data[0] + str(len(data)-2) + data[len(data)-1]
else:
print data
|
Suppose we have a sequence of non-negative integers, Namely a_1, a_2, ... ,a_n. At each time we can choose one term a_i with 0 < i < n and we subtract 1 from both a_i and a_i+1. We wonder whether we can get a sequence of all zeros after several operations.
Input
The first line of test case is a number N. (0 < N β€ 100... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n = int(raw_input())
nums = map(int, raw_input().split())
POSSIBLE = (reduce(lambda x,y : y-x, nums) == 0)
if POSSIBLE:
print "YES"
else:
print "NO" |
Chef loves research! Now he is looking for subarray of maximal length with non-zero product.
Chef has an array A with N elements: A1, A2, ..., AN.
Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj.
Product of subarray Aij is product of all its elements (from ith to jth).
Input
First li... | 1 | n=input()
s=map(int,raw_input().split())
l=0
a=[0]*n
for i in range(n):
if s[i]==0:
l=0
else:
l+=1
a[i]=l
print max(a) |
There are N integers, A_1, A_2, ..., A_N, written on the blackboard.
You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.
Find the maximum possible greatest common divisor of the N integers on the blackboard afte... | 1 | import sys
from fractions import gcd
from collections import deque
N=input()
A=map(int, sys.stdin.readline().split())
L=deque()
for i in range(N):
if i==0:
L.append(A[i])
else:
L.append( gcd(A[i],L[i-1]) )
R=deque()
for i in range(N-1,-1,-1):
if i==N-1:
R.appendleft(A[i])
else:
R.appendleft( gcd(A[i],R... |
You are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
... | 3 | def test():
st1 = list(input())
st2 = list(input())
for i in range(len(st1)):
for j in range(len(st2)):
if st1[i] == st2[j]:
print("YES")
return
print("NO")
n = int(input())
for i in range(n):
test() |
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program that... | 3 | a = list(map(int, input().split()))
p = sum(a)
if p % 5 == 0 and p > 0:
print(p//5)
else:
print(-1)
|
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in... | 3 | import sys
import math
from collections import defaultdict,deque
n=int(sys.stdin.readline())
deg=list(map(int,sys.stdin.readline().split()))
nodes=[]
count=0
leaf=0
leaves=[]
for i in range(n):
if deg[i]>1:
nodes.append(i+1)
count+=deg[i]
else:
leaf+=1
leaves.append(i+1)
if leaf>... |
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.
<image>
The park can be represented as a rectangular n Γ m field. The park has k spiders, each spider at ... | 3 | n,m,k=map(int,input().split())
seen = [0 for _ in range(m)]
for i in range(n):
S = list(input())
for j in range(m):
if S[j] == 'U' and not i&1:
seen[j]+=1
elif S[j] == 'L' and j-i>=0:
seen[j-i]+=1
elif S[j] == 'R' and j+i<m:
seen[j+i]+=1
print(*seen, sep=" ") |
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | 3 | for _ in range(int(input())):
x, y = [int(x) for x in input().rstrip().split(" ")]
a, b = [int(x) for x in input().rstrip().split(" ")]
val1 = (x + y) * a
val2 = min(x, y) * b
val2 += (max(x, y) - min(x, y)) * a
print(min(val1, val2)) |
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | 3 | a=int(input())
b=input().split()
c=[int(i) for i in b]
sum=0
k=max(c)
for i in c:
if i!=k:
sum+=k-i
print(sum)
|
Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 β€ i β€ n) has a best friend p[i] (1 β€ p[i] β€ n). In fact, each student is a best frie... | 3 | import math
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ind=defaultdict(lambda:0)
for i in range(n):
ind[a[i]]=i+1
for i in b:
print(ind[i],end=" ") |
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can... | 3 | class CodeforcesTask439BSolution:
def __init__(self):
self.result = ''
self.n_x = []
self.chapters = []
def read_input(self):
self.n_x = [int(x) for x in input().split(" ")]
self.chapters = [int(x) for x in input().split(" ")]
def process_task(self):
self.ch... |
Polycarp has an array a consisting of n integers.
He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its... | 3 | from sys import stdin,stdout
from collections import Counter
def ai(): return list(map(int, stdin.readline().split()))
def ei(): return map(int, stdin.readline().split())
def ip(): return int(stdin.readline().strip())
def op(ans): return stdout.write(str(ans) + '\n')
n=ip()
li = ai()
ans = sum(li)
even = []
odd = []
... |
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=[int(i) for i in input().split()]
a.sort()
b=[str(j) for j in a]
print(' '.join(b))
|
Today is Kriti's birthday but I forgot to bring a gift for her. She is very angry with me. I have an idea for a gift. She likes coding very much. Why not give her a problem to solve as her gift?
I know a problem but I am not sure whether its solvable or not.
The problem initially has N strings numbered 1 to N. The pr... | 1 | N=int(raw_input())
strings=dict()
for i in xrange(N):
s=raw_input()
if(s in strings):
strings[s].append(i+1)
else:
strings[s]=[i+1]
Q=int(raw_input())
for i in xrange(Q):
l,r,query=raw_input().split()
l=int(l)
r=int(r)
cnt=0
if query in strings:
a=strings[query]
cnt=sum([1 for x in a if x>=l and x... |
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi... | 3 | x, y, z = map(int,input().split())
a, b, c = map(int,input().split())
possible = a>=x and a+b-x>=y and a+b+c-x-y>=z
print("YES" if possible else "NO") |
There is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.
The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are ex... | 3 | n, b, a = map(int, input().split())
m = a
l = [*map(int, input().split())]
res = 0
for i in range(n):
t = (a and (l[i] == 0 or (l[i] and (a == m or b == 0))))
# print(i, t)
if t:
if a == 0: break
a -= 1
else:
if b == 0: break
b -= 1
if l[i]: a = min(m, a + 1)
... |
In this problem, we use the 24-hour clock.
Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying?
Constraint... | 3 | h1,m1,h2,m2,k = map(int,input().split())
m = m2-m1 + (h2-h1)*60
print(m-k)
|
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 | for _ in range(int(input())):
x,y=map(int,input().split())
c=(y+1)/2
z=x%(y+1)
if z>=c:
print("YES")
else:
print("NO") |
You are given n strings s_1, s_2, β¦, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | from collections import Counter
def f():
t = int(input())
arr = []
for _ in range(t):
numstr = int(input())
c = Counter()
for _ in range(numstr):
s = input()
c.update(s)
arr.append((c,numstr))
for Ctr, n in arr:
tf = True
for k in... |
There is a beautiful garden of stones in Innopolis.
Its most beautiful place is the n piles with stones numbered from 1 to n.
EJOI participants have visited this place twice.
When they first visited it, the number of stones in piles was x_1, x_2, β¦, x_n, correspondingly. One of the participants wrote down this sequ... | 3 | n = input()
x_stones = map(int, input().split())
y_stones = map(int, input().split())
if (sum(y_stones) > sum(x_stones)):
print("No")
else:
print("Yes")
|
Fennec is fighting with N monsters.
The health of the i-th monster is H_i.
Fennec can do the following two actions:
* Attack: Fennec chooses one monster. That monster's health will decrease by 1.
* Special Move: Fennec chooses one monster. That monster's health will become 0.
There is no way other than Attack and... | 3 | f=lambda:map(int,input().split())
n,k=f()
print(sum(sorted(list(f()))[:max(n-k,0)])) |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | n = int(input())
z = input()
a = z.lower()
if len(set(a)) == 26:
print('YES')
else:
print('NO')
|
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | def help():
# n,m = map(int,input().split(" "))
# arr = list(map(int,input().split(" ")))
n = int(input())
stri = input()
n1 = stri.find('1')
n0 = stri.rfind('0')
if(n0 == -1 or n1 == -1 or n1 == n0+1):
print(stri)
return
print(stri[:n1]+stri[n0:])
for _ in range(int(input())):
help() |
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of sw... | 3 | if __name__ == '__main__':
n = int(input())
line = list(map(int, input().split()))
rest = list()
for i in range(n - 1):
j = i
for t in range(i + 1, n):
if line[j] > line[t]:
j = t
rest.append((i, j))
line[i], line[j] = line[j], line[i]
prin... |
You have three tasks, all of which need to be completed.
First, you can complete any one task at cost 0.
Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.
Here, |x| denotes the absolute value of x.
Find the minimum total cost required to complete all the task.
Constrain... | 3 | a = list(map(int,input().split(" ")))
a.sort()
print(a[2]-a[0]) |
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (... | 3 | a,b,s=input().split()
a=abs(int(a))
b=abs(int(b))
s=int(s)
if (s-(a+b))%2==0 and a+b<=s:
print('Yes')
else:
print('No') |
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 | first = input().split(" ")
n = int(first[0])
t = int(first[1])
s = list(input())
for i in range(t):
c = 0
while c <= n-2:
if s[c] == "B" and s[c+1] == "G":
s[c] = "G"
s[c+1] = "B"
c += 2
else:
c+=1
print("".join(s))
|
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 | def ain():
return map( int, input().split() )
# for _ in range(int(input()))
# n = int(input())
# a = list(map(int, input().split()))
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
count = [ 0 ]*12
for x in a:
if x == 1:
count[0] += 1
i... |
There are a total of A + B cats and dogs. Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.
Determine if it is possible that there are exactly X cats among these A + B animals.
Constraints
* 1 \leq A \leq 100
* 1 \leq B \leq 100
* 1 \leq X \leq 200
* All values in input... | 3 |
a,b,x=map(int,input().split())
print('YES' if 0<=(x-a)<=b else 'NO') |
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams... | 3 | n = int(input())
X = input()
x = X.split()
c1 = x.count('1')
c2 = x.count('2')
def num_finder(c1,c2):
flag = 0
teams = 0
r1 = 0
r2 = 0
if c1>c2 and c2 != 0:
teams += c2
r1 = c1 - c2
flag = 1
elif c1<c2 and c1 != 0:
teams += c1
r2 = c2 - c1
return teams
elif c1 == c2:
teams += c1
return teams
if ... |
You are given an integer n and an integer k.
In one step you can do one of the following moves:
* decrease n by 1;
* divide n by k if n is divisible by k.
For example, if n = 27 and k = 3 you can do the following steps: 27 β 26 β 25 β 24 β 8 β 7 β 6 β 2 β 1 β 0.
You are asked to calculate the minimum numbe... | 3 | x= int(input())
result=0
for i in range(x):
n,k = map(int ,input().split())
while n!=0:
result += n%k+1
n = n//k
print(result-1)
result=0 |
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 | import sys
input = lambda: sys.stdin.readline().strip()
print = lambda s: sys.stdout.write(s)
t = int(input())
for i in range(t):
n, x, a, b = map(int, input().split())
print(str(min(abs(a-b)+x, n-1))+'\n')
|
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | 3 | def solve():
N = int(input())
A = list(map(int,input().split()))
S=set()
for i in range(N):
S.add((i+A[i])%N)
if len(S)==N:
print("YES")
else:
print("NO")
for _ in range(int(input())):
solve()
|
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... | 1 | s = raw_input()
hello = ['h', 'e', 'l', 'l', 'o']
index = 0
f = True
for i in hello:
index = s.find(i)
if index >= 0:
s = s[index+1:]
else:
f = False
break
if f: print 'YES'
else: print 'NO'
|
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.
You know the rules of comparing the results of two give... | 3 | # cook your dish here
p=[]
t=[]
members=[]
def editList(iterable,i,index):
temp=iterable[i]
iterable[i]=iterable[index]
iterable[index]=temp
def allocate_entries(p,t,members,p_entry,t_entry):
for k in range(0,len(p)):
if(p[k]==p_entry):
if(t[k]==t_entry):
membe... |
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!
Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho... | 3 |
t = list(map(int,input().split()))
a= max(t)
b= min(t)
if a-b<=1:
print(0)
else:
t.sort()
ans=(a-b-1)
if t[1]+1<t[-1]:
ans+= t[-1]-t[1]-1
print(ans)
|
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | 3 | for i in range(int(input())):
n=int(input())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
l1.sort()
l2.sort()
print(*l1)
print(*l2) |
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value β_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: neb0123
"""
def solution(n,m):
if n == 1:
return 0
elif n == 2:
return m
else:
return 2*m
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n, m = map(int, input().split(' '))
print(solution(n,m)) |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | import math
import sys
from collections import Counter
n = int(input())
d = dict()
for i in range(0,n):
s = input()
if s in d:
d[s] += 1
print(s+str(d[s]-1))
else:
d[s] = 1
print("OK") |
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ... | 3 | n = int(input())
w = list(map(int, input().split()))
odd, even = w.count(100), w.count(200)
if even % 2 == 0 and odd % 2 == 0:
print("YES")
elif even % 2 and odd % 2 == 0 and odd > 0:
print("YES")
else:
print("NO") |
You have 2n integers 1, 2, ..., 2n. You have to redistribute these 2n elements into n pairs. After that, you choose x pairs and take minimum elements from them, and from the other n - x pairs, you take maximum elements.
Your goal is to obtain the set of numbers \\{b_1, b_2, ..., b_n\} as the result of taking elements ... | 3 | t = int(input())
import math
while(t>0):
t-=1
n= [int (op) for op in input().split()][0]
ar= [int (op) for op in input().split()]
mi = 0
mnr = [0]
kn=0
for a in ar:
if max(0,a-mi-1+mnr[-1])==0:
kn+=1
mnr.append(max(0,a-mi-1+mnr[-1]-1))
mi=a
mi=2*n+1
... |
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 β€ n β€ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separat... | 1 | """
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
* Readability counts *
// Author : raj1307 - Raj Singh
// Date... |
You are given a board of size n Γ n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move... | 3 | for t in range(int(input())):
n = int(input())
ans = ( (n-1) * n * (n+1) ) // 3
print(ans) |
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of a... | 1 | n=input()
A=map(int,raw_input().split())
a1=[]
a2=[]
a3=[]
neg=0
pos=0
for i in A:
if i<0:
neg+=1
else:
pos+=1
for i in A:
if i<0 and len(a1)==0:
a1.append(i)
elif i<0 and neg%2!=0:
a2.append(i)
elif i<0 :
a3.append(i)
neg-=1
elif i>0 and len(a1)==1 and len(a2)!=0:
a1.append(i)
elif i>0 and len(a2)... |
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes... | 3 | v=list(int(x) for x in input().split())
mi=max(3*v[0]/10, v[0]-v[0]/250*v[2])
va=max(3*v[1]/10, v[1]-v[1]/250*v[3])
if mi<va:
print("Vasya")
elif va<mi:
print("Misha")
else:
print("Tie") |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 |
t = int(input())
while t!=0:
n = int(input())
a = list(input())
b = list(input())
ans = []
st = 0
en = n-1
inv_f = drn_f = 0
count = 0
j = n-1
while count<n:
count+=1
if inv_f==0:
if drn_f==0:
if a[en]==b[j]:
en-... |
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 β€ N β€ 10^{18}
* 1 β€ K β€ 10^{18}
* All valu... | 3 | n,k= map(int,input().split())
a=n%k
b=abs(k-a)
print(min(a,b)) |
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9.
A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} β¦ s_r. A substring s[l ... r] of s is called even if the number represented by it is even.
Find the number of even substrings of s. Note, that even if some subs... | 3 | length=int(input())
string=input()
count=0
for i in range(length):
if (int(string[i])%2==0):
count=count+i+1
print (count)
|
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 | from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
def get_int():
return int(stdin.readline().strip())
def get_tuple():
return map(int, stdin.readline().split())
def get_list():
return list(map(int, st... |
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ... | 3 | n,l=map(int,input().split())
p=list(map(int,input().split()))
p.sort()
#print (p)
m=0
for i in range(n-1):
if (p[i+1]-p[i])>m:
m=(p[i+1]-p[i])
x=m/2
if p[0]!=0:
if (p[0])>x:
x=(p[0])
if p[-1]!=l:
#print ("ubibik",(l-p[-1]))
if (l-p[-1])>x:
x=(l-p[-1])
#print ('{0:.10f}'... |
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N.
We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7).
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq K \leq N+1
* All values in input are integers.
Input
Input is given from S... | 3 | n,k = map(int,input().split())
r = 0
mod = 10**9 + 7
for i in range(k,n+2):
r += (n-i+1)*i % mod +1
print(r%mod) |
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc... | 3 | import math
from collections import defaultdict,deque
from itertools import permutations
ml=lambda:map(int,input().split())
ll=lambda:list(map(int,input().split()))
ii=lambda:int(input())
ip=lambda:list(input())
ips=lambda:input().split()
"""========main code==============="""
t=ii()
for _ in range(t):
n=ii()
... |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 β€ n β€ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | t=int(input())
if t%2==0:
print(t//2)
else:
print(-t//2) |
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.
The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch... | 3 | """http://codeforces.com/problemset/problem/276/A"""
def solve(k, l):
res = -1 * 1e9
for i in l:
i = list(i)
joy = i[0] - max(0, i[1] - k)
res = max(res, joy)
return res
n, k = map(int, input().split())
l = [map(int, input().split()) for _ in range(n)]
print(solve(k, l)) |
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).
Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M... | 3 | import math
t = int(input())
ans = []
for i in range(t):
n = int(input())
if n <= 7:
ans.append(1)
else:
k = 0
d = 7
while n > 0 and d >= 2:
if n - d >= d:
k += 1
n = n - d
else:
d = d - 1
ans.ap... |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | n=input()
m=input()
n=[int(x) for x in n.split(' ')]
m=[int(x) for x in m.split(' ')]
m.sort()
q=10000000000000000
p=0
k=n[0]-1
while(k<len(m)):
if(q>m[k]-m[p]):
q=m[k]-m[p]
p+=1
k+=1
print(q)
|
Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store β "PriceFixed". Here are some rules of that store:
* The store has an infinite number of items of every product.
* All products have the same price: 2 rubles per item.
* ... | 3 | import sys
input = sys.stdin.buffer.readline
N = int(input())
A = [0] * N
B = [0] * N
for i in range(N):
A[i], B[i] = map(int, input().split())
indices = list(range(N))
indices.sort(key=lambda i: B[i])
low = 0
high = N - 1
bought = 0
cost = 0
while low <= high:
l = indices[low]
h = indices[high]
if bou... |
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk... | 3 | n = int(input(""))
k = n
s = n-1
t = 0
for i in range(1,n+2):
m = k
while(m!=0):
print(' ',end='')
m = m-1
if i==1:
print("0")
else:
for j1 in range(0,n-s+1):
print(j1,end=' ')
for j2 in range(n-s-1,-1,-1):
t = t+1
if t>=1 and... |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | for i in range(int(input())):
n=int(input())
s=input()
while len(s)>0 and s[0]=='P':
s=s[1:]
n=len(s)
ans=0
pa=0
for i in range(n):
if s[i]=='A':
ans=max(pa,ans)
pa=0
else:
pa+=1
print(max(pa,ans))
|
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Mish... | 3 | s,t=input(),input()
print("YES" if sum(x!=y for x,y in zip(s,t))==2 and all(y in s for y in t) else "NO") |
You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.
Input
The first line contains integer n (1 β€ n β€ 3Β·105) β the number of points on the line.
The second line contains n integers xi ( - 109 β€ xi β€ 109) β the coordinates of the given n ... | 1 | import sys
n = int(sys.stdin.readline())
coords = sorted(map(lambda w: int(w), sys.stdin.readline().split()))
if n%2==1:
print coords[(n-1)/2]
else:
print coords[n/2-1] |
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation β of two ternary n... | 3 | tests=int(input())
nnn=[]
strings=[]
for i in range(0, tests):
nnn.append(int(input()))
strings.append(input())
for i in range(0, tests):
n=nnn[i]
string=strings[i]
big=''
small=''
flag = 0
for j in string:
if j == '2':
if flag == 0:
big+='1'
... |
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... | 3 | import string
username=str(input()).lower()
distinctchar=0
for letter in string.ascii_lowercase:
if username.count(letter)>=1:
distinctchar+=1
if distinctchar%2==0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.