problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
The circle line of the Roflanpolis subway has n stations.
There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ... | 1 | n, sai1, chega1, sai2, chega2 = map(int, raw_input().split())
aux1 = sai1
aux2 = sai2
ans = False
if (chega1 == n): chega1 = 0
if (chega2 == n): chega2 = 0
for i in xrange(n):
if (aux1 == aux2):
ans = True
break
if (aux1 == chega1 or aux2 == chega2):
break
aux1 = (aux1 + 1)... |
You have got a shelf and want to put some books on it.
You are given q queries of three types:
1. L id — put a book having index id on the shelf to the left from the leftmost existing book;
2. R id — put a book having index id on the shelf to the right from the rightmost existing book;
3. ? id — calculate the... | 3 | def prog():
from sys import stdin
q = int(stdin.readline())
p = [0 for i in range(200020)]
l,r = -1,1
y,x = stdin.readline().split()
for i in range(1,q):
y,x = stdin.readline().split()
x = int(x)
if y=='L':
p[x]=l
l-=1
elif y=='R':
... |
One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.
We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B ... | 3 | import sys
def input(): return sys.stdin.readline().strip()
n, m = map(int, input().split())
visited = [0 for i in range(n)]
edges = [[] for i in range(n)]
for i in range(m):
x, y = map(int, input().split())
edges[x-1].append(y-1)
edges[y-1].append(x-1)
part = [[], []]
i = 0
outside = 0
for j in range(n):
if not... |
We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).
Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where th... | 3 | h,w,m = map(int,input().split())
tate = [0]*(h+1)
yoko = [0]*(w+1)
basyo = []
for i in range(m):
hh,ww = map(int,input().split())
basyo.append((hh-1,ww-1))
tate[hh-1] += 1
yoko[ww-1] += 1
tt,yy = 0,0
x = max(tate)
for i in tate:
if i == x:
tt += 1
y = max(yoko)
for i i... |
Like most of the girlfriends, Ashima when asks for something, won’t stop until she gets that.
The way she gets that is by keep on repeating the same things again and again. Like if she wants chocolate, she will just keep on repeating “chocolate” again and again.
I have decided to answer to her demands as “Yes” or “No”... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
s = raw_input()
kases = int(raw_input())
length = len(s);
while(kases):
kases-=1
a,b=map(int,raw_input().split())
a-=1
b-=1
a = a%length
b = b%length
if s[a] == s[b]:
print "Ye... |
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team ... | 1 | n=input()
if n%2==0 :
print 'home'
else:
print 'contest'
|
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ ... | 3 | import sys
input = sys.stdin.buffer.readline
def print(val):
sys.stdout.write(str(val) + '\n')
def prog():
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
prefix = [0]*(n+1)
tuples = 0
for i in range(1,n-2):
prefix[a[i-1]] += ... |
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | 3 |
import math
# import sys
from collections import Counter, defaultdict, deque
def f(n, a):
# lg = [(0, 0)]
# for i in range(1, n):
# #print(i)
# if lg[i-1][0] <= a[i-1]:
# lg.append((a[i-1], i - 1))
# else:
# lg.append(lg[i - 1])
# rg = [None for i in ra... |
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.
It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h... | 3 | import string
two=[]
def ch():
for i in string.ascii_lowercase:
for j in string.ascii_lowercase:
two.append(i+j)
for k in string.ascii_lowercase:
two.append(i+j+k)
ch()
two.sort(key=len)
try:
t=int(input())
while(t):
t-=1
n=int(input(... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n=int(input())
count=0
for i in range(n):
str=input()
if(str=="++X" or str=="X++"):
count=count+1
else:
count=count-1
print(count) |
There are N dishes, numbered 1, 2, \ldots, N. Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it.
Taro will perform the following operation repeatedly until all the pieces of sushi are eaten:
* Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, a... | 3 | n = int(input())
A = list(map(int,input().split()))
one = A.count(1)
two = A.count(2)
three = A.count(3)
dp = [[[0]*(n+1) for _ in range(n+1)] for _ in range(n+1)]
for sushi in range(1,n+1):
for k in range(sushi+1):
for j in range(sushi-k+1):
i = sushi-k-j
if i != 0:
... |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | import re;
x=input()
x.lower()
if re.search("h.*e.*l.*l.*o",x):
print("YES")
else:
print("NO") |
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.
A team of SIS students is going to make a trip on a submarine.... | 3 | # s = list(map(int,input().split(" ")))
n = int(input())
mod = 998244353
ans = 0
arr = list(map(int,input().split(" ")))
for i in range(n):
x = arr[i]
curr = str(x)
req1 = curr[0]
for j in range(1,len(curr)):
req1 += "0"
req1 += curr[j]
req2 = req1 + "0"
v1 = int(req2)
v2 = int(req1)
v1 = ((v1%mod)... |
Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.
The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)
Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or abo... | 3 | x=int(input())
c=0
k=100
while(k<x):
k+=k//100
c+=1
print(c) |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | n=int(input())
a=list(map(int,input().split()))
for i in range(0,len(a)):
if a[i]%2==0:
a[i]=a[i]-1
for i in a:
print(i,end=" ")
print()
|
Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.
Not all of sellers are honest, so now some products could be more expensive than after a week of discou... | 3 | n, k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
paidmoney = sum(b)
c = sorted(list(map(lambda x,y :x-y , a,b)))
for i in range(n):
if i<k or c[i] <0 : paidmoney += c[i]
else: break
print(paidmoney)
|
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi... | 1 | x,y,z = map(int, raw_input().split())
a, b, c= map(int, raw_input().split())
a -= x
if a < 0:
print "NO"
else:
tot_first_two = a + b
tot_first_two -= y
if tot_first_two < 0:
print "NO"
else:
rest = tot_first_two + c
if rest >= z:
print "YES"
else:
... |
We have N integers. The i-th number is A_i.
\\{A_i\\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.
\\{A_i\\} is said to be setwise coprime when \\{A_i\\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.
Determine if \\{A_i\\} is pairwise coprime, setw... | 3 | import math
N = 1000001
spf = [*range(N)]
i = 2
while i * i < N:
if spf[i] == i:
for j in range(i * i, N, i):
if spf[j] == j:
spf[j] = i
i += 1
r = 'pairwise'
input()
d = None
u = set()
for x in map(int, input().split()):
d = math.gcd(d or x, x);
s = set()
while x > 1:
p = spf[x... |
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.
Can you reconst... | 3 |
a , b = map(int , input().split())
if a == b:
print(str(a) + str(1) , str(b) + str(2))
elif a == 9 and b == 1:
print(9 , 10)
elif a + 1 == b:
print(str(a) + str(9) , str(b) + str(0))
else:
print(-1) |
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.
Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing... | 3 | n , k , a, b = [int(i) for i in input().split()]
G = 'G'
B = 'B'
if a< b:
G, B = B, G
a, b = b, a
if a / (b+1) > k or b / (a+1) > k:
print('NO')
else:
while a+b > 0:
if a - b >= k :
print(G*k, end='')
a-=k
if b>0:
pri... |
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ... | 3 | n,m=map(int,input().split())
l=list(map(int,input().split()))
sum1=0
k=1
i=0
l.sort()
while(k<=m and i<len(l)):
if(l[i]<0):
sum1=sum1+l[i]
k+=1
i+=1
if(sum1<=0):
print(-sum1)
|
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.
During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s... | 1 | from decimal import *
k, d, t = map(int, raw_input().split())
f = d - k%d
if f==d:
f = 0
s = float(k)/float(t)+float(f)/float(2*t)
h = float(k) + float(f)
w = float(1)/float(s)
r = int(w)
h = float(h) * float(r)
s = float(s) * float(r)
if float(k)/float(t)+float(s)>=float(1):
h = float(h) + (float(1)-float(s))*float(... |
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes.
Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.
2 coverings are different if some 2 triangles are covered by the same diamond shape in ... | 3 | t = int(input())
b = []
for i in range(t):
n = int(input())
b.append(n)
for i in range(t):
print(b[i]) |
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |... | 3 | n=int(input())
h=list(map(int,input('').split()))
dp=[0]*n
dp[1]=abs(h[1]-h[0])
for i in range(2,n):
dp[i]=min(abs(h[i-1]-h[i])+dp[i-1],abs(h[i-2]-h[i])+dp[i-2])
print(dp[-1])
|
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 1 | a, b = [int(x) for x in raw_input().split()]
ret1 = (a / 2) * b
if a%2 == 1:
ret1 += b/2
ret2 = (b / 2) * a
if b%2 == 1:
ret2 += a/2
print max(ret1, ret2) |
One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.
He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the p... | 1 | import sys
difx = [-1, 0 , 1, -1, 0 , 1,- 1, 0 , 1]
dify = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
matrix = [[0 for x in xrange(1000)] for x in xrange(1000)]
if __name__=="__main__":
n,m = map(int,raw_input().split())
for i in xrange(0,m):
x,y = map(int,raw_input().split())
for j in xrange(0,9):
xnew = x-1 + difx[... |
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th... | 3 | d, sumTime = [int(i) for i in input().split()]
minTime, maxTime = [], []
day_list = []
k = 0
while k < d:
minTi, maxTi = [int(i) for i in input().split()]
minTime.append(minTi)
maxTime.append(maxTi)
day_list.append((minTi, maxTi))
k += 1
if sum(minTime) <= sumTime and sumTime <= sum(maxTime):
... |
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 | n = int(input())
a = [int(i) for i in input().split()]
a.sort(reverse = True)
a[1:1] = a.pop(),
print (*a) |
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
... | 3 | n, m = list(map(int, input().rstrip().split()))
words = []
op = 0
for i in range(n):
words += [input()]
final = [""]*n
for j in range(m):
flag = 1
for i in range(n - 1):
x = final[i] + words[i][j]
y = final[i + 1] + words[i + 1][j]
if x > y:
op += 1
flag = 0
... |
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x... | 3 | n=int(input())
a=list(map(int, input().split()))
a.sort()
minn=10000000000000
for i in range(n):
minn=min(minn, a[i+n-1]-a[i])
if n==1:
print(0)
else:
print(min(((a[2*n-1]-a[0])*(minn)),(a[n-1]-a[0])*(a[2*n-1]-a[n]))) |
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())
s = input()
a = list(map(int,s.split()))
a.sort()
for i in range(n):
print(a[i], end = ' ') |
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of di... | 1 | def buildPre(p):
pre = [0] * len(p)
i = 1
j = 0
while i < len(p):
if p[i] == p[j]:
j += 1
pre[i] = j
i += 1
else:
if j == 0:
i += 1
else:
j = pre[j - 1]
return pre
def hashP(oldVal, char):
... |
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.
Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the s... | 3 | MAXN = int(2e18)
def check(n, x, y, p, q):
np, nq = n * p, n * q
# print(x, y, np, nq)
if nq < y:
return False
diff = nq - y
return x <= np <= x + diff
def solve():
x, y, p, q = map(int, input().split())
l, r = 1, int(MAXN)
while l != r:
m = (l + r) // 2
if not c... |
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 | n = int(input())
p = set(map(int,input().split(' ')[1:]))
q = set(map(int,input().split(' ')[1:]))
a = p|q
if len(a) == n:
print('I become the guy.')
else:
print('Oh, my keyboard!') |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 1 | def process(n,d,s):
su=0
for i in range(len(s)):
su=su+s[i]
if d<(n-1)*10+su:
return -1
return (n-1)*2+(d-(n-1)*10-su)/5
if __name__=="__main__":
s=raw_input()
nums1=map(int,list(s.split(" ")))
s=raw_input()
nums2=map(int,list(s.split(" ")))
print process(nums1[0],nums1[1],nums2)
|
You are given two integers A and B.
Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section:
* Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100.
* The set of the squares painted white is ... | 3 | A,B=map(int,input().split())
mat=[]
for i in range(100):
array=["."]*20+["#"]*20
mat.append(array)
for i in range(B-1):
j=2*(i//10)
k=2*(i%10)
mat[j][k]="#"
for i in range(A-1):
j=2*(i//10)
k=2*(i%10)+21
mat[j][k]="."
print(100,40)
for i in range(100):
print("".join(mat[i])) |
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times.
Greg now only does three types of exercises: "chest" exercises,... | 3 | n = int(input())
arr = list(map(int, input().split()))
chest, biceps, back = 0, 0, 0
for i in range(0, n, 3):
chest += arr[i]
for i in range(1, n, 3):
biceps += arr[i]
for i in range(2, n, 3):
back += arr[i]
if chest > biceps and chest > back:
print("chest")
elif biceps > chest and biceps > back:
... |
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an → an, a1, a2, ..., an - 1.
Help Twi... | 1 | n = input()
list = raw_input().split()
list[0] = int(list[0])
mark = False
passed = False
flag = False
min = 1000000
pos = 0
for i in range(1, n):
list[i] = int(list[i])
if list[i - 1] > list[i]:
if mark:
flag = True
break
else:
mark = True
pos = ... |
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substring s[l … r] (1 ≤ l ≤ r ≤ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_... | 3 | a=input()
x=len(a)
print([[x-1,x][a[:x//2]!=a[:-1-x//2:-1]],0][len({*a})<2]) |
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.
We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this ... | 3 | n,k=map(int,input().split())
p=list(map(int,input().split()))
q=[0]
for i in range(0,n-k):
q.append(q[-1]+p[i+k]-p[i])
b=q.index(max(q))
s=0
for i in range(b,b+k):
s+=p[i]
print((s+k)/2) |
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 | import sys
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
N, K = [int(x) for x in input().split()]
if N % 2 == 1 and K % 2 == 0:
print("NO")
continue
if N % 2 == 0 and (2 * K > N and N - K == 1):
print("NO")
... |
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.
Organizers are stil... | 1 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys, math, random, operator
from string import ascii_lowercase, ascii_uppercase
from fractions import Fraction, gcd
#from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
from Queue import Queue, PriorityQueue
from collectio... |
Given an integer x, find 2 integers a and b such that:
* 1 ≤ a,b ≤ x
* b divides a (a is divisible by b).
* a ⋅ b>x.
* a/b<x.
Input
The only line contains the integer x (1 ≤ x ≤ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | x=int(input())
c=0
d=0
for i in range(1,x+1):
for j in range(1,x+1):
if i*j>x and i/j<x and i%j==0:
c,d=i,j
# print(i,j)
break
if c!=0 and d!=0:
print(c,d)
else:
print(-1) |
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should... | 3 | def get_sum_array(arr):
sums = [0] * len(arr)
for i in range(len(arr)):
if i == 0:
sums[i] = arr[i]
else:
sums[i] = sums[i - 1] + arr[i]
return sums
n = int(input())
costs = list(map(int, input().split()))
costs_sorted = sorted(costs)
costs_sum_array = get_sum_array... |
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 | a = str(input(''))
b = a.split(' ')
x = int(b[0])
y = int(b[1])
for i in range(1,100):
x = x*3
y = y*2
if x>y:
break
print(i) |
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | 3 | t=int(input())
for _ in range(t):
a,b,c,d=(map(int,input().split()))
print(b,c,c)
# print(min(len(list(s))-1,m))
|
Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.
Constraints
* 1 \leq N \leq 10^9
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the largest square number not exceeding N... | 3 | N = int(input())
X = int(N ** 0.5)
print(X **2) |
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!
Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho... | 1 | def do_solve(a, b, c):
u = max(b, c)
if a in [u - 1, u, u + 1]:
return u + u - b - c
elif a > u + 1:
u = a - 1
return u + u - b - c
else:
return u * 3 - a - b - c - 1
def solve(a, b, c):
return min(
do_solve(a, b, c),
do_solve(b, c, a),
do_sol... |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s=input()
h='hello'
i=0
flag=0
for c in s:
if(h[i]==c):
i+=1
if(i==5):
flag=1
break
if(flag==1):
print('YES')
else:
print('NO')
|
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights... | 3 | t = int(input())
for i in range(t):
n, k = map(int, input().split())
A = [0] + list(map(int, input().split()))
B = [0]*(len(A))
for j in range(2, n):
if A[j-1] < A[j] > A[j+1]:
B[j] = 1
now = 0
R = [0] * (len(A))
for q in range(1, k+1):
if B[q] == 1 and q != 1 and... |
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.
Vasya decided to organize information about the phone numbers of friends. You will be given n strings — all entries from Vasya's phone books. Each entry starts with a fri... | 3 | n = int(input())
ans = [[] for i in range(n)]
name = ['' for i in range(n)]
itog = [[''] for i in range(n)]
used = [[] for i in range(n)]
for i in range(n):
a = input()
j = 0
now = ''
while (a[j] != ' '):
now += a[j]
j += 1
place = 0
for k in range(n):
if (name[k] == now)... |
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 1 | # Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import Byt... |
Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | 3 | r,g,b,n=map(int,input().split())
nr=n//r
ans=0
for i in range(nr+1):
ng=(n-i*r)//g
for j in range(ng+1):
res=n-r*i-g*j
if res%b==0:
ans+=1
print(ans)
|
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String t is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin... | 3 | import sys
s = input()
cnt1 = cnt2 = no = 0
p = -1
q = len(s)
for i in range(len(s)):
if s[i] == '0':
cnt1 += 1
else:
p = i
break
for i in range(len(s)-1,-1,-1):
if s[i] == '0':
cnt2 += 1
else:
q = i
break
#print(s[p:q+1])
s2 = s[p:q+1]
if cnt1 > cnt2:
... |
You are given a string s consisting of n lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String s = s_1 s_2 ... s_n is lexicograp... | 3 | n=int(input())
t=input()
s=str(t)
if len(set(s))==1: print(s[1:])
else:
for i in range(len(s)-1):
if s[i]>s[i+1]:
print(s[:i]+s[i+1:])
break
else:print(s[:len(s)-1])
|
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | def foo():
n, s, t = map(int, input().split())
print(max(n-s, n-t)+1)
for _ in range(int(input())):
foo() |
[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())
sum = 0
while n != 0:
sum += (1/n)
n -= 1
print(sum) |
You are given an integer n and an integer k.
In one step you can do one of the following moves:
* decrease n by 1;
* divide n by k if n is divisible by k.
For example, if n = 27 and k = 3 you can do the following steps: 27 → 26 → 25 → 24 → 8 → 7 → 6 → 2 → 1 → 0.
You are asked to calculate the minimum numbe... | 1 | t = input()
for i in xrange(t):
n, k = map(int ,raw_input().split())
step = 0
while n > 0:
if n % k == 0:
step += 1
n /= k
else:
step += n%k
n -= n%k
print step
|
You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the length... | 3 | import sys
#sys.stdin = open("input.txt")
#sys.stdout = open("output.txt", "w")
n, n1 = map(int, input().split())
a1 = set(map(int, input().split()))
a2 = set(map(int, input().split()))
a = set(a1).intersection(a2)
if a:
print(sorted(list(a))[0])
else:
a = sorted(list(a1))[0]
b = sorted(list(a2))[0]
a... |
Anya loves to fold and stick. Today she decided to do just that.
Anya has n cubes lying in a line and numbered from 1 to n from left to right, with natural numbers written on them. She also has k stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.
Anya can stick a... | 1 | import sys
import itertools
from collections import defaultdict
factorials = [1] * 19
for i in range(1, 19):
factorials[i] = i * factorials[i - 1]
def cumsum(l):
n = len(l)
for i in range(1, n):
l[i] += l[i-1]
def enum(l):
global K, S
options = itertools.product(*([(0, 1, 2)] * le... |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | l=list(map(int,input().split()))
l.sort()
for i in range(3):
print(l[3]-l[i],end=" ") |
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, …, the lab with the number n^2 is at the highest place.
To transpor... | 3 | # !/usr/bin/env python3
# encoding: UTF-8
# Last Modified: 17/Oct/2019 08:24:21 PM
# ✪ H4WK3yE乡
# Mohd. Farhan Tahir
# Indian Institute Of Information Technology (IIIT), Gwalior
import sys
import os
from io import IOBase, BytesIO
def main():
n = int(input())
arr = [[0] * n for _ in range... |
Given is a three-digit integer N. Does N contain the digit 7?
If so, print `Yes`; otherwise, print `No`.
Constraints
* 100 \leq N \leq 999
Input
Input is given from Standard Input in the following format:
N
Output
If N contains the digit 7, print `Yes`; otherwise, print `No`.
Examples
Input
117
Output
Y... | 3 | s = input()
if "7" in s:
print("Yes")
else:
print("No") |
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s... | 1 | import math
def f():
n = int( raw_input())
d = {}
l = map(int,raw_input().split())
for i in range(n):
d [l[i]] = i
time = 0
for i in range(1,n):
sec = d[i]
time = time + abs(sec - d[i + 1] )
print time
f()
|
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1... | 1 | n,m = [int(c) for c in raw_input().split()]
g = [[int(c) for c in raw_input().split()] for i in xrange(n)]
print [4,2][any(g[0]+g[-1]+[r[0] for r in g] + [r[-1] for r in g])] |
Berland year consists of m months with d days each. Months are numbered from 1 to m. Berland week consists of w days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than w days.
A pair (x, y) such that x < y is ambiguous if day x of month y is the same... | 3 | from bisect import bisect_left, bisect_right
class Result:
def __init__(self, index, value):
self.index = index
self.value = value
class BinarySearch:
def __init__(self):
pass
@staticmethod
def greater_than(num: int, func, size: int = 1):
"""Searches for smallest eleme... |
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())
ans =1
s = input()
for _ in range(n-1):
next = input()
if s[-1] == next[0]:
ans +=1
s = next
print(ans) |
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())
if 2 <= n <= 100:
st = input()
a = 0
b = 0
i = 0
while i < n - 1:
if st[i] == 'F' and st[i+1] == 'S':
a += 1
elif st[i] == 'S' and st[i+1] == 'F':
b += 1
i += 1
if a > b:
print('NO')
if a < b:
print('YES')
i... |
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least nu... | 3 | s = input()
t = input()
end = crr = []
crr = ord(s[0]) - 96, int(s[1])
end = ord(t[0]) - 96, int(t[1])
a = crr[0] - end[0]
b = crr[1] - end[1]
print(max(a, -a, b, -b))
while a or b != 0:
p = ""
if a < 0:
p = "R"
a += 1
if a > 0:
p = "L"
a -= 1
if b < 0:
p += ... |
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | 3 | n=int(input())
mishka=0
chris=0
for i in range(n):
a,b=[int(x) for x in input().split()]
if a>b:
mishka+=1
if b>a:
chris+=1
if mishka>chris:
print('Mishka')
elif chris>mishka:
print('Chris')
else:
print('Friendship is magic!^^') |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | inp = input()
low = 0
upp = 0
for k in inp:
if str.isupper(k):
upp += 1
else:
low += 1
if low == upp:
inp = str.lower(inp)
elif low < upp:
inp = str.upper(inp)
else:
inp = str.lower(inp)
print(inp) |
Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:
* He never visits a point with coordinate less than 0, or a point with coordinate greater than L.
* He starts walking at a point with integer coordinate, and also finishes walking at a point with ... | 1 | # coding: utf-8
"""
o 999
o 2 3
x 2 0 2
o 2 1 2
x 2 1 2 1
o 2 1 3 1
o 2 1 3 2
o 3 1 3
x 3 2 3
o 3 2 2
- 0は両端のみ
- 偶奇の切り替わりが2回以下
0 zzoo
1 zzee
2 zzooee
3 zzeeoo
4 zzeeooee
5 zz
6 ???zz
"""
L = input()
A = [input() for _ in range(L)]
T = [L,L,L,L,L,0,L]
for a in A:
P = T
o = 1-a%2
e = 1-o
if a==0:
e = 2
... |
<image>
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in th... | 3 | from collections import deque
from math import *
import heapq
# n=int(input())
n,k=map(int, input().split())
s=input()
d={}
e={}
for i in range(len(s)):
d[s[i]]=i
e[s[i]]=0
counter=0
for j in range(len(s)):
# print(j,d[s[j]])
if d[s[j]]!=j and e[s[j]]==0:
e[s[j]]=1
counter+=1
elif... |
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | from math import floor
m, n = [int(i) for i in input().strip().split()]
area = m*n
print(int(floor(area/2))) |
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≤ x,y,z ≤ n), a_{x}+a_{y} ≠ a_{z} (not necessarily distinct).
You are given one integer ... | 3 | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wr... |
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... | 3 | from collections import defaultdict
import math
import sys
_ = input()
numbers = [int(i) for i in input().split(' ')]
numbers = sorted(numbers)
Q = int(input())
for _ in range(Q):
N = int(input())
if N < numbers[0]:
print(0)
continue
l = 0
r = len(numbers) - 1
while l <= r:
... |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n,h = map(int,input().split())
a = list(map(int,input().split()))
c = 0
for i in range(n) :
if(a[i]>h) :
c += 1
c += 1
print(c) |
As a New Year's gift, Dolphin received a string s of length 19.
The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`.
Dolphin wants to convert the comma-separated string s into a space-separated string.
Write a program to perform th... | 3 | a = input()
s = a.replace(',', ' ')
print(s) |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | # -*- coding: utf-8 -*-
"""
@author: c_py
"""
if __name__ == "__main__":
for _ in range(int(input())):
s = input()
res = s[:2]
s=s[2:]
for i in range(len(s)):
if i%2:
res=res+s[i]
print(res) |
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 | final_lvl = int(input())
little_x = [int(i) for i in input().split()]
del little_x[0]
little_y = [int(i) for i in input().split()]
del little_y[0]
for i in little_y:
little_x.append(i)
little_x = list(set(little_x))
if len(little_x) < final_lvl:
print("Oh, my keyboard!")
else:
if little_x[len(little_x)-1] <... |
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≤ i ≤ k). The store has an infinite number of packages of each type.
Polycarp wants to choose one type of packages and then buy several (one or... | 3 | from sys import stdin, stdout
import math
def main():
t = int(stdin.readline())
MX = 1.e9 + 1
prime = [2]
for i in range(3, math.ceil(math.sqrt(MX)),2 ):
is_prime = True
for x in prime:
if i % x == 0:
is_prime = False
break
if x > ... |
A tetromino is a figure formed by joining four squares edge to edge. We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:
a60bcb8e9e8f22e3af51049eda063392.png
Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession... | 3 | from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
INF = float("inf")
def ok(a, i, j, l, o):
if a > min(i, j, l):
return 0
i ... |
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend t... | 1 | class Friend:
def __init__(self, m, s):
self.money = m
self.factor = s
def __repr__(self):
return repr((self.money, self.factor))
[n, d] = map(int, raw_input().split())
friends = []
for i in range(0, n):
[m, s] = map(int, raw_input().split())
friends.append(Friend(m, s))
# s2 = sorted(friends, key=lambda... |
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "c... | 1 | s = raw_input()
print s[:-1]+s[::-1]
|
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 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
count = dict()
for i in a:
if count.get(i, 0) == 0:
count[i] = 1
else:
count[i] += 1
mset = set(a)
m = 1
for i in count:
if count[i] > m:
m = c... |
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost ... | 3 | n,s = list(map(int,input().split()))
arr = list(map(int,input().split()))
def buy(k):
global n,s,arr
if k==0:
return 0
temp = sorted([arr[i-1]+i*k for i in range(1,n+1)])
return sum(temp[:k])
def main():
f,l = 0,n
while f<l:
if f==l-1:
a,b=buy(f),buy(l)
... |
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $... | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: map_delete
# CreatedDate: 2020-07-15 11:23:30 +0900
# LastModified: 2020-07-15 11:29:50 +0900
#
import os
import sys
# import numpy as np
# import pandas as pd
def main():
q = int(input())
dictionary = {}
for _ in range(q):
command = ... |
A: Many Kinds of Apples
Problem Statement
Apple Farmer Mon has two kinds of tasks: "harvest apples" and "ship apples".
There are N different species of apples, and N distinguishable boxes. Apples are labeled by the species, and boxes are also labeled, from 1 to N. The i-th species of apples are stored in the i-th bo... | 3 | n = int(input())
C = list(map(int, input().split()))
q = int(input())
data = []
for _ in range(q):
t, x, d = map(int, input().split())
data.append([t, x, d])
apple = [0] * n
for D in data:
t, x, d = D
if t == 1:
apple[x-1] += d
if apple[x-1] > C[x-1]:
print(x)
b... |
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, …, s_n.
Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).
Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} ... | 3 | t=int(input())
def factors(n):
d=[1]
for i in range(2,int(n**0.5)+1):
if n%i==0:
d.append(i)
d.append(n//i)
return d
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
dp=[1 for i in range(n+1)]
for i in range(1,n+1):
d=factors(i)
... |
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo... | 3 | f=lambda:map(int,input().split())
n,m=f()
l=list(f())
pg=0
for i in range(n):
print((pg+l[i])//m,end=' ')
pg=(pg+l[i])%m
|
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input
The first line contains t... | 3 | temp = [int(x) for x in input().split()]
nA = temp[0]
nB = temp[1]
temp = [int(x) for x in input().split()]
k = temp[0]
m = temp[1]
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
if A[k-1] < B[-m]:
print('YES')
else:
print('NO')
|
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ... | 3 | t = int(input())
for _ in range (t):
a ,b ,c= (map(int , input().split()))
if c // b >= a :
print (1 , end = " ")
print (-1)
elif c // b < a and c <= a :
print (-1,end = " ")
print (b)
elif c // b < a and c > a :
print (1 ,end = " ")
print (b)
|
There are N gems. The value of the i-th gem is V_i.
You will choose some of these gems, possibly all or none, and get them.
However, you need to pay a cost of C_i to get the i-th gem.
Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.
Find the maximum possible value of X-Y.
Co... | 3 | N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))
print(sum([max(0, V[i] - C[i]) for i in range(N)])) |
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights... | 3 | import math,sys
import heapq
from collections import Counter,defaultdict
def li(): return list(map(int,sys.stdin.readline().split()))
def ls(): return list(map(int,list(input())))
def la(): return list(input())
def ii(): return int(input())
def dic(x): return defaultdict(lambda: x)
def isPrime(n):
i= 2
if n =... |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n = int(input())
arr = list(map(int, input().split()))
for i in range(n):
if arr[i] == 1:
print("HARD")
break
if i == n - 1:
print("EASY")
|
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 3 | n = int(input())
a = list(map(int, input().split()))
ans = k = 1
for i in range(n-1):
if a[i] < a[i+1]:
k += 1
if k > ans:
ans = k
else:
k = 1
print (ans) |
You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:
* 1 \leq a_i, b_i \leq 10^9 for all i
* a_1 < a_2 < ... < a_N
* b_1 > b_2 > ... > b_N
* a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a... | 3 | n = int(input())
p = [int(i) for i in input().split()]
a,b = [n*i+1 for i in range(n)],[0 for i in range(n)]
for i in range(n-1): print(a[i],end=" ")
print(a[-1])
for i in range(n): b[p[i]-1] = i-a[p[i]-1]
x = abs(b[-1])+1
for i in range(n-1): print(b[i]+x,end=" ")
print(1) |
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.
Given an input array, what i... | 3 | input()
s=list(map(int,input().split()))
def f(x):
if len(x)==1:
return 1
elif len(x)==2:
if x[0]<x[1]:
return 2
else:
return 1
elif x==sorted(x):
return len(x)
elif x==sorted(x)[::-1]:
return 1
else:
p=x[:len(x)//2]
q=x[len(x)//2:]
return max(f(p),f(q))
print(f(s)) |
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of e... | 3 | while True:
s = int(input())
if s == 0: break
a = [0 for i in range(10)]
for i in range(s):
n = int(input())
a[n]+= 1
for i in range(10):
if a[i]>0:
print('*'*a[i])
else:
print('-')
|
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 | data = list(map(int, input().split('+')))
data.sort()
print('+'.join(list(map(str, data))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.