problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | k,l,m,n,d = [int(input()) for _ in range(5)]
c = 0
for i in range(1,d+1):
if i%k!=0 and i%l!=0 and i%m!=0 and i%n!=0:
c+=1
print(d-c)
|
There is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.
The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are ex... | 3 | R = lambda: map(int, input().split())
n, b, a = R()
s = list(R())
x = 0
v, u = b, a
for y in s:
if v or u:
if (not y or u == a) and u:
u -= 1
elif v:
v -= 1
if y:
u = min(u + 1, a)
else:
u -= 1
x += 1
print(x)
|
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | for _ in range(int(input())):
n = int(input())
ans = ((n%10)-1)*10
i = 0
while n>0:
i += 1
n = n//10
ans += (i*(i+1)//2)
print(ans) |
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit c... | 3 | #!/usr/local/bin/python3.4
k2, k3 , k5 , k6 = map( int, input().split() )
minimal256=min(k6,k5,k2)
sum=256*minimal256
k2-=minimal256
minimal32=min(k3,k2)
sum+=minimal32 * 32
print (sum)
|
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())
l = list(map(int,input().split()))
print(len(range(min(l),max(l)+1)) - n) |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | s=input()
n=len(s)
if(n==1 or n==2):
print(s)
else:
if(n%2==0):
c=n//2
i=c-1
j=c
else:
c=n//2
i=c
j=c+1
print(s[i],s[j],sep='',end='')
count=n-2
while(count>0):
i-=1
count-=1
print(s[i],end='')
if(count==0):
... |
You are given three bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number a from the first bag and number b from the second bag.... | 3 | import sys
from collections import *
import math
import bisect
def input():
return sys.stdin.readline()
n1,n2,n3=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))
a.sort()
b.sort()
c.sort()
s1=sum(a)
s2=sum(b)
s3=sum(c)
s=s1+s2+s3
maxx=max(... |
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears:
1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;
2. Let ... | 3 | import heapq
T = int(input())
for t in range(T):
# print("----")
n = int(input())
a = [0 for i in range(n)]
interval_length = n
prev_pos = [(-n, 0, n - 1)]
heapq.heapify(prev_pos)
# print(prev_pos)
nb = 1
while True:
try:
interval_length, l, r = heapq.heappop(pre... |
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())
z = 0
a = 0
for i in range(n):
x,y = [int(i) for i in input().split()]
z-=x
z+=y
if z > a:
a = z
print(a) |
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 math
t=int(input())
while(t):
n=int(input())
k=2
while(1):
res=math.pow(2,k)
#print(res)
res=int(res)-1
if(n%res==0):
x=n//res
print(x)
break
k=k+1
t=t-1 |
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | 3 | import math
n =int (input())
m = [int(x) for x in str (input())]
# print(m)
n = []
s = ''
k = 0
for i in m :
if i == 2 or i == 3 or i == 5 or i == 7 :
n.append(i)
if i == 4 or i == 6 or i == 8 or i ==9 :
k = math.factorial(i)
while(k != 1):
# print(k)
if k % m... |
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the ... | 3 | import sys
class RangeBit:
def __init__(self, n):
sz = 1
while n >= sz:
sz *= 2
self.size = sz
self.dataAdd = [0 for _ in range(sz)]
self.dataMul = [0 for _ in range(sz)]
def sum(self, i):
assert i > 0
add, mul, start = 0, 0, i
while ... |
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | import math
def newCost(a):
x=sum(a)
avg=int(math.ceil(x/len(a)))
return avg
if __name__ == '__main__':
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().rstrip().split()))
res=newCost(a)
print(res)
|
We have a string S of length N consisting of uppercase English letters.
How many times does `ABC` occur in S as contiguous subsequences (see Sample Inputs and Outputs)?
Constraints
* 3 \leq N \leq 50
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
... | 3 | tam = int(input())
k = input()
print(k.count("ABC"))
|
You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. The order of a,b,c does matter, and some of them can be the same.
Constraints
* 1 \leq N,K \leq 2\times 10^5
* N and K are integers.
Input
Input is given from ... | 3 | N, K = map(int, input().split())
# 全部Kの倍数のパターン
ans = (N // K) ** 3
# 偶数の時は、全部Kの倍数+(K/2)のパターンでもよい
if K % 2 == 0:
ans += ((N - K/2) // K + 1) ** 3
print(int(ans)) |
We have a 3×3 square grid, where each square contains a lowercase English letters. The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.
Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bot... | 3 | s=str()
s+=input()[0]
s+=input()[1]
s+=input()[2]
print(s) |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | t = int(input())
for _ in range(t):
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
a.sort()
b.sort(reverse = True)
for i in range(k):
if b[i] > a[i]:
a[i],b[i] = b[i],a[i]
else:
break
print(sum(a)) |
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | t=int(input())
while(t>0):
l=list(map(int,input().split()))
a=l[0]
b=l[1]
c=l[2]
n=l[3]
sum = a + b + c + n
if (sum % 3 == 0 and a <= sum / 3 and b <= sum / 3 and c <= sum / 3):
print("YES")
else:
print("NO")
t=t-1
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla... | 1 | n = int(raw_input())
def get_time(a, b):
index = 0
while index < len(a) and a[index] < b:
index += 1
return index
def cumsum(a):
x = []
curr = 0
for num in a:
curr += num
x.append(curr)
return x
m = dict()
m2 = dict()
for i in range(n):
line = raw_input()
na... |
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 | statment1 = "I hate that I love that"
statment2 = "I hate it "
statment3 = "I hate that I love it"
statment4 = "I hate that I love that"
n = int(input(""))
if n == 1:
print("I hate it" , end=" ")
if n == 2:
print("I hate that I love it" , end = " ")
if n % 2 == 0 and n > 2:
while n > 2:
print(statme... |
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.
What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ... | 3 | a, b, c = [int(i) for i in input().split()]
if max(a, b, c) >= sum([a, b, c]) - max(a, b, c):
print(2 * max(a, b, c) - sum([a,b,c]) + 1)
else:
print(0) |
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell (0, 0). Robot can perform the following four kinds of operations:
* U — move from (x, y) to (x, y + 1);
* D — move from (x, y) to (x, y - 1);
* L — move from (x, y) to (x - 1, y);
* R — move from (x, y) to (x + 1,... | 3 | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def change(res,el,fac):
if el == 'U':
res[1] += fac
elif el == 'D':
res[1] -= fac
elif el == 'R':
res[0] += fac
else:
res[0] -= fac
def check(mid,s,res,x,y,n):
... |
Takahashi and Aoki will play a game. They will repeatedly play it until one of them have N wins in total.
When they play the game once, Takahashi wins with probability A %, Aoki wins with probability B %, and the game ends in a draw (that is, nobody wins) with probability C %. Find the expected number of games that wi... | 3 | # WARN: Require mod number m is prime number
class ModComb:
# For nCr mod m
def __init__(self, n_max, m):
self._n_max = n_max
self._m = m
self._mod_facts = [1] * (n_max+1) # list of n! mod m
self._mod_inv_facts = [1] * (n_max+1) # list of inverse r! mod m
if not ... |
Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest. In this game, an honest player always tells the truth, and an dishonest player always tell lies. You are given two characters a and b as the input. Each of them is either `H` or `D`, and carries the following information:
If a=`H`, AtCoDe... | 3 | a,b=map(str,input().split());print('DH'[a==b::2]) |
Chef wrote some text on a piece of paper and now he wants to know how many holes are in the text. What is a hole? If you think of the paper as the plane and a letter as a curve on the plane, then each letter divides the plane into regions. For example letters "A", "D", "O", "P", "R" divide the plane into two regions so... | 1 | alpha = {"A":1,"B":2,"D":1,"O":1,"P":1,"Q":1,"R":1}
loop = int(raw_input())
for i in range(0,loop):
str = raw_input()
count = 0
for char, num in alpha.iteritems():
index = 0
val = 0
while index!=-1:
index = str.find(char,index)
if index!=-1:
... |
You are given two strings A and B of the same length. Each string contains N Lower case Latin character (from 'a' to 'z'). A shift operation will remove the first character of a string and add the same character at the end of that string. For example after you perform a shift operation on a string 'abcd', the new strin... | 1 | def border(s):
dic={}
dic[0]=-1
dic[1]=0
n=len(s)
j=0
for i in range(2,n+1):
while s[i-1]!=s[j] and j!=-1:
j=dic[j]
j+=1
dic[i]=j
return dic
n=input()
a=raw_input()
b=raw_input()*2
pre=border(a)
m=0
ans=0
cur=0
for i in range(n):
while a[cur]!=b[i] and... |
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | 3 | for _ in range(int(input())):
a,b,x,y,n = [int(x) for x in input().split()]
if max(a-n,x)>=max(b-n,y):
if b-n>=y:
print(a*(b-n))
else:
if a-(n-(b-y))>=x:
print(y*(a-(n-(b-y))))
else:
print(x*y)
else:
if a-n>=x:
... |
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 | matrix = [[int(i) for i in input().split(' ')] for i in range(5)]
ii, jj = int(), int()
for i in range(5):
for j in range(5):
if matrix[i][j] == 1:
ii, jj = i, j
print(abs(2 - ii) + abs(2 - jj))
|
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 | s=str(input())
print(s[0].upper(),s[1::],sep="") |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | s = str(input(''))
t = str(input(''))
if s[::-1] == t:
print('YES')
else:
print('NO')
|
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 | def main():
for _ in range(int(input())):
n=int(input())
l=[9]*n
l1=[]
for i in range(n):
l1.extend(list(bin(l[i]))[2:])
w=[]
for i in range(n):
w.append(l1.pop())
w=w[::-1]
j=-1
for i in range(len(w)//4):
l[j]=8
j-=1
if(len(w)%4!=0):
l[j]=8
print(*l,sep='')
# print(w)
main()
# 6... |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | n, k = map(int, input().split(" "))
if n % 2 == 0:
m = n // 2
else:
m = n // 2 + 1
if k <= m:
print(k * 2 - 1)
else:
print(2 * (k - m)) |
You will receive 3 points for solving this problem.
Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'.
... | 3 | r = input()
i = 0
outer_count = 0
while i < len(r):
count = 0
char = r[i]
while r[i] == char:
count += 1
i += 1
if i == len(r):
break
if count % 2 == 0:
outer_count += 1
print(outer_count)
|
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | t = int(input())
while t:
ok = False
n, m = map(int, input().split())
for i in range(n):
a,b = map(int, input().split())
c, d = map(int, input().split())
ok = ok or b == c
if m % 2 == 0 and ok:
print("YES")
else:
print("NO")
t -= 1 |
You are given four integers n, c_0, c_1 and h and a binary string s of length n.
A binary string is a string consisting of characters 0 and 1.
You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change.
After some changes (possibly zero) ... | 3 |
if __name__ == "__main__":
t = int(input())
cases = []
for _ in range(t):
n, c0, c1, h = input().split()
n, c0, c1, h = int(n), int(c0), int(c1), int(h)
s = input()
coins = 0
if c1 > c0 and c1-c0 > h:
s = list(s)
for i,v in enumerate(s):
... |
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())):
a,k=map(int,input().split())
if a>=k:
print((a-k)%2)
else:
print(k-a) |
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.
For each square, you will perform either of the following operations once:
* Decrease the height of the square by 1.
* Do nothing.
Determine if it is possible to perform the operations so that the heights ... | 3 | n = int(input())
h = list(map(int, input().split()))
mi = 0
for hi in h:
if hi < mi - 1:
print("No")
break
mi = max(mi, hi)
else:
print("Yes") |
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())
mas = []
for i in range(n):
x, y, z = map(int, input().split())
p = [x, y, z]
mas.append(p)
pokoi = [0, 0, 0]
summa = [0, 0, 0]
for i in range(n):
summa[0] += mas[i][0]
summa[1] += mas[i][1]
summa[2] += mas[i][2]
if summa == pokoi:
print('YES')
else:
print('NO') |
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with.
Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break th... | 1 | from collections import defaultdict
n = int(raw_input())
S = raw_input().split()
C = defaultdict(int)
for s in S:
C[int(s)] += 1
s = 0
for i in range(1, 101):
s += C[i] / 2
print s/2
|
Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a a... | 3 | def GCD(a, b):
if a == 0:
return b
return GCD(b % a, a)
# Function to return LCM of two numbers
def LCM(a, b):
return (a * b) / GCD(a, b)
n,a,b,p,q=map(int,input().split())
lcm = LCM(a,b)
x=0
sum=0
if p>q :
x=int(n/a)
sum += (x*p)
x=int(n/b) - int(n/lcm)
sum += (x*q)
else :
... |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | n=int(input())
a=input()
c=0
d=0
for i in range(1,len(a)):
if a[i-1]=='S' and a[i]=='F':
c+=1
if a[i-1]=='F' and a[i]=='S':
d+=1
if(c>d):
print("YES")
else:
print("NO")
|
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is `#`, and a "road" square if S_{ij} is `.`.
From a road square, you can move to a horizontally or vertically adjacent ro... | 3 | from collections import deque
h,w = map(int,input().split())
G = [input() for i in range(h)]
directions = [(1,0),(0,1),(-1,0),(0,-1)]
ans = 0
for sx in range(w):
for sy in range(h):
if G[sy][sx] == "#":
continue
dist = [[-1] * w for i in range(h)]
dist[sy][sx] = 0
que = deque([[sy, sx]])... |
An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.
Given an integer N, determine whether it is a Harshad number.
Constraints
* 1?N?10^8
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output... | 3 | X = input()
N = int(X)
fX = sum(map(int, X))
print("Yes" if N%fX==0 else "No") |
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.
<image>
There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, .... | 3 | x=999
s=0
for i in range (int(input())):
a,p = map(int,input().split())
x = min(x,p)
s += a*x
print(s) |
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 | def sol():
n=int(input())
print("0" if (n*(n+1))%4==0 else "1")
if(__name__=='__main__'):
sol()
|
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | 3 | for _ in range(int(input())):
s=list(input())
ans=[]
for i in range(len(s)-2):
a,b,c=s[i],s[i+1],s[i+2]
if a+b+c=='one':ans.append(i+2);s[i+1]='#'
elif a+b+c=='two':
if i<len(s)-4:
d,e=s[i+3],s[i+4]
if d+e=='ne':ans.append(i+3);s[i+2]='#'
... |
Are you going to Scarborough Fair?
Parsley, sage, rosemary and thyme.
Remember me to one who lives there.
He once was the true love of mine.
Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.
Willem asks his friend, Grick for directions, Grick helped... | 3 | n,m=map(int,input().split())
s=input()
for i in range(m):
a=list(input().split())
l=int(a[0])
r=int(a[1])
for j in range(l-1,r):
if s[j]==a[2]:
s=s[:j]+a[3]+s[j+1:]
print(s) |
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ... | 3 | n = int(input())
if n == 0:
print("01")
elif n ==1:
print("05")
else:
print("25") |
Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
* At time 1, the first spectator stands.
* At time 2, the second spectator stands.
* ...
* At time k, the k-th spectator stands.
* At time k + 1, the (k + 1)-th specta... | 3 | n,k,t = map(int,input().split())
if(t<=k):
print(t)
elif(n>t>k):
print(k)
else:
print(n+k-t) |
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card.
Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with num... | 3 | n = int(input())
a = []
while n:
a.append(int(input()))
n -= 1
a.sort()
first = a[0]
second = a[int(len(a) / 2)]
dem = -1
if first == second:
print("NO")
quit()
for i in a:
dem += 1
if(dem < int(len(a) / 2) and i != first):
print("NO")
quit()
elif(dem >= int(len(a) / 2) and i... |
You are given a string s. Each character is either 0 or 1.
You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.
You may eras... | 3 | t=int(input())
while(t):
s=input()
l=list(s)
l2=[]
s=0
for i in range(len(l)):
if(l[i]=='1'):
l2.append(i)
for i in range(1,len(l2)):
if((l2[i]-l2[i-1])>1):
s+=(l2[i]-l2[i-1])-1
print(s)
t=t-1 |
A flowerbed has many flowers and two fountains.
You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, t... | 3 | n, x1, y1, x2, y2 =map(int,input().split())
lis=[]
ans=[]
r1=r2=0
for i in range(n):
a,b=map(int,input().split())
lis.append([a,b])
k=(x1-a)**2+(y1-b)**2
l=(x2-a)**2+(y2-b)**2
ans.append([k,l])
ans.sort(reverse=True)
ans.append([0,0])
r1=ans[0][0]
r2=0
fin=r1+r2
#print(ans)
for i in range(1,n+1):
... |
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 | n = int(input())
s = str(input())
x = s.count('A')
y = n-x
if x==y:
print("Friendship")
elif x>y:
print("Anton")
else:
print("Danik") |
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays... | 3 | n, m = map(int, input().split())
s = []
for i in range(n):
a, b = map(int, input().split())
s.append(a * b)
q = list(map(int, input().split()))
a = 0
b = 0
su = s[0]
while b < m:
if q[b] > su:
a += 1
su += s[a]
else:
print(a + 1)
b += 1
|
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, ... | 3 | n, M = [int(x) for x in input().split()]
arr = [0] + [int(x) for x in input().split()] + [M]
forward, backward = [0], []
[forward.append(forward[i-1] + arr[i] - arr[i-1] if i%2 == 1 else forward[i-1]) for i in range(1, n+2)]
mx = forward[-1]
if n%2 == 0:
temp = arr[::-1]
backward = [0]
[backward.append(backward[i... |
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (... | 3 | # import sys
# from io import StringIO
# sys.stdin = StringIO(open(__file__.replace('.py', '.in')).read())
n = int(input())
s = input()
p2 = (0, 0)
p1 = (0, 0)
r = 0
for c in s:
if c == 'U':
if p2[0] == p1[0] and p1[0] == p1[1] and p1[0] != 0:
r += 1
p2 = p1
p1 = (p1[0], p1[1... |
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a... | 1 | s=str(raw_input())
lists=list(s)
length=len(lists)
limit=0
if lists==lists[::-1]:
if length%2==0:
lists.insert(length//2,'y')
print "".join(map(str,lists))
elif length%2==1:
lists.insert(1+length//2,lists[length//2])
print "".join(map(str,lists))
else:
for i in range(0,len(li... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | #import sys
#
#count=0
#
#for line in sys.stdin:
# count +=1
# if count > 1:
# if len(line.strip('\n')) <= 10:
# print(line.strip('\n'))
# if len(line.strip('\n')) > 10:
# print(line[0] + str((len(line.strip('\n')))-2) + line[-2])
#vowels = ["A", "a", "O", "o", "Y", "y", "E"... |
There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i). Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N.
In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B. Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th t... | 3 | n = int(input())
k = int(input())
s = 0
for x in list(map(int,input().split())):
s += min(x,k-x)
print(2*s)
|
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ ... | 3 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
... |
You are given circle $A$ with radius $r_a$ and with central coordinate $(x_a, y_a)$ and circle $B$ with radius $r_b$ and with central coordinate $(x_b, y_b)$.
Write a program which prints:
* "2" if $B$ is in $A$,
* "-2" if $A$ is in $B$,
* "1" if circumference of $A$ and $B$ intersect, and
* "0" if $A$ and $B$ do not... | 3 | n = int(input())
for i in range(n):
xa, ya, ra, xb, yb, rb = map(float, input().split())
d = ((xa - xb)**2 + (ya - yb)**2)**0.5
if d > ra + rb:
print(0)
elif ra + d < rb:
print(-2)
elif rb + d < ra:
print(2)
else:
print(1) |
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'... | 1 | l = map(int, raw_input().split(' '))
n = l[0]
m = l[1]
a = l[2]
row = (m-1)/a + 1
col = (n-1)/a + 1
print str(row*col) |
You are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on).
You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, ..., a_... | 3 | from sys import maxsize, stdout, stdin,stderr
mod = int(1e9+7)
import sys
def I(): return int(stdin.readline())
def lint(): return [int(x) for x in stdin.readline().split()]
def S(): return list(map(str,input().strip()))
def grid(r, c): return [lint() for i in range(r)]
from collections import defaultdict, Counter, deq... |
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... | 1 | n = input()
s = raw_input()
cnt = 0
for i in s:
if i == '-':
if cnt>0:
cnt-=1
else:
cnt = 0
if i == '+':
cnt+=1
print cnt |
Polar bears like unique arrays — that is, arrays without repeated elements.
You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, w... | 1 | rd = lambda : map(int, raw_input().split())
n, = rd()
s = rd()
ss = sorted(s)
a, b = {}, {}
for i in range(n):
if i < (n + 2) / 3:
a[ss[i]] = i
b[ss[i]] = ss[i] - i
elif i < (2 * n + 2) / 3:
a[ss[i]] = ss[i] - i
b[ss[i]] = i
else:
a[ss[i]] = ss[i] - n + i + 1
b[ss[i]] = n - i - 1
print 'Y... |
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their... | 3 | n = int(input())
s = list(map(int, input()))
m = list(map(int, input()))
m.sort()
m1 = list(m)
mor = 0
she = 0
for i in s:
flick = True
brk = True
for j in range(n):
if m[j] >= i and flick:
flick = False
m[j] = -1
if m1[j] > i and brk:
she += 1
... |
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= map(int,input().split())
if n%a == 0:
x = n//a
else:
x = (n//a)+1
if m%a == 0:
y = m//a
else:
y = (m//a)+1
print(int(x*y)) |
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu... | 1 | n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
a.sort()
b = set()
ans = 0
for x in a:
if x not in b:
b.add(x*k)
ans += 1
print ans
|
Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers.
She thinks that a set S = \\{a_{1}, a_{2}, ..., a_{N}\\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remai... | 3 | n=int(input())
if n==3:
print(2,5,63)
else:
if n%2==0:
ans=[3,9]
cnt=2
for i in range(30001):
if i%6==2:
if i+2<=30000:
ans.append(i)
ans.append(i+2)
cnt+=2
if cnt==n:
break
else:
continue
if cnt<n:
for i in range(... |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
The decreasing coefficient of permutation p1, p2, ...,... | 3 | n,k = [int(ch) for ch in input().split(' ')]
input = [i+1 for i in range(n)]
idx = n-1-k
left = input[:n-1-k]
right = input[n-1-k:]
res = left + sorted(right,reverse=True)
ans = ''
for num in res:
print(num,end=' ')
|
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 | num = int(input())
word = input()
word = word.upper()
def pangram(num, word):
for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
if (word.find(i) == -1):
print("NO")
return
print("YES")
pangram(num, word)
|
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.
Determine a minimal number of wooden bars which are needed t... | 3 | n, a, b = [int(input()) for _ in range(3)]
d = [0]
c = 0
for i in (a, b, a, a, b, a):
if max(d) >= i:
d[d.index(max(d))] -= i
else:
c += 1
d += [n - i]
print(c) |
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.
A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at vo... | 3 | n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
happiness = 0
for i in range(n):
if (b[i] + 1) // 2 <= a[i] and b[i] > 1:
happiness += (b[i] // 2) * ((b[i] + 1) // 2)
else:
happiness -= 1
print(happiness) |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | l=list(map(int,input().split('+')))
l=sorted(l)
a=''
if len(l)==1:
print(l[0])
exit()
for i in l:
a+=str(int(i))+'+'
print(a[0:len(a)-1]) |
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou... | 1 |
def c(n,m):
ans=1
t0=max(n-m,m)
d=n-t0
for i in xrange(n,n-d,-1):
ans*=i
x=1
for i in xrange(1,d+1):x*=i
return ans/x
n,m,t=map(int,raw_input().split())
ans=0
for i in xrange(4,min(n,t)+1):
if t-i<=m and t-i>=1:
ans+=c(n,i)*c(m,t-i)
print ans |
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 | l=list(input())
l[0]=l[0].upper()
for i in l:
print(i,end="")
|
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.
Spring is starting and the Winter sleep is ... | 3 | n,k,q=map(int,input().split())
l=[0]+list(map(int,input().split()))
o=[]
ans=[]
for i in range(q):
x,y=map(int,input().split())
if x==1:
if len(o)<k: o+=[l[y]]
elif l[y]>min(o): o+=[l[y]]; o.remove(min(o))
else:
if l[y] in o: ans+=['YES']
else: ans+=['NO']
print('\n'.join(ans... |
Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.
You are given Smeke's current rating, x. Print `ABC` if Smeke will participate in ABC, and print `ARC` otherwise.
Constraints
* 1 ≦ x ≦ 3{,}000
* x i... | 3 | x = int(input())
print('ABC') if x < 1200 else print('ARC') |
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices.... | 3 | # the iterative approach to grpah traversal was required
# generate graph
graph = {}
vert,edge = map(int,input().split())
reached = set()
for _ in range(edge):
a,b = map(int,input().split())
if a not in graph.keys():
graph.update({a:[b]})
else: graph[a].append(b)
if b not in graph.keys():
... |
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th m... | 3 | n, k = map(int, input().split())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
ans = 0
for i in range(n):
if t[i]:
ans += a[i]
a[i] = 0
pk = sum(a[:k])
tech = sum(a[:k])
for i in range(n - k):
pk = pk - a[i] + a[i + k]
tech = max(tech, pk)
print(ans + tech)
|
[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());ans=0
for i in range(1,n+1):ans+=1/i
print(ans) |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ... | 3 | inp=input()
p=list(range(2))
p=inp.split()
n=int(p[0])
k=int(p[1])
l=list(range(n))
i=count=0
ll=input()
l=ll.split()
while i<n:
l[i]=int(l[i])
i+=1
i=0
while i<n:
if l[i]>=l[k-1] and l[i]>0:
count+=1
i+=1
print(count)
|
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ... | 3 | n = int(input())
c = [[0,0]]*n
for i in range(n):
c[i] = list(map(int, input().split()))
v = 1
res = 1
for i in range(1, n):
if c[i]==c[i-1]:
v+=1
if v>res:
res+=1
else:
v = 1
print(res) |
Limak is a little polar bear. He has n balls, the i-th ball has size ti.
Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:
* No two friends can get balls of the same size.
* No two friends can get balls of sizes that di... | 1 |
n = int(raw_input())
ballsSize = map(int, raw_input().split())
s = set(ballsSize)
ballsSize = list(s)
ballsSize.sort()
found = False
for i in xrange(len(ballsSize)-2):
a = ballsSize[i]
b = ballsSize[i+1]
c = ballsSize[i+2]
if(a != b and a != b and b!= c and c-a <= 2):
found = True
break
if(found): print '... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | a=input()
y=0
z=a[0]
max=0
for i in range(len(a)):
if a[i]==z:
y+=1
else:
y=1
z=str(int(z)^1)
if(max<y):
max=y
if(max>6):
print("YES")
else:
print("NO")
|
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 | def recurr1(a,b,c):
if a*8 <= b:
a *= 8
if a==b:
c += 1
else:
c += 1
c = recurr1(a,b,c)
elif a*4 <= b:
a *= 4
if a==b:
c += 1
else:
c += 1
c = recurr1(a,b,c)
elif a*2 <= b:
a *= 2
... |
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 | n = len(input())
print(4)
print('R', 2)
print('R', 2*n - 3)
print('L', 2*n - 2)
print('L', 2) |
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019.
Constraints
* All values in input are integers.
* 0 \leq L < R \leq 2 \times 10^9
Input
Input is given from Standard Input in the fol... | 3 | import sys
l,r=map(int,input().split())
if l+2019<=r:
print(0)
sys.exit()
mn=2018*2018
for i in range(l,r+1):
for j in range(i+1,r+1):
mn=min(mn,i*j%2019)
print(mn) |
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ... | 3 | N = int(input())
S = input()
ans = ''
for s in S:
ans += chr(((ord(s)-65+N)%26)+65)
print(ans) |
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from ... | 3 | n = int(input())
m = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if 1 in a or 1 in b:
print(-1)
exit()
list_ = [a[0]]
for i in range(1, n):
list_.append(b[i])
list_.append(a[i])
list_.append(b[0])
need = list_[::-1]
mas = m
for el in need:
mas += mas / (... |
N persons are standing in a row. The height of the i-th person from the front is A_i.
We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:
Condition: Nobody in front of the person is taller than the person. Here, the height of a ... | 3 | N = input()
A = list(map(int, input().split()))
c = 0
mae = A[0]
for i in A:
if i < mae:
c += mae - i
else:
mae = i
print(c) |
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans... | 1 |
vowels = 'aeiouyAEIOUY'
consonants = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ'
string = raw_input()
for s in string[::-1]:
if (s in vowels or s in consonants):
if (s in vowels):
print "YES"
else:
print "NO"
break
|
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≤ i ≤ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc... | 3 | a, b, c, d = map(int, input().split())
p = 0
e = []
if a > b:
if c == 0 and d == 0 and a == (b + 1):
for j in range(a + b):
if j % 2 == 0:
e.append(0)
else:
e.append(1)
else:
p = 1
else:
if d > c:
if a == 0 and b == 0 and d =... |
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.
Each tool can be sold for exactly one emerald. How many... | 3 | for t in range(int(input())):
a, b = [int(x) for x in input().split()]
print(min((a+b)//3, min(a, b)))
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | w=int(input())
if w%2!=0 or w==2 or w==0:
print("No")
else:
print("Yes") |
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a... | 3 | n = input()
print("First" if any(int(i) % 2 for i in list(input().split())) else "Second") |
Consider a tic-tac-toe on a 3x3 board. Tic-tac-toe is a two-player battle game. Decide the first attack and the second attack, one hits Kuroishi and one hits Shiraishi. The winner is the person who puts stones one by one on the board alternately and arranges three of his own stones first in either the vertical, horizon... | 1 | while True:
s=raw_input()
if s=="0":break
s+="".join([raw_input() for i in range(2)])
L=[(i,i+1,i+2) for i in range(0,9,3)]+[(i,i+3,i+6) for i in range(3)]+[(0,4\
,8),(2,4,6)]
for i,j,k in L:
if s[i]==s[j]==s[k]!="+":
print "b" if s[i]=="b" else "w"
break
else:
... |
It is winter now, and Max decided it's about time he watered the garden.
The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned ... | 3 | t=int(input())
for i in range(t):
time=0
n,k=map(int,input().split(" "))
x=list(map(int,input().split(" ")))
arr_bed=list(range(1,n+1))
while arr_bed!=[]:
time+=1
x_copy=[]
for j in x:
if j in arr_bed:
arr_bed.remove(j)
if j-1 >0:
... |
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).
He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will... | 3 | def solve():
xdiff = abs(x1 - x2)
ydiff = abs(y1 - y2)
if ydiff == 0:
return xdiff
if xdiff == 0:
return ydiff
summ = xdiff + ydiff
return summ + 2
T = int(input())
for t in range(T):
x1, y1, x2, y2 = list(map(int, input().split()))
ans = solve()
print(ans) |
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 ... | 3 | from collections import Counter
n=int(input())
p=input().split(" ")
q=input().split(" ")
arr=[]
for i in range(1,len(p),1):
arr.append(int(p[i]))
for i in range(1,len(q),1):
arr.append(int(q[i]))
arr.sort()
count=len(Counter(arr).keys())
if(count==n):
print("I become the guy.")
else:
print("Oh, my keyb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.