problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0.
You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 Γ 2, and replace every element in the chosen sub... | 3 | #Ashish Sagar
#q=int(input())
q=1
for _ in range(q):
n,m=map(int,input().split())
A=[]
for i in range(n):
a=list(map(int,input().split()))
A.append(a)
ans=[]
B=[[0]*m for i in range(n)]
for i in range(n-1):
for j in range(m-1):
if A[i][j]+A[i][j+1]+A[i+1][j]+A... |
Now you get Baby Ehab's first words: "Given an integer n, find the longest subsequence of [1,2, β¦, n-1] whose product is 1 modulo n." Please solve the problem.
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal ... | 3 | import math
n=int(input())
modulo = []
p = 1
for i in range(1,n):
if math.gcd(i,n)==1:
p=(p*i)%n
modulo.append(i)
#print(p)
if p%n==1:
print(len(modulo))
for i in modulo:
print(i,end=' ')
else:
z=p%n
print(len(modulo)-1)
for i in modulo:
if i!=z:
print(i,end=' ')
|
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.
The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.
Input
The first line of the input ... | 3 | n = int(input())
print(n * (n + 1) // 2 % 2) |
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | def matgame(mat,n,m):
row = [1 for _ in range(n)]
col = [1 for _ in range(m)]
for i in range(n):
for j in range(m):
if mat[i][j] == 1:
row[i] = 0
col[j] = 0
res = min(sum(row),sum(col))
if res%2 == 0:
print("Vivek")
else:
print("Ashish")
if __name__ == "__main__":
t = int(inp... |
In this problem we consider a very simplified model of Barcelona city.
Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal... | 3 | a,b,c=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
bRange=abs(y2-y1)+abs(x2-x1)
if a==0 or b==0:
print(bRange)
else:
px1=(-b*y1-c)/a
px2=(-b*y2-c)/a
py1=(-a*x1-c)/b
py2=(-a*x2-c)/b
pRange1=((x2-px1)**2+(py2-y1)**2)**0.5+abs(px1-x1)+abs(py2-y2)
pRange2=((x2-x1)**2+(py2-py1... |
Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, β¦, l_m (1 β€ l_i β€ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number ... | 3 | def IntInput(): return int(input())
def M_IntInput(): return map(int,input().split())
def M_StrInput(): return map(int,input().split())
def IntArrayInput(): return list(map(int,input().split()))
def modInverse(p,a,m): return ((p%m)*pow(a%m,m-2,m))%m
# -----------------------Anshul Raj------------------------ #
n,m = ... |
A permutation of length n 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 in the array).
For a positive integer n, we call a... | 3 | for z in range(int(input())):
n=int(input())
arr=[x for x in range(1,n+1)]
print(*arr) |
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 3 | n=int(input())
ans1=n//2
nof2=0
print(ans1)
rem=n%2
if rem!=0:
nof2=ans1-1
for i in range(nof2):
print("2",end=" ")
print("3")
elif rem==0:
nof2=ans1
for i in range(nof2):
print("2",end=" ")
|
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 β₯ p_2 β₯ ... β₯ p_n.
Help the jury distrib... | 3 | def find_medalist(c_ps_sorted, n):
total = 0
included = []
while c_ps_sorted and total+c_ps_sorted[-1][1] <= n//2:
total += c_ps_sorted[-1][1]
included.append(c_ps_sorted.pop())
included.reverse()
return included
def medalist_numbers(included):
try:
gold = included.pop(... |
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ... | 3 | n,m=[int(x) for x in input().split()]
if n-m>1 or m>2*n+2:
print(-1)
else:
if n>m:
print('0',end='')
print('10'*(n-1))
elif m>2*n:
if m%2:
print('1',end='')
m-=1
else:
print('11',end='')
m-=2
m//=2
print('011'*m)... |
This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.
Polycarp likes to play computer role-playing game Β«Lizards and BasementsΒ». At the moment he is playing it as a magician. At one of the las... | 3 | #!/usr/bin/env python
def main():
n, a, b = map(int, input().split())
health = [0]
health.extend(map(int, input().split()))
target = [0] * len(health)
def need(t, d):
nonlocal health
p = health[t]
return (p // d + 1) if p >= 0 else 0
least_target = []
least_thrown... |
You are given n strings a_1, a_2, β¦, a_n: all of them have the same length m. The strings consist of lowercase English letters.
Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
li=[]
for i in range(n):
li.append(list(input()))
ansli=[]
for i in range(n):
ans=li[i].copy()
for j in range(m):
for zz in range(n):
tem=ans.copy()
tem[j]=li[zz][j]
... |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | from sys import stdin, stdout
"""
n = stdin.readline()
arr = [int(x) for x in stdin.readline().split()]
stdout.write(str(summation))
"""
fibo = [0,1,1]
while fibo[-1]<=1000000000 :
fibo.append(fibo[-1]+fibo[-2])
for test in range(int(stdin.readline())):
arr = [int(x) for x in stdin.readline().split... |
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())
count = 0
max_count = 0
for i in range(n):
vihod, vhod = map(int, input().split())
count -= vihod
count += vhod
if count >= max_count:
max_count = count
print(max_count)
|
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n = int(input())-1
a = input()
c = 1
for i in range(n):
b = input()
if a[1] == b[0]:
c += 1
a = b
print(c) |
For given three integers $a, b, c$, print the minimum value and the maximum value.
Constraints
* $-1,000,000,000 \leq a, b, c \leq 1,000,000,000$
Input
The input is given in the following format.
$a \; b \; c\;$
Three integers $a, b, c$ are given in a line.
Output
Print the minimum and maximum values separate... | 3 | a = list(map(int, input().split()))
print('%d %d' % (min(a), max(a)))
|
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | 3 | from sys import stdin, stdout
from math import log10
from decimal import Decimal
a, b = map(Decimal, stdin.readline().split())
a, b = b * Decimal(log10(a)), a * Decimal(log10(b))
if a > b:
stdout.write('>')
elif a < b:
stdout.write('<')
else:
stdout.write('=') |
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())
decisions = []
for i in range(n):
decision = list(map(int, input().strip().split()))
if sum(decision) > 1:
decisions.append(1)
print(sum(decisions)) |
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can b... | 3 | n = int(input())
s = input()
z = 0
for i in range(n):
if s[i] == '-':
if z > 0: z=z-1
else: z=z+1
print(z) |
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present β the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to d. It is guaranteed that ai β€ d for all i from 1 to n. The clock does not keep information ab... | 3 | d=int(input())
n=int(input())
arr=list(map(int,input().split()))
c=0
for i in arr[:n-1]:
c=c+d-i
print(c) |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
m,n = [int(x) for x in input().split()]
if m*n == 1:
print(0)
else:
a = max(m,n)
x = a//2
r = a%2
print(x*(m+n-a)+r*((m+n-a)//2))
|
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | 3 | n=int(input())
print(22*n,21*n) |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n = int(input())
s =""
for i in range(1,n+1):
if(i%2!=0):
if(i!=n):
s+="I hate that "
else:
s+="I hate it"
else:
if(i!=n):
s+="I love that "
else:
s+="I love it"
print(s) |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | a = input()
b = input()
c = input()
check=False
C=[]
for i in c:
C.append(i)
for i in a:
if i in C:
C.remove(i)
else:
check=True
break
for i in b:
if i in C:
C.remove(i)
else:
check=True
break
if check or len(C)!=0:
print("NO")
else:
print("YES... |
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 | m,n=map(int,input().split())
while n>0:
if m%10!=0:
m=m-1
else:
m=m//10
n-=1
print(m) |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 3 | n=int(input())
a=0
b=1
c=1
s=2
while s<n:
a=b
b=c
c=s
s=c+b
if s==n:
print(a,b,b)
elif n==0:
print("0 0 0")
elif n==1:
print("0 0 1")
else:
print("I'm too stupid to solve this problem") |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | a = int(input())
p=0
for i in range(a):
b = input()
m = list (b)
if m[1] == "+":
p+=1
else:
p-=1
print (p)
|
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, w... | 3 | import sys
input = sys.stdin.readline
from collections import deque
nn = 202020
mod = 10 ** 9 + 7
fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
fa[i+1] = fa[i] * (i+1) % mod
fainv[-1] = pow(fa[-1], mod-2, mod)
for i in range(nn)[::-1]:
fainv[i] = fainv[i+1] * (i+1) % mod
C = lambda a, b: fa[a] *... |
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan... | 3 | n = int(input())
s = input()
best, ans = n, None
for p in ('RGB', 'RBG', 'GRB', 'GBR', 'BRG', 'BGR'):
t = p * ((n + 2) // 3)
c = sum(x != y for x, y in zip(s, t))
if c < best:
best = c
ans = t[:n]
print(best, ans, sep='\n') |
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.
Input
The only line contains three integers n, a and ... | 3 | n,a,b=map(int,input().split())
cnt=0
cnt1=0
while(True):
if a<n:
cnt+=1
else:
break
if b>0:
cnt1+=1
else:
break
a+=1
b-=1
print(max(cnt,cnt1)) |
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers pi (1 β€ i β€ k), such that
1. 1 β€ k β€ 3
2. ... | 3 | def mp(): return map(int,input().split())
def lt(): return list(map(int,input().split()))
def pt(x): print(x)
def ip(): return input()
def it(): return int(input())
def sl(x): return [t for t in x]
def spl(x): return x.split()
def aj(liste, item): liste.append(item)
def bin(x): return "{0:b}".format(x)
def print... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | x = int(input())
# (n+4) // 5
if x % 5 == 0:
print(x//5)
else:
print(x//5 + 1) |
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 math import *
t=int(input())
for i in range(t):
n,x=map(int,input().split())
if n==1:
print(1)
else: print(ceil((n-2)/x)+1) |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 1 | import sys
class FoxAndSnake:
def solve(self,n,m):
for x in range(1,n+1):
for y in range(1,m+1):
if x%2==1:
sys.stdout.write("#")
sys.stdout.flush()
elif x%4==0 and y==1:
sys.stdout.write("#")
... |
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 | long_string =input()
print(long_string[0].upper()+long_string[1:]) |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | for i in range(int(input())):
a, b, n = map(int, input().split())
count = 0
a, b = min(a, b), max(a, b)
while max(a, b) <= n:
a += b
count += 1
a, b = min(a, b), max(a, b)
print(count)
|
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | s,n=[int(x) for x in input().split()]
ls= [tuple(map(int,input().split())) for i in range(n)]
ls=sorted(ls)
for tup in ls:
if s>tup[0]:
s+=tup[1]
else:
print('NO')
break
else:
print("YES")
|
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... | 1 | input1 = int(raw_input())
num_available = 0
for i in range(input1):
input2 = map(int, raw_input().split())
a = input2[0]
b = input2[1]
if b-a >= 2:
num_available += 1
print num_available
|
Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.
To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of... | 3 | print("YES" if sorted(input().split()) == ["5", "5", "7"] else "NO")
|
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied:
For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th... | 3 | n = int(input())
nsum = n*(2*n+1)//2
if n % 2 == 0:
print("NO")
else:
print("YES")
odds = []
evens = []
for i in range(n):
odds.append(2*i+1)
evens.append(2*i+2)
for i in range(n//2):
temp = odds[2*i+1]
odds[2*i+1] = evens[2*i+1]
evens[2*i+1] = temp
... |
Takahashi has two positive integers A and B.
It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).
Constraints
* 2 β€ N β€ 10^5
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Outp... | 3 | a=sum(int(i)for i in input());print(10if a==1else a) |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | import sys
t = int(input())
ans = []
for line in sys.stdin.readlines():
n = int(line)
if n % 4 != 0:
ans.append('NO\n')
continue
result = list(range(2, n + 1, 2)) + list(range(1, n - 1, 2)) + [n + n // 2 - 1]
ans.append('YES\n')
ans.append(' '.join(map(str, result)) + '\n')
print('... |
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible num... | 3 | #n junctions m roads
#start at s and finish at t
n,m,s,t=map(int,input().split())
from collections import defaultdict
d=defaultdict(list)
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
d[a].append(b)
d[b].append(a)
def calc(d,s,t):
# print(d)
dist=[10**9]*n
vis=[0]*n
... |
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 | t=int(input())
i=0
x=[]
while(i<t):
s=str(input())
if len(s)<=10:
x.append(s)
else:
x.append(str(s[0])+str(len(s)-2)+str(s[len(s)-1]))
i+=1
for i in range(len(x)):
print(x[i]) |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | t=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
a.sort()
b.sort()
count=0
for i in range(0,len(a)):
j=0
while j<len(b):
if abs(a[i]-b[j])<=1:
b.pop(j)
count+=1
break
elif abs(a[i]-b[j])>1:
... |
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.
On this sequence, Snuke can perform the following operation:
* Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.... | 3 | [print(int((n[0] - 2) / (n[1] - 1) + 1)) for n in [list(map(int, input().split()))]] |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | # ip = open("testdata.txt", "r")
# def input():
# return ip.readline().strip()
from collections import Counter
n = int(input())
s = input()
counter = Counter(s)
if counter['A'] > counter['D']:
print('Anton')
elif counter['A'] < counter['D']:
print('Danik')
else:
print('Friendship') |
Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms:
* Everyone must gift as many coins as others.
* All coins given to Ivan must be different.
* Not l... | 3 | n, m, k, l = map(int, input().split())
if k + l > n:
print(-1)
else:
x = (k + l) // m + (1 if (k + l) % m != 0 else 0)
if x * m > n:
print(-1)
else:
print(x)
|
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number... | 3 | import sys
#from collections import defaultdict
#from collections import Counter
#import math
#from fractions import Fraction
#import heapq
from bisect import bisect_left
def main():
def GCD(x, y):
while (y):
x, y = y, x % y
return x
def lcm(a,b):
return (a*b)//GCD(a,b)
... |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | s,n=input().split()
s=int(s)
n=int(n)
t=[]
for i in range(n):
x,y=input().split()
x=int(x)
y=int(y)
t.append((x,y))
t=sorted(t)
q=[]
for i in t:
if i[0]<s:
s=s+i[1]
else:
print('NO')
q.append('1')
break
if len(q)==0:
print('YES')
|
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 | for i in range(int(input())):
s = input()
if len(s) <= 10:
print(s)
else:
a = len(s)-2
print(s[0]+str(a)+s[-1]) |
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 1 | n = int(raw_input())
print 'I become the guy.' if len(set(map(int, raw_input().split()[1:])).union(set(map(int, raw_input().split()[1:])))) == n else 'Oh, my keyboard!'
|
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of... | 1 | #####################################
import atexit, io, sys , collections
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
#####################################
def f(source , target , cc):
if len(target) < len(source): return False
i = 0
for... |
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed... | 1 | l,r,k = map(int,raw_input().split())
ans = [str(k**i) for i in range(64) if l<=k**i<=r]
if len(ans) == 0:
print -1
else:
print ' '.join(ans)
|
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following n days. For each day sales manager... | 1 | import operator
n,f = map(int, raw_input().split(" "))
k = []
l = []
# sum_ = 0
a = []
b = {}
for i in xrange(n):
ki,li = map(int, raw_input().split(" "))
k.append(ki)
l.append(li)
# sum_+=min(ki,li)
if li>ki:
a.append(i)
b[i] = min(li, ki*2) - min(li, ki)
i = 0
sorted_x = sorted(b.... |
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl... | 3 | def Min(a,b):
if a < b:
return a
else:
return b
def Max(a,b):
if a > b:
return a
else:
return b
s = input()
l,r,a = s.split()
l = int(l)
r = int(r)
a = int(a)
mn = Min(l,r)
mx = Max(l,r)
mn += a
if mn < mx:
print(mn*2)
else:
if (mn+mx)%2 == 1:
print(mn+mx-... |
Link to Russian translation the problem
You are given a number N. How many zeroes does N! end on?
Input
The first line contains one integer T - number of test cases.
The following T lines contain one integer each - N.
Output
For each test case output one integer per line - the answer for this question.
Constraints
... | 1 | #!/usr/bin/python
'''
from math import factorial as f
N=int(raw_input())
if 1 <= N <= 1000:
for i in range(N):
num=int(raw_input())
v=str(f(num))
c=0
for num in v[::-1]:
if(num!='0'):
break
else:
c+=1
print c
'''
N=int(raw_input())
if 1 <= N <=... |
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to... | 1 | n, m = map(int, raw_input().split())
g = [ [0] * (n+1) for i in xrange(n+1) ]
for i in xrange(m):
a, b = map(int, raw_input().split())
g[a][b] = 1
g[b][a] = 1
#print g
ans = [0] * (n+1)
for i in xrange(1, n+1):
if ans[i] == 0:
t = [j for j in xrange(1, n+1) if g[i][j] == 0 and i != j]
#... |
You are given an array a consisting of n integers.
Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.
Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c... | 3 | '''def palindrome(a, n):
for i in range(n):
for j in range(i+2, n):
p1, p2 = i, j
while p2 >= p1:
if a[p1] == a[p2]:
p2 -= 1
p1 += 1
else: break
if p1 >= p2: return 'Yes'
return 'No'
T = int(inpu... |
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | 3 | v=int(input())
x = [None] * v
for i in range(v):
x[i] = list(map(int, input().split()))
x=sorted(x)
if any(x[i][1] > x[i+1][1] for i in range(v-1)):
print("Happy Alex")
else:
print("Poor Alex")
|
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.
At least how many sheets of paper does he need?
Constraints
* N is an integer.
* 1 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the a... | 3 | N = int(input())
ans = -(-N // 2)
print(ans) |
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... | 1 |
# Author : raj1307 - Raj Singh
# Date : 27.10.2020
from __future__ import division, print_function
import os,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 ii(): return int(input())... |
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.
The scales is in equilibrium ... | 3 | s = input()
t = input()
l,p = s.split('|')
dl,dp,dt = len(l),len(p),len(t)
x = abs(dl-dp)
if x > dt :
print("Impossible")
else:
y = dt - x
if y%2 == 1:
print("Impossible")
else:
y//=2
xx = t[:(x+y)]
yy = t[(x+y):]
if dl < dp:
l = l+xx
p = p+yy
else :
p = p+xx
l = l+yy
print(l,'|',p,sep="")... |
You will be given a contest schedule for D days. For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.
Input
Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.
D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,... | 3 | D = int(input())
C = list(map(int, input().split()))
s = list()
for i in range(D):
s1 = list(map(int, input().split()))
s.append(s1)
t = list()
for i in range(D):
N = int(input())
t.append(N-1)
done = [0] * 26
ans = 0
for d in range(1, D+1):
td = t[d-1]
done[td] = d
ans += s[d-1][td]
for i in range(26)... |
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting o... | 3 | n=int(input())
l=input().split()
li=[int(i) for i in l]
li.sort()
num1=sum(li[0:n//2])
num2=sum(li)-num1
print(num1**2+num2**2) |
Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).
He is dividing the problems into two categories by choosing an integer K, as follows:
* A problem with difficulty K or higher will be for ... | 3 | m = int(input()) // 2
a = sorted(map(int, input().split()))
print(a[m] - a[m - 1])
|
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | # Author : devil9614 - Sujan Mukherjee
from __future__ import division, print_function
import os,sys
import math
import collections
from itertools import permutations
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, ... |
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.
Across all the sets Misha scored a points ... | 3 | k, a, b = map(int, input().split())
ans = a // k + b // k
if ans:
if a % k and b // k == 0:
print(-1)
elif b % k and a // k == 0:
print(-1)
else:
print(ans)
else:
print(-1) |
You are given a rectangular cake, represented as an r Γ c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 Γ 4 cake may look as follows:
<image>
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain... | 3 | num_rows, num_columns = map(int, input().split())
non_empty_rows = set()
non_empty_cols = set()
for num_row in range(1, num_rows + 1):
row = input()
for num_column, char in enumerate(row, start=1):
if char == 'S':
non_empty_rows.add(num_row)
non_empty_cols.add(num_column)
num_emp... |
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | 1 | n=int(raw_input())
#n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
if len(a)==1:
if a[0]==15:
print 'DOWN'
elif a[0]==0:
print 'UP'
else:
print -1
elif a[-2]>a[-1] and a[-2]!=1:
print 'DOWN'
else:
if a[-2]==14:
print 'DOWN'
else:
print 'UP... |
The chef has just finished baking several pies, and it's time to place them on cooling racks.
The chef has exactly as many cooling racks as pies. Each cooling rack can only hold one pie, and each pie may only be held by one cooling rack,
but the chef isn't confident that the cooling racks can support the weight of the... | 1 | t=int(raw_input())
for i in xrange(0,t):
np=int(raw_input())
P=map(int,raw_input().split())
R=map(int,raw_input().split())
count=0
while np!=0:
mr=max(R)
mp=max(P)
if mr>mp or mr==mp:
count+=1
np-=1
R.remove(mr)
... |
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 ... | 1 | a=int(raw_input())
m=0
ans=0
for i in range(a):
b=raw_input()
c=b.split(' ')
m-=int(c[0])
m+=int(c[1])
if m>ans:
ans=m
print ans
|
There are N integers a_1, a_2, ..., a_N not less than 1. The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.
Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.
Constraints
* 1 \leq N \leq 10^{12}
* 1 \leq P \leq 10^{12}
Input
Input is... | 3 | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
N,P = map(int,input().split())
f = []
x = 2
while x*x <= P:
if P%x == 0:
f.append(x)
P //= x
continue
x += 1
if P > 1:
f.append(P)
from collections import Counter
counter = Counter(f)
answer = 1
for p,k in coun... |
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 | def solve():
n = int(input())
s = input()
ans = 0
count = 0
for i in range(n):
if s[i] == 'x':
count += 1
if count > 2:
ans += 1
else:
count = 0
print(ans)
solve() |
Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score a and Lexa starts with score b. In a single turn, both Memory and Lexa get some integer in the range [ - k;k] (i.e. one integer among - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k) and add... | 3 | mod=10**9+7
f=[0]*500000
def POW(a,b):
if(b==0):
return 1
if(b&1):
return POW(a,b//2)**2*a%mod
else:
return POW(a,b//2)**2
def C(n,m):
if(m>n):
return 0
t=f[n]*POW(f[m],mod-2)%mod*POW(f[n-m],mod-2)%mod
return t
f[0]=1
for i in range(1,500000):
f[i]=f[i-1]*i%mod
a,b,k,t=map(int,input().split(' '))
an... |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 |
x = [int(x) for x in input().split()]
x.sort(reverse = True)
a = x[0] - x[1]
b = x[0] - x[2]
c = x[0] - x[3]
print(a , b , c) |
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 β€ m β€ cntn), where cntn... | 1 | from sys import stdin
n, m = map(int, stdin.readline().split())
a = []
num = m-1
i = n
while i>1:
a.append(num/(2**(i-2)))
num = num%(2**(i-2))
i -= 1
ans = [1]
for item in a[::-1]:
for i in xrange(len(ans)):
ans[i] += 1
if item == 1:
ans.append(1)
else:
ans.insert(0, 1... |
You are given two integers n and k.
Your task is to construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minim... | 3 | def A():
alphabet = "abcdefghijklmnopqrstuvwxyz"
t = int(input())
s = []
for i in range(t):
nk = input().split()
n , k = int(nk[0]) , int(nk[1])
s_i = ""
for i in range(n): s_i+= alphabet[i%k]
s.append(s_i)
for s_i in s: print(s_i)
A() |
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 3 | from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime-----... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | x=int(input())
z=0
for i in range(x):
y=input()
if(y[1]=='+'):
z+=1
else:
z-=1
print(z)
|
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is ... | 3 | a = input()
#a=list(a)
ant,pos =0,0
h=[]
j =-1
used_ant =0
used_post =1
ti=0
while a[ti]!="^":
ti+=1
for x in range(0,len(a)):
if j == -1 and a[x]!="^":
if a[x]!="=":
ant+= int(a[x])*(ti-used_ant)
used_ant+=1
else:
used_ant+=1
... |
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | n=int(input())
a=list(map(int,input().strip().split()))[:n]
x=min(a)
y=max(a)
c=0
for i in range(0,n):
if a[i]>=x and a[i]<=y:
c=c+1
c=((y-x)-c+1)
print(c)
|
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this ... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
import math
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():
n,q=map(int,input().split())
... |
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one β into b pieces.
Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plat... | 3 | n,a,b=map(int,input().split())
ans=1
for i in range(1,min((n//2)+1,a)):
l,r=i,n-i
piece=a//l
piece=min(piece,b//r)
ans=max(ans,piece)
l,r=r,l
piece=a//l
piece=min(piece,b//r)
ans=max(ans,piece)
print(ans) |
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep".
Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.
In Shapur's opinion the weaknes... | 1 | def fast2():
import os, sys, atexit
from cStringIO import StringIO as BytesIO
# range = xrange
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
class order_tree:
def __init__(self, n):
self.t... |
Ringo found a string s of length n in his [yellow submarine](https://www.youtube.com/watch?v=m2uTFF_3MaA). The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string s into a palindrome by applying two types of operations to the stri... | 3 | s=input()
n=len(s)
l=[]
print(3)
print('R',2)
print('L',n)
print('L',n-1) |
Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 Γ 3 grid (one player always draws crosses, the other β noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the g... | 1 | import sys
board = "".join(sys.stdin.readlines()).strip()
num_xs = board.count('X')
num_os = board.count('0')
win_a = """CCC
###
###
"""
win_b = """C##
C##
C##
"""
win_c = """C##
#C#
##C
"""
win_d = """#C#
#C#
#C#
"""
win_e = """##C
#C#
C##
"""
win_f = """###
CCC
###
"""
win_g = """###
###
CCC
"""
win_h = """#... |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | import sys
input=sys.stdin.readline
A=[]
for i in range(2,31):
A.append((2**i)-1)
T=int(input())
for _ in range(T):
n=int(input())
for i in A:
if (n%i==0):
x=n//i
break
print(x)
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | n,m,a=[int(i) for i in input().split()]
if n%a==0:
k=n//a
else:
k=(n//a)+1
if m%a==0:
l=m//a
else:
l=(m//a)+1
print(l*k)
|
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | for _ in range(int(input())):
s=input()
l=s[-1]
s=s[:-1]
k=''
for i in range(0,len(s),2):
k+=s[i]
k+=l
print(k)
|
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segment... | 3 | from sys import stdin as fin, setrecursionlimit as srl
# fin = open("hcc2016d1.in", "r")
debug = False
def process():
r, c = map(int, fin.readline().split())
emp = [True] * c
for j in range(r):
row = fin.readline().rstrip()
for i in range(c):
if row[i] == 'B':
em... |
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two ch... | 3 | n,a,b = (int(i) for i in input().split())
ans = [[0 for i in range(b)] for j in range(a)]
if n>a*b:
print(-1)
else:
k = 1
for i in range(a):
for j in range(b):
if n == 0 :
break
else:
ans[i][j] = k
k+=1
n-=1
... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n=int(input())
out=""
while n>=2:
out+="I hate that I love that "
n-=2
if n:
out += "I hate it"
else:
out=out[:-6]
out+=" it"
print(out) |
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY)
A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location... | 3 | import sys
import math
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n,s,k=map(int,input().split())
arr=list(map(int,input().split()))
ac=dict()
for i in range(k):
ac[arr[i]]=1
lower=s
flag1=0
while(lower>0):
if(lower not in ac.keys()):
flag1=1
... |
You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.
You must paint a fence which consists of 10^{100} planks in two colors in the following way (suppose planks are numbered from ... | 3 | import math
def case():
r, b, k = map(int, input().split())
r, b = min(r, b), max(r, b)
g = math.gcd(r, b)
if math.ceil((b-g)/r) >= k:
print('REBEL')
else:
print('OBEY')
for _ in range(int(input())):
case() |
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 | for _ in range(input()):
x = raw_input()
a = len(x)
if a > 10:
print x[0] + str(a - 2) + x[a - 1]
else:
print x + '\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.... | 3 | #!/usr/bin/python3
matrix = []
n = 5
center_pos = 2
count = 0
for _ in range(n):
matrix.append(list(map(int, input().split())))
for i in range(n):
if 1 in matrix[i]:
# row movement
count += abs(center_pos - i)
for index, j in enumerate(matrix[i]):
if j == 1:
... |
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())
m=input()
s=m.lower()
s=set(s)
x=len(s)
if x >= 26:
print("YES")
else:
print("NO")
|
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.... | 3 | fila = 0
while True:
entrada = input()[::2]
if '1' in entrada:
print(abs(fila - 2) + abs(entrada.index("1") - 2))
break
fila += 1 |
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:
XX XX .X X.
X. .X XX XX
Bishwocks don't attack any squares and can even occupy on the adjacent square... | 3 | r1=input()
r2=input()
n=len(r1)
l=[0]
for i in range(n):
if r1[i]=='0':
if r2[i]=='0':
l.append(2)
else:
l.append(1)
else:
if r2[i]=='X':
l.append(0)
else:
l.append(-1)
l.append(0)
s=len(l)
count=0
u=1
e=1
while(u<s-1):
if l[u]==2 and e==1:
if l[u+1]==2:
e=2
u=u+1
continue
elif (l[u+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.