problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
n! = n Γ (n β 1) Γ (n β 2) Γ ... Γ 3 Γ 2 Γ 1
Is called the factorial of n. For example, the factorial of 12
12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600
And there are two consecutive 0s at the end.
Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of... | 3 | while 1:
n = int(input())
if n == 0:break
c = 0
while n > 4:
n //= 5
c += n
print(c)
|
Input
The input contains a single integer a (0 β€ a β€ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 3 | s = bin(int(input()))[2:].zfill(6)
print(int(s[0]+s[5]+s[3]+s[2]+s[4]+s[1],2))
|
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | 1 | #from __future__ import print_function
mod=int(1e9+7)
#import resource
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.stack_size(2**28)
#import sys
#sys.setrecursionlimit(10**6)
#fact=[1]
#for i in range(1,100001):
# fact.append((fact[-1]*i)%mod)
#ifact... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n=int(input())
a=[int(i) for i in input().split()]
b=a
b.sort()
t=0
while b!=a:
while t<len(a)-1:
if a[len(a)-1-i]<a[len(a)-2-i]:
a[len(a)-1-i]=a[len(a)-2-i]-a[len(a)-1-i]
t+=1
b=a
b.sort()
b=[str(i) for i in a]
print(" ".join(b)) |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l β€ x β€ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 β€ l β€ r β€ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 |
if __name__ == '__main__':
numbers = list(map(int, input().split()))
found = False
l = numbers[0]
r = numbers[1]
for i in range(l, r + 1):
x = str(i)
if len(set(x)) == len(x):
found = True
print(x)
break
if found is False:
print("-1"... |
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | 3 | import collections
import math
def is_prime(x):
for i in range(2, math.ceil(math.sqrt(x))):
if x % i == 0:
return False
return True
G = input()
A = input()
L = len(A)
ans, t = 0, -1
for i in range(len(G)):
if G[i:i+L] == A and i > t:
ans += 1
t = i + L - 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 | a = int(input())
if a==2:
print("NO")
elif a%2!=0:
print("NO")
else:
print("YES") |
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t... | 3 | n = int(input())
s = input()
zeros = s.count('z')
o_count = s.count('o')
ones = o_count - zeros
num = ''
for _ in range(ones):
num += '1'
for _ in range(zeros):
num += '0'
print(' '.join(list(num))) |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | a=input()
s=0
for i in range(len(a)):
if a[i]=='4' or a[i]=='7':
s+=1
if s==4 or s==7:
print('YES')
else:
print('NO')
|
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.
So the team is considered perfect if it includ... | 3 | for _ in range(int(input())):
l=list(map(int,input().split()))
c,m,x=l[0],l[1],l[2]
p=min(c,m,x)
if p==c:
print(p)
elif p==m:
print(p)
else:
c-=p;m-=p
u=(c+m)//3
p+=min(u,c,m)
print(p) |
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute β health points, shortened to HP.
In general, different values of HP are grouped into 4 categories:
* Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ... | 3 | num = int(input())
if num%4 == 1:
temp = 'A'
var = 0
if num%4 == 3:
var = 2
temp = 'A'
if num%4 == 2:
temp = 'B'
var = 1
if num%4 == 0:
var = 1
temp = 'A'
print(var,temp) |
The length of the longest common prefix of two strings s = s_1 s_2 β¦ s_n and t = t_1 t_2 β¦ t_m is defined as the maximum integer k (0 β€ k β€ min(n,m)) such that s_1 s_2 β¦ s_k equals t_1 t_2 β¦ t_k.
Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}.
For each i (1 β€ i β€ n) she calculated a_i β the length of ... | 3 | t=[98]*51
for s in[*open(0)][2::2]:
for x in[0]+s.split():t[int(x)]^=1;print(*map(chr,t),sep='') |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 3 | t=int(input())
while t>0:
t-=1
n,k=map(int, input().split())
if n>=k:
if k%2==0:
if n%2==0:
print(0)
continue
else:
print(1)
continue
else:
if n%2==1:
print(0)
continue
else:
print(1)
continue
elif n<k:
print(k-n) |
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 | n = int(input())
l = [int(x) for x in input().split()]
a = l.count(1)
b = l.count(2)
c = l.count(3)
s = l.count(4)
if b%2 == 0:
if a <= c:
s = s + b/2 + c
else:
if (a-c)%4 == 0:
s = s + b/2 + (a-c)/4 + c
else:
s = s + b/2 + (a-c)//4 + 1 + c
else:
if a <= c+2:
... |
An n Γ n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n = int(input())
line = [1] * n
for i in range(1, n):
for j in range(1, n):
line[j] += line[j - 1]
print(line[n-1])
|
Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.
Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] =... | 3 | n = int(input())
s = list(map(int,input().split()))
count = 0
def merge(a, left, mid, right):
global count
l = a[left:mid] + [float("inf")]
r = a[mid:right] + [float("inf")]
i = j = 0
for k in range(left, right):
if l[i] <= r[j]:
a[k] = l[i]
i += 1
else:
... |
Vasya has got n books, numbered from 1 to n, arranged in a stack. The topmost book has number a_1, the next one β a_2, and so on. The book at the bottom of the stack has number a_n. All numbers are distinct.
Vasya wants to move all the books to his backpack in n steps. During i-th step he wants to move the book number... | 3 | x=int(input())
f = [0]*(x+1)
o , w = 0 , 0
for i in input().split():
f[int(i)] = o+1
o+=1
for i in input().split():
i=int(i)
if f[i]>w:
print(f[i]-w,end=" ")
w=f[i]
else:
print(0,end=" ") |
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integer... | 3 | n, k = map(int, input().split())
used = [False] * k
a = []
d = [0] * (k + 1)
t = (n + 1) // 2
for i in range(n):
b = int(input())
a.append(b)
d[b] += 1
s = 0
# print(d)
for i in range(1, k + 1):
if t - d[i] // 2 >= 0:
t -= d[i] // 2
s += d[i] // 2 * 2
else:
s += t * 2
... |
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i β€ x holds for each i (1 β€ i β€ n).
Input
The first line of input contains one integer t (1 β€ t β€ 100) β the number of test cases. t blocks follow, each d... | 3 | for t in range(int(input())-1):
n,x=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=input()
a.sort()
b.sort()
b=b[::-1]
for i in range(n):
if a[i]+b[i]>x:
print("No")
break
else:
print("Yes")
n,x=map... |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 β€ r ... | 3 |
def main():
k,r = map(int, input().split())
for i in range(1,11):
if (i*k)%10 == 0:
print(i)
break
if ((i*k)%10)-r == 0:
print(i)
break
main() |
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows:
* a_1 = -1
* a_2 = 2
* a_3 = -3
* a_4 = 4
* a_5 = -5
* And so on ...
... | 3 | a = int(input())
for i in range(a):
x,y = list(map(int,input().split()))
if x %2 == 0:
if y -x == 0:
print(x)
else:
ans = y - x + 1
if ans % 2 == 0:
print(int(-1 * (ans) / 2))
else:
print(int(y + (-1 * (ans - 1) /... |
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())
if n%2 !=0:
n+=1
n/=2
if n%2 == 0:
print(0)
else:
print(1) |
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 | x=int(input())
res=0
for a in range(x):
temp=input()
if temp=="Tetrahedron":
res+=4
elif temp=="Cube":
res+=6
elif temp=="Octahedron":
res+=8
elif temp=="Dodecahedron":
res+=12
elif temp=="Icosahedron":
res+=20
print(res)
|
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or ... | 3 | t = input()
H = input().split()
for c in H:
if c[0] == t[0] or c[1] == t[1]:
print("YES")
quit()
print("NO")
|
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())
w = list(input())
count = 0
for i in range(1,len(w)):
if w[i] != w[i-1]:
continue
else:
if i != len(w) - 1:
next = ['R','G','B']
next.remove(w[i-1])
if w[i+1] in next: next.remove(w[i+1])
w[i] = next[0]
count += 1
else:
next = ['R','G','B']
next.remove(w[i-1])
w[i] = nex... |
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an n Γ m table with integers in its cells. The order of meteors in... | 3 | # bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# import math
# from itertools import *
# import random
# import calendar
# import datetime
# import webbrowser
# import bisect
# f = open("input.txt", 'r')
# g = open("output.txt", 'w')
# n, m = map(int, f.readline().split())
" additional line for fast result "
import ... |
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you ha... | 3 | q=int(input())
ans=[]
for i in range(q):
n=int(input())
if(n<4):
ans.append(4-n)
if(n%2==0 and n>=4):
ans.append(0)
if(n%2!=0 and n>=4):
ans.append(1)
for e in ans:
print(e)
|
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | t = int(input())
counter = 0
for l in range(t):
x, y = input().split()
a = int(x)
b = int(y)
counter = 0
even_difference = abs(b - a) % 2 == 0
odd_difference = abs(b - a) % 2 != 0
if b == a:
counter = 0
elif odd_difference and b > a or even_difference and b < a:
counter +... |
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have n cards with digits, and you want to use them to make as many phone n... | 3 | n = int(input())
a = input()
k = 0
kk = 0
for x in a:
if x == '8':
k += 1
while n >= 11 and k:
k -= 1
n -= 11
kk += 1
print(kk) |
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it β either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a... | 3 | import sys
from collections import defaultdict
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int,strInp()))
n = int(input())
a = intInp()
countOne = a.count(1)
countTwo = a.count(2)
ans = []
s = 0
if countTwo > 0:
s += 2
ans.append(2)
countTwo -= 1
while countO... |
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 | l = [5,4,3,2,1]
ans = 0
n = int(input())
for i in l:
if(n//i==0):
continue
ans+=(n//i)
n-=(ans*i)
if(n<0):
break
print(ans) |
Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.
Three mirrors of length N are set so that they form an equilateral triangle. Let the vertices of the triangle be a, b and c.
Inside the triangle, the rifle is placed at the point p on segment ab such that ap ... | 3 | #!/usr/bin/env python3
import sys
def debug(*args): print(*args, file=sys.stderr)
def exit(): sys.exit(0)
sys.setrecursionlimit(100000)
N, X = map(int, input().split())
def f(x, n):
if x == 0 or x == n:
return 0
debug(x,n)
# if 2*x == n:
# return 3*x
if x % (n-x) == 0:
return ... |
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | 3 | class Stack:
def __init__(self):
self.stack_array = []
self.stack_size = 0
def push(self, element):
self.stack_array.append(element)
self.stack_size += 1
def pop(self):
self.stack_array.pop()
self.stack_size -= 1
def peek(self):
return self.s... |
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | 3 | n = int(input())
a = list(map(int, input().split()))
k = 0
ch = 0
for i in a:
if i % 2 == 0:
ch += 1
print(min(ch, len(a) - ch)) |
There are $ n $ acitivities with start times $ \\ {s_i \\} $ and finish times $ \\ {t_i \\} $. Assuming that a person can only work on a single activity at a time, find the maximum number of activities that can be performed by a single person.
Constraints
* $ 1 \ le n \ le 10 ^ 5 $
* $ 1 \ le s_i \ lt t_i \ le 10 ^ 9... | 3 | n = int(input())
lst = [list(map(int, input().split())) for _ in range(n)]
lst.sort(key=lambda x:x[1])
now = -1
ans = 0
for s, t in lst:
if now < s:
ans += 1
now = t
print(ans)
|
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list.
For ex... | 3 | def solve():
n = int(input())
mydct = {}
for i in map(int, input().split()):
mydct[i] = mydct.setdefault(i, 0) + 1
a = max(mydct)
for i in mydct.copy():
if a % i == 0:
mydct[i] -= 1
if mydct[i] == 0:
mydct.pop(i)
b = max(mydct)
print(a, b)
if... |
Let's call a string good if and only if it consists of only two types of letters β 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin... | 3 | a,b,c = map(int,input().split())
a = a+c
b = b+c
print( 2*min(a,b) + int(a!=b) ) |
An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, β¦, a_r for some l, r.
Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example:
* ... | 3 | from bisect import bisect_left, bisect_right
n,m,k = map(int,input().split())
arr = list(map(int,input().split()))
mk = [ a for a in arr ]
mk.sort()
idx = -1*m*k
ans = sum( mk[idx:] )
v = mk[idx]
i=0
while idx+i != 0 and mk[idx+i]==v:
i+=1
large= []
for a in arr:
if a==v and i>0:
large.append(a)
... |
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected ... | 3 | l = input().split()
print(*l)
n = int(input())
for i in range(n):
t = input().split()
i = 0
if l[1] == t[0]:
i = 1
l[i] = t[1]
print(*l)
|
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 | while True:
try:
n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
ans = A[n-1] - A[0]
for i in range(1, m-n+1):
ans = min(ans, A[i+n-1] - A[i])
print(ans)
except EOFError:
break
... |
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe... | 3 | import math
n, l, v1, v2, k = map(int, input().split(' '))
p = math.ceil(n/k)
def calc(d):
cyc = ((d-d/v2*v1)/(v1+v2))
t = cyc + d/v2
#t is the time per cycle
ans = -1
for i in range(p):
tb4 = t * i;
db4 = tb4 * v1
ans = max(ans, (d/v2+tb4+max(0, l-d-db4)/v1))
return ans... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n=int(input())
a=[]
x=0
y=0
z=0
for i in range(n):
b=input()
a=b.split(' ')
x+=int(a[0])
y+=int(a[1])
z+=int(a[2])
if x==y==z==0:
print("YES")
else:
print("NO")
|
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | count = int(input())
db = {}
for x in range(count):
name = input()
value = db.get(name)
if value is None:
db[name] = 0
print('OK')
else:
increment = db[name] + 1
db[name] = increment
print(name + str(increment))
|
According to a new ISO standard, a flag of every country should have a chequered field n Γ m, each square should be of one of 10 colours, and the flag should be Β«stripedΒ»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'... | 3 | #! /usr/bin/env python3
import fractions
import sys
def main():
solve()
def solve():
data = sys.stdin.readlines()
n, m, flag = parse(data)
answer = check_flag(n, m, flag)
output = 'YES' if answer else 'NO'
print(output)
def parse(data):
n, m = tuple(int(s) for s in data[0].split())
... |
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) β f(n-2) when n > 1, where β de... | 3 | n=int(input())
for i in range(n):
a,b,n=[int(x) for x in input().split()]
c=n%3
if c==0:
print(a)
elif c==1:
print(b)
else:
print(a^b)
|
You are given two positive integers n (1 β€ n β€ 10^9) and k (1 β€ k β€ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, β¦, a_k such that all a_i>0, n = a_1 + a_2 + β¦ + a_k and either all a_i are even or all a_i ar... | 3 | for _ in range(int(input())):
n, k = map(int, input().split())
if n % 2 == 0 and (n - 2*(k - 1)) % 2 == 0 and (n - 2*(k - 1)) > 0:
print('YES')
for i in range(k-1):
print(2, end = ' ')
print(n-2*(k-1))
elif (n - (k - 1)) % 2 == 1 and (n - (k - 1)) > 0:
print('YES... |
You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 β€ |a|, |b| β€ n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a β
x = b or b β
x = a), where |x| denotes the absolute value of x.
After such a transformation, your score increas... | 1 | #!/usr/bin/env python
"""
This file is part of https://github.com/Cheran-Senthil/PyRival.
Copyright 2018 Cheran Senthilkumar all rights reserved,
Cheran Senthilkumar <hello@cheran.io>
Permission to use, modify, and distribute this software is given under the
terms of the MIT License.
"""
from __future__ import divisi... |
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 ... | 1 | import sys
n, m = sys.stdin.readline().split()
n, m = int(n), int(m)
s = [""] * n
for i in range (n):
s[i] = sys.stdin.readline().strip()
res = 0
for i in range (n-1):
for j in range (m-1):
t = ''.join(sorted(s[i][j:j+2] + s[i+1][j:j+2]))
if t == "acef":
res += 1
print (res)
|
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (β_{i=l}^{r} a_i = r - l + 1).
For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1... | 3 | import sys
import math
def int_arr(): return list(map(int, sys.stdin.readline().split()))
def str_arr(): return list(map(str, sys.stdin.readline().split()))
def input(): return sys.stdin.readline().strip()
for _ in range(int(input())):
n=int(input())
st=input()
prev=0
ans=0
dict={}
for i in range(n):
prev... |
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black. Here, it is not allowed to paint two adjacent vertices both in black.
Find the number of ways in which the vertices can be pa... | 3 | # coding: utf-8
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
mod = int(1e9 + 7)
def f(r):
if v[r]:
return(False)
v[r] = 1
dpr = dp[r]
dpr[0] = 1
dpr[1] = 1
for j in e[r]:
if f(j):
dpj = dp[j]
dpr[0] = dpr[0] * (dpj[0] + dpj[1]) % m... |
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)
print(3)
print('L {}'.format(n - 1))
print('R {}'.format(n - 1))
print('R {}'.format(2 * n - 1))
|
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value β_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | import math
t = int(input())
for i in range(t):
n,m = map(int,input().split())
if(n==1):
print(0)
elif(n==2):
print(m)
else:
print(2*m)
|
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n = int(input())
coins = [int(a) for a in input().strip().split()]
coins.sort(reverse=True)
balance = 0
num_coins = 0
for i in range(n):
coin = coins[i]
balance += coin
num_coins += 1
if balance > sum(coins[i+1:]):
print(num_coins)
break
|
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 | str1=str(input())
str2=""
for i in str1:
j=i.lower()
if j in ("a","o","y","e","u","i"):
continue
else:
seq=(str2,".",j)
str2="".join(seq)
print(str2) |
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a... | 3 | n,m=list(map(int,input().split()))
p=list(map(int,input().split()))
y=0
for x in range(n-1):
if p[x]+p[x+1]<m:
ta=m-p[x]-p[x+1]
p[x+1]=p[x+1]+ta
y+=ta
else:
pass
print(y)
print(*p) |
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 | i, j = divmod((input() + input() + input() + input() + input()).replace(' ', '').index('1'), 5)
print(abs(i - 2) + abs(j - 2)) |
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 | x = input().split()
a, b = int(x[0]), int(x[1])
i = 0
while a <= b:
a = 3*a
b = 2*b
i = i+1
print(i) |
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | t=int(input())
def pow_3(n):
c=0
while type(n)==int:
if n%3==0:
n=n//3
c+=1
else:
n=n/3
return c
def pow_2(n):
c=0
while type(n)==int:
if n%2==0:
n=n//2
c+=1
else:
n=n/2
return c
for _ in rang... |
"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 | #!/bin/python3
# common
import math
import os
import random
import re
import sys
def solve():
n, k = list(map(int, input().split()))
xs = list(map(int, input().split()))
k_score = xs[k-1]
if k_score == 0:
print(sum([x > 0 for x in xs]))
return
total = [x >= k_score and k_score >... |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 3 | def gcd(a , b) :
if b==0 :
return a
else :
return gcd(b,a%b)
t,m,n=input().split()
n,m,t=int(n),int(m),int(t)
i=1
flag = True
while (i):
if i%2==1 :
num=gcd(t,n)
if num>n :
flag=False
break
n=n-num
else :
num1=gcd(m,n)
... |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 β€ k β€ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | test_case= int(input())
for _ in range(test_case):
x,y,num= map(int,input().split())
rem=num%x
if(rem>y):
print(num-(rem-y))
elif(rem==y):
print(num)
else:
print(num-(x-(y-rem))) |
Walking along a riverside, Mino silently takes a note of something.
"Time," Mino thinks aloud.
"What?"
"Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this."
"And what are you recording?"
"You see it, tide. Everything has its own period, and I think I've figured... | 3 | n,m=map(int,input().split())
s=list(input())
l=len(s)
f=False
for i in range(l-m):
if not((s[i]==s[i+m]) and ((s[i]!=".") and (s[i+m]!="."))):
f=True
if s[i]==".":
if s[i+m]=="1":
s[i]="0"
else:
s[i]="1"
if s[i+m]==".":
if s[i]=="0":
s[i+m]="1"
else:
s[i+m]="0"
if f==False:
print("... |
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 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import sys
import os
def main():
n = int(sys.stdin.readline())
r = 0
for i in xrange(n):
p, q = map(int, sys.stdin.readline().split())
if p <= q - 2:
r += 1
print r
if __name__ == '__main__':
main()
|
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 | x= int(input())
counter=0
i=0
for i in range(x):
n = list(map(int , input().split() ))
if (n[0] and n[1]) or (n[2] and n[1]) or (n[0] and n[2]):
counter+=1
print(counter)
|
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | import copy
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
b=copy.copy(a)
if b.sort()==a:
print(0)
else:
j=n-1
while j-1>=0 and (a[j]<=a[j-1]):
j=j-1
#print(j)
while j-1>=0 and (a[j]>=a[j-1]) :
j=j-1
print(j)
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | """
n=int(z())
for _ in range(int(z())):
x=int(z())
l=list(map(int,z().split()))
n=int(z())
l=sorted(list(map(int,z().split())))[::-1]
a,b=map(int,z().split())
l=set(map(int,z().split()))
led=(6,2,5,5,4,5,6,3,7,6)
vowel={'a':0,'e':0,'i':0,'o':0,'u':0}
color4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OY... |
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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 16:08:05 2017
@author: lawrenceylong
"""
[n,m,a] = map(int, input().split())
if n%a == 0:
if m % a == 0:
print(int(n/a*m/a))
else:
print(int(n/a*(m//a+1)))
elif m%a == 0:
print(int((n//a+1)*m/a))
else:
print(int(... |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | import sys
import math
#from queue import *
#import random
#sys.setrecursionlimit(int(1e6))
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inara():
return(list(map(int,input().split())))
def insr():
s = input()
return(lis... |
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | 3 |
NUM_ITR = int(input())
for iteration in range(NUM_ITR):
N = int(input())
li = [int(x) for x in input().split(" ")]
dictionary = {}
for i in li:
if i in dictionary:
dictionary[i] += 1
else:
dictionary[i] = 1
# find max
MAX = 0
for i in dictionary:
if dictionary[i] > MAX:
MAX = dictionary[i]
... |
Polycarp is wondering about buying a new computer, which costs c tugriks. To do this, he wants to get a job as a programmer in a big company.
There are n positions in Polycarp's company, numbered starting from one. An employee in position i earns a[i] tugriks every day. The higher the position number, the more tugriks... | 3 | from math import inf, ceil
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, cost = map(int, input().split())
earnings = list(map(int, input().split()))
progress_cost = list(map(int, input().split()))
minimum_cost = inf
day = 0
has_money = 0
for i in range(n-1):
... |
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 |
if __name__ == '__main__':
n = input()
print(n + n[::-1]) |
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers... | 3 | t = int(input())
t2 = t*2
n = t2**(1/2)
n = n // 1
t3 = (n**2 + n)/2
if t3 == t:
print("YES")
elif t3 > t:
n = n+1
t3 = (n**2 + n)/2
if t3 == t:
print("YES")
else:
print("NO")
else:
print("NO") |
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a sec... | 3 | import bisect
def preview(n, a, b, t, S):
t -= b+1 if S[0] else 1
S[0] = False
if t < 0:
return 0
R = []
s = 0
for i in range(1, n):
s += a + (b+1 if S[i] else 1)
if s > t:
break
R.append(s)
else:
return n
L = []
s = 0
for i... |
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second β... | 1 | import sys
def give_int(lst):
return [int(c) for c in lst]
def main():
c, v0, v1, a, l = give_int(sys.stdin.readline().split())
sum = 0
num_d = 0
current_vel = v0
while sum < c:
if current_vel < v1:
current_vel = v0 + num_d * a
if current_vel > v1:
... |
Little C loves number Β«3Β» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 β€ n β€ 10^9) β the integ... | 1 | n = input()
if n % 3 == 0 :
print "1 1 " + str(n-2)
else :
print "1 2 " + str(n-3)
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | n,m=map(int,input().split())
blackhas=True
a=["C","M","Y"]
for i in range(n):
s=input()
for i in range(3):
if a[i] in s:
blackhas=False
break
if not blackhas:
break
if blackhas:
print("#Black&White")
else:
print("#Color") |
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | 3 | import sys
def main():
input = sys.stdin.readline
print = sys.stdout.write
t = int(input())
for i1 in [0]*t:
n, k = map(int, input().split())
nums = list(map(int, input().split()))
current_max = max(nums)
for i in range(n):
nums[i] = current_max - nu... |
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (β_{i=l}^{r} a_i = r - l + 1).
For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1... | 3 |
for _ in range(int(input())):
n = int(input())
s = input()
l = len(s)
##generate prefix sum array (subtract -1 from every element)
prefix_arr = [0]*l
prefix_arr[0] = int(s[0])-1
for i in range(1,l):
prefix_arr[i] = prefix_arr[i-1] + int(s[i]) - 1
#now problem is to find out number of subarrys whose ... |
Problem Statement
We can describe detailed direction by repeating the directional names: north, south, east and west. For example, northwest is the direction halfway between north and west, and northnorthwest is between north and northwest.
In this problem, we describe more detailed direction between north and west a... | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
while True:
direction = ''.join(reversed(input()))
if direction == '#':
break
count = 0
ans = 0
while direction != '':
if direction[0] == 'h':
if count == 0:
ans = 0
else:
ans = an... |
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order.
Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 β€ i β€ n), that s_i < t_i, and for a... | 3 |
import sys
# name = "input2.txt"
# sys.stdin = open(name)
def process(n, k):
# print (n,k)
n1 = 1
while n1 * (n1-1) / 2 < k:
n1 += 1
diff =(n1*(n1-1) // 2) - k
coordb2 =n-n1+1+diff
s = list('a'*n)
s[n-n1] = 'b'
s[coordb2] = 'b'
print(''.join(s))
input = sys.stdin.readl... |
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The on... | 1 | '''input
2
'''
n = input()
print (2**(n+1)-2) |
You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.
There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.
According to an examina... | 3 | from collections import *
n = int(input())
a = list(map(int, input().split()))
c = Counter(i-a[i] for i in range(n))
r = 0
for i in range(n):
c[i-a[i]] -= 1
r += c[a[i]+i]
print(r) |
Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.
Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred... | 3 | R = lambda: map(int, input().split())
n,m = map(int, input().split())
x,y = list(R()), list(R())
p1 = 0; p2 = 0
ans = 0
pa = x[p1]
pb = y[p2]
while p1 < n or p2 < m:
while pa < pb:
p1 += 1
pa += x[p1]
while pb < pa:
p2 += 1
pb += y[p2]
if pa == pb:
ans += 1
... |
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 Γ 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p... | 1 | # encoding: utf-8
import copy
def swapped(paper, x, y):
copied = copy.deepcopy(paper)
square = paper[y][x]
if (square == '.'):
copied[y][x] = '#'
else:
copied[y][x] = '.'
return copied
def has2x2(paper):
for x in range(3):
for y in range(3):
for s in ['#', ... |
[3R2 - Standby for Action](https://www.youtube.com/watch?v=P2ZVC9aoiKo)
Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"!
The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The sho... | 3 | n = int(input())
x = [1/i for i in range(1, n+1)]
print(sum(x)) |
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ... | 1 | from sys import stdin,stdout
t=input()
for i in range(t):
n=input()
l=list(map(int,stdin.readline().split()))
a=1000000
c=0
for j in range(-1,-n-1,-1):
if l[j]>a:
c+=1
a=min(a,l[j])
print c
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | import sys
input = lambda: sys.stdin.readline()
def Main():
n = int(input())
p = input().split(" ")
r =[0]*n
for i in range(n):
r[int(p[i])-1]=i+1
print(' '.join(map(str, r)))
if __name__ == '__main__':
Main() |
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 | cnt = 0
n = int(input())
extraN = n
while n > 3 :
cnt += 1
n -= 2
print(cnt + 1)
while extraN > 3 :
print(2, end = ' ')
extraN -= 2
print(extraN) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | a=input()
n=int(a)
for i in range(n+1,9013):
c=len(set(str(i)))
if c==4:
print(i)
break
|
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())
str = input()
count = 0
temp = str[0]
i = 1
while(i<n):
#print(str[i])
#print(temp)
if(temp == str[i]):
count += 1
#print(count)
else:
temp = str[i]
i += 1
print(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())
c=0
b=0
for i in range(n):
a=int(input())
if a!=b:
c+=1
b=a
print(c) |
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.
Vasiliy plans to buy his favorite drink fo... | 1 | def get_index(wine_price,today_money):
left = 0
right = len(wine_price) - 1
while left < right:
mid = (left + right)/2
if wine_price[mid] <= today_money:
left = mid + 1
else:
right = mid
return right
def get_result(wine_price,today_money):
result = ge... |
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ... | 3 |
s = input()
m = len(s)
n = int(input())
arr = [0 for _ in range(m+1)]
out = list(map(int, input().split()))
for x in out:
arr[x] = 1 + arr[x]
if m-x+2<=m:
arr[m-x+2] -= 1
for y in range(1, m+1):
arr[y] = arr[y] + arr[y-1]
out = list(s)
i = 1
while i <= m//2:
if arr[i]&1:
... |
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt... | 3 | t = int(input())
for _ in range(t):
n, d = map(int, input().split())
if (1 - n) ** 2 - 4 * (d - n) >= 0:
print('YES')
else:
print('NO')
|
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the... | 3 | n=int(input())
flag=1
a=[]
b=set()
for i in range(n):
d=input()
c=set(d)
b.update(c)
if(len(b)!=2):
flag=0
else:
a+=[d]
if(flag==0):
print("NO")
else:
x=a[0][0]
for i in range(n):
for j in range(n):
if(j==i or j==n-1-i):
if(a[i][j]!=x):... |
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopo... | 3 | n,m=[int(x) for x in input().split()]
ans=1
for i in range(1,min(n,m)+1):
ans*=i
print(ans) |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 3 | for _ in range(int(input())):
n,m = map(int,input().split())
ans=0
if(n<=m):
ans = m-n;
else:
x = n-m;
if(x%2==0): ans=0;
else: ans=1;
print(ans) |
Little C loves number Β«3Β» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 β€ n β€ 10^9) β the integ... | 3 | x = int(input())
a = 1 ; b = 1 ; c = x - (a + b)
if c % 3 == 0:
a += 1 ; c -= 1
print(a, b, c)
|
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi... | 3 | #from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
#from __future__ import print_function, division #while using python2
def modinv(n,p):
return pow(n,p-2,p)
import math
def main():
... |
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
... | 3 | def solve():
s = input()
zeros = 0
ones = 0
for char in s:
zeros+= (char=='0')
ones+= (char=='1')
#print(zeros,' ',ones)
ans = 1000000
left_ones = 0
left_zeros = 0
right_zeros = zeros
right_ones = ones
if len(s)==1:
print(0)
return 0 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.