problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
There are n distinct points on a coordinate line, the coordinate of i-th point equals to x_i. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset co... | 3 | N = int(input())
L = list(map(int, input().split()))
L = sorted(L)
import bisect as bi
P = []
for i in range (0, 31):
P.append(2**i)
max = 1
saved = [L[0]]
for i in range (0, N):
for j in range (0, 31):
if bi.bisect_left(L, L[i]+P[j])!=bi.bisect_right(L, L[i]+P[j]):
max = 2
s... |
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.
There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte... | 1 | def _mp():
return map(int,raw_input().split())
n=input()
arr=_mp()
n=len(arr)
a=[0]*(2*n)
a[2*n-1]=arr[0]
for i in range(1,n):
c=a[i-1]
if arr[i]-c<=a[2*n-i]:
a[i]=c
a[2*n-i-1]=arr[i]-c
else:
a[2*n-i-1]=a[2*n-i]
a[i]=arr[i]-a[2*n-i-1]
print ' '.join(str(x) for x in a) |
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.
For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.
For given n find out to which integer will Vasy... | 3 | n = int(input())
if n % 10 > 4:
print(n + (10 - n % 10))
else:
print(n - (n % 10)) |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | ################################################################
# Code Forces
# Problem - Wrong Subtraction
# 12/04/2020
# Ratings - 600
# Category - Implementation, Strings
################################################################
def main():
n = int(input())
tf = 0
for i in range(n):
nam... |
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 | x=int(input())
for j in range(x):
y=int(input())
s=input()
s1=""
s2=""
flag=0
for i in range(y):
if(flag==0):
if(s[i]=='2'):
s1+='1'
s2+='1'
elif(s[i]=='0'):
s1+='0'
s2+='0'
else:
... |
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia... | 3 | n = int(input())
s = input()
ans = 0
count = 0
for i in range(n):
if s[i] == "x":
count += 1
else:
count = 0
if count >= 3:
ans += 1
print(ans) |
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a β x) + (b β x) for any given x, where β denotes the [bitwise XOR operation](http... | 3 | t = int(input())
while t:
a, b = map(int, input().split())
c = max(a,b)
prev = (a^c) + (b^c)
while c:
if (a^c) + (b^c) < prev:
prev = (a^c) + (b^c)
c = c>>1
print(prev)
t = t-1 |
For a non-negative integer K, we define a fractal of level K as follows:
* A fractal of level 0 is a grid with just one white square.
* When K > 0, a fractal of level K is a 3^K \times 3^K grid. If we divide this grid into nine 3^{K-1} \times 3^{K-1} subgrids:
* The central subgrid consists of only black squares.
* Ea... | 3 | import sys
input=sys.stdin.readline
def dist(a,b,c,d,P3):
for p in P3:
da,ma=divmod(a,p)
dc,mc=divmod(c,p)
if da!=dc:
return abs(a-c)+abs(b-d)
if da!=1:
a,c=ma,mc
continue
db,mb=divmod(b,p)
dd,md=divmod(d,p)
if abs(db-dd)<2... |
Notes
Template in C
Constraints
2 β€ the number of operands in the expression β€ 100
1 β€ the number of operators in the expression β€ 99
-1 Γ 109 β€ values in the stack β€ 109
Input
An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.
You can assume that +... | 1 | def operate(operand0, operand1, operator):
if operator == "+":
return str(int(operand0) + int(operand1))
elif operator == "*":
return str(int(operand0) * int(operand1))
elif operator == "-":
return str(int(operand0) - int(operand1))
if __name__ == "__main__":
import sys
expr... |
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si β lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ... | 3 | from collections import Counter
n, k = map(int, input().split())
c = Counter(input()).most_common(1)
if c[0][1] <= k:
print("YES")
else:
print("NO")
|
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,... | 3 | a=int(input())
b=list()
ans=list()
b=b+[int(b) for b in input().split()]
no_stairw=b.count(1)
print(no_stairw)
no_stairw=0
for i in range(0,a):
if b[i]==1 and no_stairw==1:
ans=ans+[b[i-1]]
no_stairw=1
ans=ans+[b[a-1]]
for i in ans:
print(i,end=' ')
|
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c... | 3 | data = [int(information) for information in input().split(' ')]
j1 = data[0]
j2 = data[1]
minutes = 0
if j1 != 1 or j2 != 1:
while j1 > 0 and j2 > 0:
if j1 > j2:
minutes += 1
j2 += 1
j1 -= 2
else:
minutes += 1
j1 += 1
j2 -= 2
print(minutes)
|
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | name = input()
res = 0
cur = 97
for i in name:
distance = abs(ord(i) - cur)
if distance > 13:
distance = 26 - distance
res += distance
cur = ord(i)
print(res)
|
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 | #Puzzles.py
import sys
n, m = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
s = 0
e = n
diff = sys.maxsize
for i in range(m - n + 1):
mn = min(arr[s + i:e + i])
mx = max(arr[s + i:e + i])
#print(i, mn, mx)
if mx - mn < diff:
diff = mx - mn
print(diff) |
You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1.
A simpl... | 3 | f=200001;v=[0]*f;g=[[]for _ in[0]*f];s=[1];n,m,k=map(int,input().split())
for _ in range(m):a,b=map(int,input().split());g[b]+=a,;g[a]+=b,
while 1:
v[s[-1]]=1
for i in g[s[-1]]:
if v[i]<1:s+=i,;break
else:
t=set(g[s[-1]])
for i in range(len(s)):
if s[i]in t:exit(print(len... |
There are N integers, A_1, A_2, ..., A_N, written on a blackboard.
We will repeat the following operation N-1 times so that we have only one integer on the blackboard.
* Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.
Find the maximum possible value of the... | 3 | from copy import deepcopy
N=int(input())
A=list(map(int,input().split()))
if N==2:
print(max(A[0]-A[1],A[1],A[0]))
print(max(A[0],A[1]),min(A[0],A[1]))
quit()
A.sort()
ans=10**(-50)
S=sum(A)
for i in range(N-1):
S=S-A[i]+(-A[i])
if ans<S:
ans=S
j=i
print(ans)
for i in range(j+1,N-1):... |
You are given a special jigsaw puzzle consisting of nβ
m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | 3 | tc=int(input())
while tc>0:
row,col=map(int,input().split())
if row==1 or col==1 or (row==2 and col==2):
print("YES")
else:
print("NO")
tc-=1 |
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 | w=int(input(""))
if w!=2 and w%2==0:
print("YES")
else:
print("NO") |
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 main ():
inte = int(input())
if inte % 2==0 and inte > 2:
print("YES")
return
else:
print ("NO")
return
main()
|
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a1 Γ b1 segments large and the second one is a2 Γ b2 segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself... | 3 | a,b=map(int,input().split())
c,d=map(int,input().split())
e=a*b
f=c*d
n=0
while e%2==0:e=e//2
while e%3==0:e=e//3
while f%2==0:f=f//2
while f%3==0:f=f//3
if e!=f:print("-1")
else:
i=0
j=0
e=a*b
f=c*d
while e%3==0:
e=e//3
i+=1
while f%3==0:
f=f//3
j+=1
k=i-j
if k>0:
... |
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ... | 3 | n=int(input())
count=0
for x in range(n):
if x>=1 and x<n:
if n%x==0:
count+=1
print(count) |
There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct.
Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to onl... | 3 | import sys
from operator import itemgetter
read = sys.stdin.read
N, *ab = map(int, read().split())
mod = 10 ** 9 + 7
ab = list(zip(ab, [0] * N + [1] * N))
ab.sort(key=itemgetter(0))
remain_pc = 0
remain_power = 0
answer = 1
for x, p in ab:
if p == 0:
if remain_power == 0:
remain_pc += 1
... |
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ... | 3 | N = int(input())
X = []
H = []
for i in range(N):
x,h = map(int,input().split())
X.append(x)
H.append(h)
dp = [[1 for i in range(3)] for j in range(N)]
# 0 means straight
# 1 means left
# 2 means right
for i in range(1,N):
# Straight
if(X[i-1] + H[i-1]<X[i]):
dp[i][0] = dp[i-1][2]
else:... |
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the app... | 3 | a,b=map(int,input().split(" "))
lia,lib=[],[]
for i in range(1,a):
for j in range(1,a):
if i*i + j*j == a*a:
lia.append([i,j])
fl=0
ans="NO"
for i in range(1,b):
for j in range(1,b):
if i*i + j*j == b*b:
lib.append([i,j])
for [a,b] in lia:
for [c,d] in lib:
if... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | a=input()
x='0000000'
y='1111111'
if x in a or y in a:
print('YES')
else:
print('NO') |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 1 | def house():
d1, d2, d3 = raw_input().split()
d1 = int(d1)
d2 = int(d2)
d3 = int(d3)
op1 = (d1+d1+d2+d2)
op2 = (d1+d1+d3+d3)
op3 = (d2+d2+d3+d3)
op4 = (d1+d2+d3)
print min(op1, op2,op3,op4)
house() |
There exists an island called Arpaβs land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpaβs land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please hel... | 3 | def mod(n):
if n==0:return 1
if n==1:return 8
t = mod(n//2)%10
t = t*t%10
if n%2:t = t*8%10
return t
print(mod(int(input())))
|
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | 3 | import sys
input = lambda: sys.stdin.readline().rstrip()
arr=[]
n,m=map(int,input().split())
ans=[]
for _ in range(n):
s=[i for i in input()]
arr.append(s)
ansz=[]
for i in range(n):
src=[] ; flag=0
for k in range(m-1,-1,-1):
src.append(arr[i][k])
for j in range(i+1,n):
if arr[j]==sr... |
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.
Input
The first line of the ... | 3 | n=int(input())
a=list(map(int,input().split()))
s=0
c=0
b=[]
for i in range(len(a)):
if(a[i]%2!=0):
c+=1
b.append(a[i])
else:
s=s+a[i]
b.sort()
if(c%2==0):
for i in range(len(b)):
s=s+b[i]
else:
for i in range(1,len(b)):
s=s+b[i]
print(s) |
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
* on Mondays, Thursdays and Sundays he eats fish food;
* on Tuesdays and Saturdays he eats rabbit stew;
* on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already pa... | 3 | [a,b,c] = (input().split(' '))
a = int(a)
b = int(b)
c = int(c)
days = 0;
factor = 10000000
while factor!=1:
while a>3*factor and b>2*factor and c>2*factor:
a -= 3*factor
b -= 2*factor
c -= 2*factor
days += 7*factor
factor /= 10
while a>2 and b>1 and c>1:
a -= 3
b -= 2
... |
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.
The crossroads are represented as a string s of length n, where s_i = A, if there is... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from bisect import bisect
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(... |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 3 | a,b,*c=map(int,input().split())
print('SFeicrosntd'[a>b::2])
# Made By Mostafa_Khaled |
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit p... | 3 | for _ in range(int(input())):
n, v, l = map(int,input().split())
while n>0:
if v == 0 and l == 0:
break
elif n>=20 and v>0 or l == 0:
n = (n//2) + 10
v = v - 1
elif n<20 and l>0 or v == 0:
n = n - 10
l = l - 1
print("YES") i... |
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.
At any time Andrew can visit the store where tasty buns are sold (y... | 3 | import math
h, m = map(int,input().split())
H,D,C,N = map(int,input().split())
mn = (20-h)*60-m
if mn < 0: mn = 0
a1 = C*math.ceil(H/N)
a2 = C*0.8*math.ceil((H+mn*D)/N)
print(min(a1,a2))
|
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ
c=b.
For n β₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | 3 | import math
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
if n%2==0:
print(n+2*k)
else:
res=n
for i in range(3, int(math.sqrt(n))+1,2):
if n%i==0:
res=i
break
print(n+res+2*(k-1))
|
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())
arr = []
for i in range(0, n + 1):
s = ""
l = n - i - 1
while l >= 0:
s += " "
l -= 1
ss = ""
for k in range(0, i + 1):
ss += (str(k) + " ") if k < i else str(k)
st = ss[:-1]
ss += st[::-1]
arr.append(s + ss)
for i in range(0, len(arr)):
... |
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 | #from math import ceil
l, b = map(int, input().split())
t = 0
while l <= b:
l = 3*l
b = 2*b
t+=1
print(t)
|
You have a given integer n. Find the number of ways to fill all 3 Γ n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
<image> This picture describes when n = 4. The left one is the shape and the right one is 3 Γ n tiles.
Input
The only line cont... | 3 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 08:03:37 2019
@author: plosi
"""
def main():
n=int(input())
if n%2==1:
print(0)
else:
k=n//2
print(2**k)
main() |
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.
Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not... | 3 | for testis in range(int(input())):
a,b,k = map(int, input().split())
a_i = [0]*a
b_i = [0]*b
cur_a = list(map(int ,input().split()))
for j in cur_a:
a_i[j - 1]+=1
#count of each element in cur_a
cur_b = list(map(int, input().split()))
for j in cur_b:
b_i[j - 1]+=1
#count of every... |
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 β€ l_i β€ r_i β€ m) β coordinates of the left and of the right endpoints.
Consider... | 3 | n, m = [int(x) for x in input().split()]
arr = [True] * (m+1)
for _ in range(n):
a, b = [int(x) for x in input().split()]
for i in range(a, b+1):
arr[i] = False
res = []
for i in range(1, m+1):
if arr[i]:
res.append(i)
print(len(res))
print(*res)
|
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ... | 1 | yc,bc=map(int,raw_input().split())
yb,gb,bb=map(int,raw_input().split())
print max(0,yb*2+gb-yc)+max(0,bb*3+gb-bc) |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | a=[int(c) for c in input()]
b=[int(c) for c in input()]
#for i in range(len(a)):
# if(a[i]==0 and b[i]==0):
# a.remove(0)
# a.append(1)
r=''
for i in range(len(a)):
r=r+str(a[i]^b[i])
print(r)
|
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane,... | 3 | x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
points = [(x0, y0)]
while True:
x, y = points[-1]
if x - xs > t or y - ys >= t:
break
points.append((ax * x + bx, ay * y + by))
ans = 0
for i in range(len(points)):
xn, yn = points[i]
tn = t - abs(xs -... |
Takahashi has N blue cards and M red cards. A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.
Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will ea... | 3 | n = int(input())
b=[input() for _ in [0]*n]
m = int(input())
r=[input() for _ in [0]*m]
ans = 0
for s in set(b):
ans = max([ans,b.count(s)-r.count(s)])
print(ans) |
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...
Your task is to print the k-th digit of this sequence.
Input
The first and only lin... | 3 | import math
def countDigit(n):
return math.floor(math.log(n, 10)+1)
n=int(input())
count=countDigit(n)
if count==1:
print(n)
else:
low=1
high=9
sum=[]
digit=0
sum.append(0)
sum.append(9)
for i in range(2,16):
low=low*10
high=high*10+9
#print(countDigit(high))
sum.append((high-low+1)*i+sum[i-1])... |
You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D β₯ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | 3 | a=[]
n = int(input())
a = map(int,input().split())
a = list(a)
b=[]
for i in range(n):
if a[i] not in b:
b.append(a[i])
b =sorted(b)
if len(b) > 3:
print(-1)
elif len(b) == 3:
if b[2] - b[1] == b[1] - b[0]:
print(b[1] - b[0])
else:
print(-1)
elif len(b) == 2:
if (b[1] - b[0])... |
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster a... | 3 | from fractions import gcd
from functools import reduce
_=input()
*a,=map(int,input().split())
print(reduce(gcd,a)) |
At many competitions that have a word Β«cupΒ» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.
The nameplate is to be rectangular an... | 3 | from math import ceil
s = input()
n = len(s)
#print(n)
stro = ceil(n / 20)
stolM = ceil(n / stro)
print(stro, stolM)
pos = stro - (stolM * stro - n)
k = 0
f = stolM
sh = stolM
fl = False
#print(pos)
for i in range(stro):
#print(k, f)
if i == pos and pos != 0:
sh -= 1;
f -= 1
fl = True
... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | vowels = {'A', 'O', 'Y', 'E', 'U', 'I',
'a', 'o', 'y', 'e', 'u', 'i'}
s = input().strip()
already_replaced = []
for vowel in vowels:
s = s.replace(vowel, '')
for ch in s:
if ch not in already_replaced:
s = s.replace(ch, '.' + ch)
already_replaced.append(ch)
print(s.lower()) |
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of ... | 3 | n=int(input())
for i in range(n):
x=input()
if "".join(x[:5])=="miao." and "".join(x[-5:])=="lala.":
print("OMG>.< I don't know!")
elif "".join(x[:5])=="miao.":
print("Rainbow's")
elif "".join(x[-5:])=="lala.":
print("Freda's")
else:
print("OMG>.< I don't know!") |
Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so ... | 3 | def main():
N = int(input())
A = list(map(int, input().split()))
C = []
if max(A) + min(A) >= 0:
x = A.index(max(A))
for i in range(N):
C.append((x+1, i+1))
for i in range(1, N):
C.append((i, i+1))
else:
x = A.index(min(A))
for i in ran... |
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 | k=int(input())
n=input()
if n.count("1")==0:
print('EASY')
else:
print("HARD") |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | def main():
n, k = liee()
for i in range(k):
if n % 10:
n -= 1
else:
n //= 10
print(n)
def fun(m, n, s, k):
return
def fun2(s):
return
from sys import *
import inspect
import re
from math import *
import threading
from collections import *
from pprint im... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 |
n = int(input())
ans = 0
mx = ans
for i in range(n):
x,y = map(int,input().split())
ans = ans-x+y
mx = max(mx,ans)
print(mx)
|
Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".
Constraints
* 0 β€ a, b, c β€ 100
Input
Three integers a, b and c separated by a single space are given in a line.
Output
Print "Yes" or "No" in a line.
Examples
Input
1 3 8
Output
Yes
Input
3 8 1
Output... | 1 | a,b,c = map(int, raw_input().split())
if(a < b < c):
print("Yes")
else:
print("No") |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 1 | n,h = map(int, raw_input().split(" "))
l = map(int, raw_input().split(" "))
c = 0
for i in l:
if i > h:
c += 2
else:
c += 1
print c
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | a = input()
if len(a) > 1:
print(a[0].upper() + a[1:])
else:
print(a.upper()) |
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 | ans = 0
def run():
global ans
nums = [int(i) for i in input().split()]
tem = 0
for i in nums:
if i > 0:
tem += 1
if tem >= 2:
ans += 1
break
t = int(input())
for i in range(t):
run()
print(ans)
|
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.
Polycarp has n (2 β€ n β€ 10) bank cards, the PIN code of the i-th card is p_i.
Polycarp has recently read a recommendation that it is bette... | 3 | for _ in range(int(input())):
n = int(input())
count=0
l=[list(map(int, input())) for _ in range(n)]
#print(l)
for i in range(n):
if(l[i] in l[i+1:]):
count+=1
while(l[i] in l[i+1:]):
a=l[i][0]
l[i][0]=(l[i][0]+count)%10
if(l[i] in l[:i]):
... |
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | 3 | #import math
import random
n = int(input())
s = list(map(int, input().split()))
#s = [random.randint(1, 9) for i in range(n)]
temp = []
j = 0
s.sort()
#print(s)
for i in range(0, n, 1):
#print(i)
if(len(temp) < 10):
if(not(s[i]-1 in temp) and (s[i] - 1 > 0)):
temp.append(s[i] - 1)
... |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 3 | a, b = [int(i) for i in input().split()]
i = 0
while a > 0:
a -= 1
i += 1
if i % b == 0:
a += 1
print(i)
|
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 | tt = int(input())
def find(c,i):
l = 0
r = len(mp[c]) - 1
ret = -1
while l <= r:
m = (l+r)//2
if mp[c][m] > i:
ret = mp[c][m]
r = m - 1
else:
l = m + 1
return ret
for _ in range(tt):
s = input()
t = input()
mp = [[] for i in ran... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | #python3.7
n = int(input())
alist = []
for i in range(n):
text = input()
tstr = ''
if(len(text)>10):
tstr = text[0] + str(len(text)-2) + text[-1]
alist.append(tstr)
else:
alist.append(text)
for i in alist:
print(i)
|
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d).
Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of... | 3 | from sys import stdin, stdout
get_string = lambda: stdin.readline().strip('\n')
get_intmap = lambda: map( int, get_string().split(' ') )
#get_intmap
def ncr_generator(n,r):
ncrr = 1
while True:
yield ncrr
n += 1
ncrr = ( ncrr * n // (n - r) )
from collections import Counter
def tes... |
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy β she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.... | 3 | n = int(input())
s = []
for i in range(n):
m = input()
if s.count(m) == 0:
s.append(m)
print(len(s)) |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | nums = set(map(int,input().split()))
print(4 - len(nums)) |
You are given a sequence of length N: A_1, A_2, ..., A_N. For each integer i between 1 and N (inclusive), answer the following question:
* Find the maximum value among the N-1 elements other than A_i in the sequence.
Constraints
* 2 \leq N \leq 200000
* 1 \leq A_i \leq 200000
* All values in input are integers.
Inp... | 3 | n = int(input())
a = [int(input()) for _ in range(n)]
l = sorted(a)
for i in a:
if l[-1] == i:
print(l[-2])
else:
print(l[-1]) |
You have array of n numbers a_{1}, a_{2}, β¦, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| β€ |a_{2} - a_{3}| β€ β¦ β€ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 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... |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | 3 | from sys import stdin
A = int(stdin.readline())
for k in range(0, A):
B = list(map(int, stdin.readline().split()))
sum = 0
C = list(map(int, stdin.readline().split()))
# B[0]=n
# B[1]=x
LIST=list()
K=0
for t in range(0, B[0]):
if C[t]%B[1]!=0:
LIST.append(t)
... |
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ... | 3 | def get(line):
if len(line) == 1:
return line
a = line.index(min(line))
if a == 0:
return [line[0]] + get(line[1:])
return [line[a]] + line[:a - 1] + get([line[a - 1]] + line[a + 1:])
for _ in range(int(input())):
n = int(input())
line = list(map(int, input().split()))
prin... |
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())
i = 1
temp = 0
while True:
if k*i <=n and k*i > y:
temp = 1
print(abs(y - k*i),end = ' ')
elif k*i>n:
break
i+=1
if temp == 0:
print(-1)
|
Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.
Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to sat... | 3 |
class Node:
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
def insert(T, z):
y = None
x = T
while x is not None:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.pa... |
The process of mammoth's genome decoding in Berland comes to its end!
One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is... | 1 | n=int(raw_input())
s=raw_input()
a=""
if n%4!=0: print "==="
else:
count={"A":n/4, "G":n/4, "C":n/4, "T":n/4}
isValid=True
for i in xrange(n):
if s[i] != "?":
count[s[i]]-=1
if count[s[i]]<0: isValid=False
if not isValid:
print "==="
else:
ans=""
for i in xrange(n):
if s[i]==... |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | a='hello'
b=c=0
d=input()
while (c<len(d))&(b<5):
if d[c]==a[b]:b+=1
c+=1
if b==5:print('YES')
else:print('NO') |
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse... | 3 | n, m = map(int, input().split())
arr = list(map(int, input().split()))
d = set(map(int, input().split()))
ans = []
for el in arr:
if el in d:
ans.append(el)
print(' '.join(map(str, ans)))
|
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 | import math
#------------------------------warmup----------------------------
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 f... |
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maxi... | 3 | n = int(input())
d = [int(x) for x in input().split()]
d.sort()
m = 0
#print(d)
k = 1
for i in range(n-1):
for j in range(k, n):
#print(i,j)
if d[j] - d[i] > 5:
break
if j - i > m:
m = j - i
#print(i, j, m)
else:
break
k = j
print(m+1... |
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | borze = input()
length = len(borze)
i = 0
result = ""
while i < length:
if borze[i] == '.':
result = result + '0'
i = i + 1
elif borze[i] == '-':
if borze[i+1] == '.':
result = result + '1'
else:
result = result + '2'
i = i + 2
print(result) |
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 | n = int(input())
s = 0
for i in range(n):
a1, a2, a3 = [ int(x) for x in input().split()]
if a1 + a2 + a3 > 1:
s += 1
print(s)
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
length = inp()
for i in range(length):
word = input().strip()
print('{}'... |
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in th... | 3 | s = input()
symv = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
symdict = {}
for i in range(len(symv)):
symdict[symv[i]] = i
word = []
for i in range(len(s)):
if not s[i] in symv:
symdict[s[i]] = len(symv)
symv.append(s[i])
wor... |
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
c = 0
for i in range(n - 1):
if(a[i] == a[i + 1]):
c+=1
if(c != n - 1):
print(1)
else:
print(n) |
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is... | 3 | kol,time,rest=input().split()
kol=int(kol)
time=int(time)
rest=int(rest)
ans=0
left=0
middle=0
for i in range(1, kol+1):
t1,t2=input().split()
t1=int(t1)
t2=int(t2)
middle=t1-left
ans=(middle//rest)+ans
left=t1+t2
ans=ans+(time-left)//rest
print(ans)
|
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | from collections import defaultdict
import bisect
from math import ceil
for _ in range(int(input())):
n,x=map(int,input().split())
c=2
ans=0
while(n>0):
n-=c
ans+=1
c=x
print(ans)
|
"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,m=map(int,input().split())
mark=list(map(int,input().split()))
p=0
for i in mark:
if i>=mark[m-1] and i>0:
p+=1
print(p) |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n = int(input())
p = []
q = []
for _ in range(n):
a, b = map(int, input().split())
p.append(a)
q.append(b)
ans = 0
for i in range(n):
if q[i]-p[i] >= 2:
ans += 1
print(ans)
|
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | import math
n=int(input())
s=list(map(int,input().strip().split()))[:n]
s.sort(reverse=True)
sum_of_list=0
count=0
if 1 not in s and 2 not in s:
count+=s.count(4)
count+=s.count(3)
elif 1 not in s and 2 in s:
count+=s.count(4)
count+=s.count(3)
count+=math.ceil(s.count(2)*2/4)
elif 1 in s and 2 not ... |
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain?
Constraints
* 1 \leq |A| \leq 200... | 3 | from collections import Counter
a = input()
n = len(a)
c = Counter(a)
# print(c.keys())
tp = 0
for val in c.values():
tp += (val*(val-1))//2
print((n*(n-1)//2)-tp+1)
|
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold:
* For any pair of integers (i,j), if i and j are coprime, a_i β a_j.
* The maximal value of all a_i should be minimized (that is, as small as possible).
A pair of integers is call... | 1 | n = int(raw_input())
a = [0 for i in xrange(n + 1)]
c = 0
for i in xrange(2, n + 1):
if a[i] > 0:
continue
c += 1
for j in xrange(i, n + 1, i):
if a[j] == 0:
a[j] = c
print " ".join(map(str, a[2:])) |
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.
Limak, a polar bear, lives on the N... | 1 | from sys import stdin
rstrs = lambda: [str(x) for x in stdin.readline().split()]
point, n = 0, int(input())
arr = [rstrs() for _ in range(n)]
for x, d in arr:
if d == 'North':
if point:
point -= int(x)
else:
point = 1
break
elif d == 'South':
if poi... |
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input
The first line contains t... | 1 | f=lambda:map(int,raw_input().split())
x,y=f()
k,m=f()
A=f()
B=f()
print ['NO','YES'][A[k-1]<B[y-m]]
|
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
Input
The first and the single line contains three space-separated integers β the areas of the parallelepi... | 3 | import math
s1,s2,s3 = map(int,input().split())
c = math.sqrt(s2*s3//s1)
b = math.sqrt(s1*s3//s2)
a = math.sqrt(s1*s2//s3)
print(int(4*(a+b+c))) |
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β₯ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subar... | 3 | import math
from operator import itemgetter
x = list(map(int, input().split()))
y = list(map(int, input().split()))
ii = x[0]
jj = x[1]
c = []
for i in range(ii-1):
c.append([i, y[i+1]-y[i]])
c.sort(key=itemgetter(1), reverse=True)
X = 0
for i in range(jj-1):
X = X + c[i][1]
print(+max(y)-min(y)-X) |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 β€ i, j β€ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | def RA():
return list(map(int, input().split()))
def solve():
n, k = RA()
a = RA()
b = RA()
a.sort()
b.sort(reverse=True)
for i in range(k):
if a[i] >= b[i]:
break
a[i] = b[i]
print(sum(a))
t = int(input())
for i in range(t):
solve() |
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.
Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in mu... | 3 | #-*-coding:utf8;-*--p
#qpy:3
#qpy:console
import sys
n, k, m = map(int, input ().split(' '))
a = map(int, input ().split(' '))
b = {i:[] for i in range(0, m)}
for i in a:
b[i%m].append(i)
for v in b.values():
if len(v) >= k:
print("Yes")
s = ''
for i in range(k):
s += s... |
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 β
n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | 3 | import math
for _ in range(int(input())):
print((1/((math.tan(math.pi/(2*int(input()))))*2))*2) |
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa... | 1 | n,m=map(int,raw_input().split())
t=''
for i in xrange(n):
s=raw_input()
for j in xrange(m):
if(s[j]=='.'):
if((i+j)%2==0):
t+='B'
else:
t+='W'
else:
t+=s[j]
i=0
while(i<n*m):
print t[i:i+m... |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | 3 | s=str(input())
x=s[::-1]
s+=x
print(s) |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n,h=map(int,input().split())
l=list(map(int,input().split()))
c=0
for i in range(n):
if l[i]<=h:
c+=1
else:
c+=2
print(c) |
Mislove had an array a_1, a_2, β
β
β
, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | 3 | n,l,r=map(int,input().split())
mi=0
c=0
for i in range(l,1,-1):
mi+=pow(2,i-1)
c+=1
c=n-c
mi+=c
ma=0
c=0
for i in range(r-1):
ma+=pow(2,i)
c+=1
c=n-c
ma+=(pow(2,r-1))*c;
print(mi,ma) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.