problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)... | 3 | n=int(input())
a=list(map(int,input().split()))
mx=0
for i in range(n):
for j in range(n):
if j<i:
continue
#flip from i to j
cnt=0
for k in range(i):
if a[k]:
cnt+=1
for k in range(i,j+1):
if not a[k]:
cn... |
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes h... | 1 | n = input()
a = [int(ai) for ai in raw_input().split(" ")]
maxa = max(a)
c = [n+1 for _ in range(maxa+1)]
for i in range(n):
c[a[i]] = i + 1
minc = min(c)
print c.index(minc)
|
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 | s = input()
l = []
for i in range(0, len(s)):
if s[i] != '+':
l.append(s[i])
l.sort()
x = ""
for i in range(0, len(l) - 1):
x += l[i] + "+"
x += l[len(l) - 1]
print(x)
|
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | 1 | __author__ = 'abbas'
n = int(raw_input())
s = [int(x) for x in raw_input().split()]
cnt = 0
f = True
pidx = 0
for i in range(len(s)):
if s[i] == 1:
if f == True:
cnt += 1
f = False
pidx = i
else:
cnt += min(i - pidx, 2)
pidx = i
print cnt |
You are given a positive integer n.
Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0.
Your task is to find two integers a, b, such that 0 ≤ a, b ≤ n, a + b = n and S(a) + S(b) is the largest possible among all such pairs.
Input
The only line of input contains a... | 3 | n=int(input());
def solve(n):
temp=-1;
if(n<=9):return n
if(n%10!=9):temp=solve(n//10-1)+n%10+10
temp=max(temp,solve(n//10)+n%10);
return temp
print(solve(n));
|
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...
Your task is to print the k-th digit of this sequence.
Input
The first and only lin... | 1 | def generate(n, x):
a = 10 ** (n - 1)
a += x
return a
def solve(k):
k -= 1
n = 1
while k - n * 9 * 10 ** (n - 1) >= 0:
k -= n * 9 * 10 ** (n - 1)
n += 1
a = generate(n, k / n)
return str(a)[k % n]
# print solve([100] * 11)
n = input()
print solve(n)
|
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | n=int(input())
if n==abs(n):
print(n)
else:
p=abs(n)
a=[int(x) for x in str(p)]
if a[-1]>a[-2]:
a.pop(-1)
else:
a.pop(-2)
for i in range(len(a)):
a[i]=str(a[i])
if a[0]=="0":
print(0)
else:
print('-'+"".join(a))
|
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ... | 3 | from collections import deque
n, m = map(int, input().split())
A = list(map(int, input().split()))
for i in range(n):
A[i] = [A[i], i + 1]
A = deque(A)
while len(A) > 1:
x = [A[0][0] - m, A[0][1]]
A.popleft()
A.append(x)
if x[0] <= 0:
A.pop()
print(A[0][1]) |
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 | t = list(map(int, input().split(" ")))
k2 = t[0]
k3 = t[1]
k5 = t[2]
k6 = t[3]
t = min(k2, k5, k6)
s = t*256
k2 = k2 - t
if(k2>0):
s = s + 32*min(k2, k3)
print(s) |
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 | da,db=map(int,input().split())
if(da==db):
print(str(da)+'1',str(db)+'2')
elif(da+1==db):
print(str(da)+'9',str(db)+'0')
elif(da==9 and db==1):
print(9,10)
else:
print(-1) |
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:... | 1 | k=raw_input()
l=len(k)
x=1
result=0
for x in range (0,l) :
result=result + pow(2,x)
x=0
for x in range (0,l) :
if int(k[x:x+1])==7 :
result+= pow(2,l-1-x)
print result
|
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | 3 |
import collections
class Solution:
# a left, b right, c down, d up
def solve(self, a, b, c, d, x, y, x1, y1, x2, y2):
x += (b-a)
y += (d-c)
if a + b > 0 and x1 == x2:
return False
elif c + d > 0 and y1 == y2:
return False
elif x1 <= x <= x2 and... |
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ... | 1 | import time, math
t1 = time.time()
n, d = map(int, raw_input().split())
hotels = (map(int, raw_input().split()))
available = []
for i in range(n-1):
if hotels[i] + 2*d <= hotels[i+1]:
available.append(hotels[i] + d)
for i in range(n-1):
if hotels[n - i - 1] - 2*d >= hotels[n - i - 2]:
if (ho... |
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:
* For each i = 1,2,..., n-2, a_i = a_{i+2}.
* Exactly two different numbers appear in the sequence.
You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing s... | 1 | from collections import Counter
n=input()
A=map(int,raw_input().split())
M0=[]
M1=[]
for i in range(n):
if i%2==0: M0.append(A[i])
else: M1.append(A[i])
C0=Counter(M0)
C1=Counter(M1)
L0=sorted(C0.items(), key=lambda x:x[1], reverse=True)
L1=sorted(C1.items(), key=lambda x:x[1], reverse=True)
a0=None
a1=None
if ... |
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis... | 3 | T=int(input())
for i in range(T):
n=int(input())
a=n//2
if(n%2==0):
print("1"*a)
else:
print("7"+"1"*(a-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=list(input())
if s.count('A')>s.count('D'): print("Anton")
elif s.count('A')<s.count('D'): print("Danik")
else: print("Friendship") |
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o... | 1 | a = raw_input().strip()
b = raw_input().strip()
la = len(a)
lb = len(b)
if la != lb:
print max(la, lb)
elif a == b:
print -1
else:
print la |
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 | def main():
n = int(input())
columns = [int(x) for x in input().split()]
done = False
while not done:
done = True
for i in range(n-1):
if columns[i] > columns[i+1]:
done = False
x = columns[i] - columns[i+1]
columns[i] -= x
... |
"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 |
string1 = input().split()
number = int(string1[0])
referIndex = int(string1[1])
scores = []
string2 = input().split()
for i in range(number):
scores.append(int(string2[i]))
referNumber = scores[referIndex - 1]
count = 0
for i in range(number):
if scores[i] >= referNumber and scores[i] > 0:
count += ... |
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())
M=[]
C=[]
x=0
for i in range(n):
m,c=map(int,input().split(" "))
M.append(m)
C.append(c)
for i in range(n):
if (M[i]>C[i]):
x=x+1
if (M[i]<C[i]):
x=x-1
if(x>0):
print("Mishka")
if (x<0):
print("Chris")
if(x==0):
print("Friendship is magic!^^") ... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | from collections import Counter
def solve(opinion):
solvable = 0
for o in opinion:
if(Counter(o)['0'] <= 1):
solvable += 1
print(solvable)
team = []
n = int(input())
while(n > 0):
team.append(input())
n -= 1
solve(team)
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 1 | def run():
direction=raw_input()
lines=raw_input()
l1="qwertyuiop"
l2="asdfghjkl;"
l3="zxcvbnm,./"
plus=0
if direction=="R":
plus=-1
elif direction=="L":
plus=1
else:
plus=0
out=""
for each in lines:
for l in [l1,l2,l3]:
pos=l.find... |
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 | l,b=map(int,input().split())
flag=False
cnt=0
while(flag!=True):
if(l>b):
flag=True
else:
l*=3
b*=2
cnt+=1
print(cnt) |
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
<image>
He ate coffee mi... | 1 | n = int(raw_input())
dic = {
0:'zero',
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',
10:'ten',
11:'eleven',
12:'twelve',
13:'thirteen',
14:'fourteen',
15:'fifteen',
16:'sixteen',
17:'seventeen',
18:'eighteen',
19:'nineteen',
20:'twenty',
30:'thirty',
40... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 09:09:41 2018
@author: drogbatony
"""
p=input()
if 'H' in p or 'Q' in p or '9' in p:
print('YES')
else:
print('NO') |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | # https://codeforces.com/contest/546/problem/A
k, n, w = map(int, input().split())
temp = w * k * (w + 1) // 2 - n
if temp < 0:
print(0)
else:
print(temp) |
Ashish has n elements arranged in a line.
These elements are represented by two integers a_i — the value of the element and b_i — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i.
He can perform the following operation any number of t... | 3 | for _ in range(int(input())):
n=int(input())
li=list(map(int,input().split()))
ty=list(map(int,input().split()))
l=len(set(ty))
if li == sorted(li):
print("Yes")
else:
if l == 2:
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 | for _ in range(int(input())):
n = int(input())
e = (n+3)//4
print("9" * (n-e) + "8" * (e)) |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
a = list(map(int,input().split()))
m = 1
j = 0
while j < n-1:
k=1
j+=1
while a[j]>= a[j-1]:
k+=1
j+=1
if j == n:
break
if k > m:
m=k
print(m) |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | import math
n,k=map(int,input().split())
lst=list(int(num) for num in input().split())[:n]
possible=0
lst1=[]
for ele in lst:
if ele <=5-k:
possible+=1
lst1.append(ele)
if possible<3:
print('0')
else:
x=math.floor(len(lst1)/3)
print(x)
|
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | Q = int(input())
for q in range(Q):
a, b, c = map(int, input().split())
print((a + b + c) // 2) |
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | import sys,bisect
input=sys.stdin.readline
T=int(input())
for _ in range(T):
n=int(input())
A=list(map(int,input().split()))
flag=0
ind=0
for i in range(n-2,-1,-1):
if (A[i]<A[i+1] and flag==0):
flag=1
elif(A[i]>A[i+1] and flag==1):
ind=i+1
break... |
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | 3 | # -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *
class Scanner():
@staticmethod
... |
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.
Help Petya to split the integers. Each of n integers should be exactly in one group.
Input
The first line contains a s... | 3 | def main():
N = int(input())
sum_ = N * (N + 1) // 2
if sum_ & 1:
diff = 1
else:
diff = 0
if N & 1:
start = 2
group = [1]
else:
start = 1
group = []
mid = (start + N + 1) // 2
group.extend([i for i in range(start, mid, 2)])
group.exte... |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | t=int(input())
for _ in range(t):
k=int(input())
S=input()
ans=0
c=-1
for s in S:
if s=="A":
ans=max(ans,c)
c=0
else:
if c!=-1:
c+=1
print(max(ans,c)) |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | def main():
t = int(input())
for _ in range(t):
n, s = input().split(" ")
s = int(s)
total = 0
for nn in n:
total += int(nn)
ans = 0
p = 1
ten = 1
carry = False
while total > s:
num = int(n[-p])
if carry:... |
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) ≤ 3 ⋅ 10^5 and (r - l) is always odd.
You want to split these numbers into exactly (r - l + 1)/(2) pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one o... | 3 | l, r = map(int, input().split())
print('YES', *['%d %d' % (i, i + 1) for i in range(l, r + 1, 2)], sep='\n') |
There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.
For each of these bags, you will paint one of the balls red, and paint the other blue.
Afterwards, the 2N balls will be classified according to color.
Then, we will define the f... | 3 | import sys
from operator import itemgetter
inf = 1 << 30
def solve():
n = int(sys.stdin.readline())
# r_max = MAX, b_min = MIN にしたとき
r_max = b_max = 0
r_min = b_min = inf
p = []
for i in range(n):
xi, yi = map(int, sys.stdin.readline().split())
if xi > yi:
... |
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()
if len(a) <= 100:
if len(a) >= 7:
b = a.split("0")
c = a.split("1")
count = 0
for i in b:
if len(i) >= 7:
count+=1
for j in c:
if len(j) >= 7:
count+=1
if count > 0:
print("YES")
e... |
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a1 × b1 segments large and the second one is a2 × b2 segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself... | 1 | import fileinput
def calc(l, a, b, cnt):
if a * b in l: return
l[a*b] = (a, b, cnt)
if a % 2 == 0:
calc(l, a / 2, b, cnt + 1)
elif b % 2 == 0:
calc(l, a, b / 2, cnt + 1)
if a % 3 == 0:
calc(l, 2 * a / 3, b, cnt + 1)
elif b % 3 == 0:
calc(l, a, 2 * b / 3, cnt + ... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
zero = 0
one = 0
res = 0
for _ in range(n):
arr = list(map(int, input().split()))
for x in arr:
if x == 1:
one += 1
elif x == 0:
zero += 1
if one > zero:
res += 1
one = 0
zero = 0
print(res) |
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ... | 3 | import math
L=lambda:list(map(int,input().split()))
M=lambda:map(int,input().split())
I=lambda:int(input())
a=I()
b=I()
c=I()
for i in range(a,0,-1):
if 2*i<=b and 4*i<=c:
print(i*7)
exit()
print(0)
|
Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes... | 1 | for t in range(input()):
abc = [int(abc) for abc in raw_input().split(" ")]
abc.sort()
c,b,a = abc
ans = 0
d = [[1,0,0],[0,1,0],[0,0,1],[1,1,0],[1,0,1],[0,1,1],[1,1,1]]
for di in d:
if a >= di[0]:
if b >= di[1]:
if c >= di[2]:
a -= di[0]
b -= di[1]
c -= di[2]
ans += 1
print ans |
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 |
S = input().split(',')
print(" ".join(S)) |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | t = int(input())
for test in range(t):
n = int(input())
a = list(map(int, input().rstrip().split()))
M = max(a)
m = min(a)
if M == m:
print("NO")
else:
print("YES")
indiceM = -1
indicem = -1
for i, el in enumerate(a):
if el == M:
indiceM = i
... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n, k= map(int, input().split())
b=0
while b<k:
if n%10==0:
n=n//10
else:
n=n-1
b+=1
print(n) |
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 | n=int(input())
s=0
def lj(x):
s=0
for i in range(1,x+1):
s+=i
return s
for i in range(1,100):
lll=lj(i)
if n>=lll:
n-=lll
t=i
if n<0:
break
print(t)
|
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=[int(i) for i in input().split()]
m=min(a)
b=[]
s='YES'
for i in a:
b.append(i)
b.sort()
for i in range(n):
if a[i]!=b[i]:
if a[i]%m!=0 or b[i]%m!=0:
s='NO'
break
print(s) |
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n.
In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≤ l ≤ r ≤ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r.
For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ... | 3 | t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
id = 0
while(id < n and a[id] == b[id]):
id+=1
fl = False
if(id < n):
if b[id] - a[id] < 0:
print("NO")
continue
while(id... |
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together a... | 1 | n = input()
a = [map(int, raw_input().split()) for _ in xrange(n)]
dp = [[(0, '') for _ in xrange(n)] for _ in xrange(n)]
def log(x, c):
ans = 0
while x and x % c == 0:
x /= c
ans += 1
return ans
d = [[float('+inf')] * n for _ in xrange(n)]
b = [[0] * n for _ in xrange(n)]
def doit():
... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | x = list(input())
if len(list(set(x))) % 2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!') |
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.
Days go ... | 3 | n=int(input())
l=list(map(int,input().split()))
y=l+l
c=0
test=0
res=0
for i in range(2*n):
if test==0 :
c=0
if y[i]==1:
c+=1
test=1
else :
if y[i]==1:
c+=1
else :
res=max(res,c)
test=0
print(res)
... |
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ... | 3 | import sys
input = sys.stdin.readline
from collections import *
t = int(input())
for _ in range(t):
n = int(input())
xy = [tuple(map(int, input().split())) for _ in range(n)]
xy.sort(key=lambda t: (t[0], t[1]))
flag = True
for i in range(n-1):
xi, yi = xy[i]
xj, yj = xy[i+1]
... |
«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 ... | 1 | s = []
for i in range(0, 5): s.append(int(raw_input()))
ans = 0
for i in range(1, s[4] + 1):
q = 0
for j in range(0, 4):
if i % s[j] == 0: q = 1
ans += q
print ans |
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 | # cook your dish here
testcases=int(input())
for i in range(testcases):
n=input()
length=len(n);
k=int(n[0])
sum=(k-1)*10 + length*(length +1)//2
print(sum) |
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 | num=int(input())
if(num==0):
x,y=input(),input()
print("Oh, my keyboard!")
else:
pla1=set(map(int,input().split()))
pla2=set(map(int,input().split()))
tot=set(pla1.union(pla2))
ordered=[i for i in range(1,num+1)]
tot=list(sorted(list(tot)))
while(0 in tot):
tot.remove(0)
poll... |
A railroad running from west to east in Atcoder Kingdom is now complete.
There are N stations on the railroad, numbered 1 through N from west to east.
Tomorrow, the opening ceremony of the railroad will take place.
On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i t... | 3 | n = int(input())
c = [0] * n
s = [0] * n
f = [0] * n
for i in range(n-1):
c[i],s[i],f[i] = map(int,input().split())
for i in range(n):
t = 0
for j in range(i,n-1):
if t < s[j]: t = s[j]
elif t % f[j] == 0: pass
else: t = t + f[j] - t%f[j]
t += c[j]
print(t)
|
For given three points p1, p2, p, find the projection point x of p onto p1p2.
<image>
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xi, yi ≤ 10000
* p1 and p2 are not identical.
Input
xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq−1 ypq−1
In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv... | 3 | #!/usr/bin/env python3
# CGL_1_A: Points/Vectors - Projection
def proj(p1, p2, p):
x1, y1 = p1
x2, y2 = p2
x, y = p
if x1 == x2:
return x1 * 1.0, y * 1.0
elif y1 == y2:
return x * 1.0, y1 * 1.0
else:
dx = x1 - x2
dy = y1 - y2
return (((dx*x + dy*y)*dx -... |
A string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".
You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the result... | 3 | import sys; input = sys.stdin.readline
for TEST in range(int(input())):
l = int(input())
w = [0 for i in range(26)]
for c in input().rstrip():
w[ord(c)-ord('a')] += 1
for i in range(25, -1, -1):
while w[i]>0:
w[i]-=1
print(chr(ord('a')+i), end="")
print()
|
Ridbit starts with an integer n.
In one move, he can perform one of the following operations:
* divide n by one of its proper divisors, or
* subtract 1 from n if n is greater than 1.
A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 2... | 3 | #: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"
input = sys.stdin.readline
##########... |
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the o... | 3 | n=int(input())
l=[]
if(n==1 or n%2!=0):
print("-1")
else:
for i in range(n):
l.append(i+1)
for i in range(0,n,2):
l[i],l[i+1]=l[i+1],l[i]
k=0
for i in range(n):
if(l[i]==i+1):
k=1
break
if(k==1):
print("-1")
else:
print(*l) |
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon... | 3 | n = int(input())
h = [int(i) for i in input().split()]
energy = 0
count = h[0]
for i in range(1, n):
if h[i-1] - h[i] + energy < 0:
count += h[i] - h[i-1] - energy
energy = 0
else:
energy += h[i-1] - h[i]
print(count)
|
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams... | 3 | n = int(input())
a = input()
tmp = min(a.count('1'), a.count('2'))
print(tmp+(a.count('1')-tmp)//3)
# CodeForcesian
# ♥
|
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.
<image>
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th... | 3 | n=int(input())
a=[0]*(n+2)
a[0]=1
a[1]=1
for i in range(2,n+2):
a[i]=a[i-1]+a[i-2]
for i in range(1,n+1):
if i in a:
print('O',end='')
else:
print('o',end='')
|
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ... | 1 | # -*- coding:utf-8 -*-
#[n, m] = [int(x) for x in raw_input().split()]
def some_func():
"""
"""
n,k = [int(x) for x in raw_input().split()]
n_list = [int(x) for x in raw_input().split()]
count = 0
for i in range(1,n):
if n_list[i] - n_list[i-1]>2*k:
count+=2
elif n_l... |
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak... | 3 | # cook your dish here
x = input()
y = x.split(" ")
n = int(y[0])
k = int(y[1])
q = n//k
if(q%2==0):
print("NO")
else:
print("YES")
|
You are given an array a of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7... | 3 | R=lambda:map(int,input().split())
t,=R()
while t:
t-=1;n,l,r=R();a=sorted(R());i=j=q=0
while n:
n-=1
while i<n and a[i]+a[n]<l:i+=1
while j<n and a[j]+a[n]<=r:j+=1
q+=min(j,n)-min(i,n)
print(q) |
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ... | 3 | n,m = map(int,input().split())
a=dict(zip(range(1,n+1),map(int,input().split())))
while len(a) != 1:
i=1
while i != n+2 and len(a) !=1:
if i in a.keys():
if a.get(i)<=m :
del a[i]
else:
a[i]-=m
i+=1
print(list(a.keys())[0])
|
A substring is a string of characters that is contained in another string. For example, the substrings of "abcdef" could be "abc", "bc", "cdef", "e" and so on. But, "bca", "ace", and "g" are not substrings of "abcdef".
Your task is to count the number of non-empty substrings possible of a given string such that all c... | 1 | a=raw_input()
n=len(a)
count=1
ans=0
for i in range(0,n-1):
if(a[i]==a[i+1]):
count=count+1
else:
ans+=(count*(count+1))/2
count=1
ans+=(count*(count+1))/2
print ans |
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth... | 3 | ## necessary imports
import sys
input = sys.stdin.readline
from math import log2, log, ceil
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binom... |
Given a set of integers (it can contain equal elements).
You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).
Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:
* m... | 3 | # Author : Pratyaydeep↯Ghanta
import sys,threading
def inpt(): return sys.stdin.readline().rstrip()
def read(): return [int(x) for x in inpt().split()]
# Am I debugging, check if I'm using same variable name in two places
def mex(a):
for i in range(107):
if i not in a:
return i
def main():
_... |
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.
Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n... | 3 | n = int(input())
x = input()
num_of_1 = x.count("1")
first = int(x, 2)
def f(x):
if x == 0:
return 0
return 1 + f(x % bin(x).count('1'))
if num_of_1 == 1:
for i in range(n):
if x[i] == '1':
print(0)
elif i == n-1:
print(2)
else:
print(1... |
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())
x=0
for i in range(n):
a=str(input())
if a=='++X' or a=='X++':
x+=1
else:
x-=1
print(x)
|
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.
On ... | 3 | n,a,b = map(int, input().split())
c = list(map(int, input().split()))
s=0
for i in range(n//2):
if c[i]==c[n-1-i]:
if c[i]==2:
s+=min(a,b)*2
else:
if c[i]==2 or c[n-1-i]==2:
if c[i]==2:
s+=a if c[n-1-i]==0 else b
else:
s+=a if c... |
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100).
The first line of... | 3 | t=int(input())
for _ in range(t):
n=int(input())
a=[i for i in range(1,2*n+1)]
m=[int(i) for i in input().split()]
l=[]
for e in m:
k=e
l.append(k)
while(True):
e=e+1
if e not in m and e not in l:
l.append(e)
break
... |
Polycarp wrote on the board a string s containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.
After that, he erased some letters from the string s, and he rewrote the remaining letters in any order. As a result, he got some new string t. You have to find it with some ad... | 3 | for _ in range(int(input())):
s = input()
n = int(input())
m = n
b = list(map(int,input().split()))
c = ['']*m
freq = [0]*26
i = 25
for elem in s:
freq[ord(elem)-ord('a')]+=1
while n>0 and i>=0:
zero=[]
count = 0
for j in range(m):
if b... |
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ... | 3 | p = int(input())
a = set(map(int, input().split()))
p = int(input())
b = set(map(int, input().split()))
fl = False
for i in a:
for j in b:
if ((i+j) not in a) and ((i+j) not in b):
print(i, j)
fl = True
break
if(fl):
break
|
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 | import math
n, m, a = input().split()
n = int(n)
m = int(m)
a = int(a)
n = math.ceil(n/a)*math.ceil(m/a)
print(n) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())
s = input()
count = 0
lst = [s[0]]
for i in s[1:]:
if lst[-1] == i:
count += 1
lst.append(i)
print(count)
|
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:
* For each i = 1,2,..., n-2, a_i = a_{i+2}.
* Exactly two different numbers appear in the sequence.
You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing s... | 3 | from collections import Counter
N = int(input())
V = list(map(int,input().split()))
even = Counter(V[1::2]).most_common() + [(0, 0)]
odd = Counter(V[::2]).most_common() + [(0, 0)]
if even[0][0] != odd[0][0]:
print(N-even[0][1]-odd[0][1])
else:
print(min(N-even[0][1]-odd[1][1], N-even[1][1]-odd[0][1]))
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 1 | n=int(input());
if (n>=4 and n%2==0):
print("YES");
else:
print("NO"); |
Multiplication of Big Integers II
Given two integers $A$ and $B$, compute the product, $A \times B$.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the product in a line.
Constraints
* $-1 \times 10^{200000} \leq A, B \leq 10^{200000}$
Sample Input 1
5 8
Sa... | 3 | (x,y)=map(int,input().split(' '))
print(x*y);
|
A country has a budget of more than 81 trillion yen. We want to process such data, but conventional integer type which uses signed 32 bit can represent up to 2,147,483,647.
Your task is to write a program which reads two integers (more than or equal to zero), and prints a sum of these integers.
If given integers or t... | 3 | N = int(input())
for i in range(N):
a = int(input())
b = int(input())
c = a+b
if len(str(c)) > 80:
print("overflow")
else:
print(c)
|
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ... | 3 | n, k = map(int,input().split())
x= list(map(int,input().split()))
count = 0
for i in x:
if i>=x[k-1] and i!=0:
count+=1
print(count) |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | s = input()
c = s.count('7') + s.count('4')
if c == 4 or c == 7:
print('YES')
else:
print('NO') |
You are given the array a consisting of n elements and the integer k ≤ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ... | 3 | n,k = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
cnt = {}
stp = {}
ans = 100000000000
for i in a:
x=i
y=0
while 1:
cnt[x] =cnt.get(x,0)+1
stp[x] =stp.get(x,0)+y
if cnt[x]==k:
ans=min(ans,stp[x])
if x==0:
break
y +=1
... |
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide... | 3 | def pow1(x, base):
if base == 0:
return 1
sq = pow1(x, base // 2)
sq = (sq * sq) % mod
if base % 2:
sq *= x
return sq
def sum_range(n):
return (n * (n + 1)) // 2
n, mod = int(input()), 1000000007
level = pow1(2, n)
print(sum_range(level) % mod)
|
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ... | 3 | import sys
LI=lambda:list(map(int, sys.stdin.readline().strip('\n').split()))
MI=lambda:map(int, sys.stdin.readline().strip('\n').split())
SI=lambda:sys.stdin.readline().strip('\n')
II=lambda:int(sys.stdin.readline().strip('\n'))
n=II()
aid={v:i for i, v in enumerate(MI(), 1)}
dist={}
for i, v in enumerate(MI(), 1):
... |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 1 | #!/usr/bin/python
from __future__ import division
from sys import stdout,stdin
#from copy import deepcopy
import math
def solve(x):
for j in xrange(3,10000):
if ((j-2)*180)/j == x:
return "YES"
return "NO"
n=int(input())
for i in xrange(n):
x=int(input())
print solve(x)
|
Berland annual chess tournament is coming!
Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.
Thus, organizers sh... | 3 | n=int(input())
a2=sorted(list(map(int,input().split())))
b1=[]
for i in range(n):
b1.append(a2[len(a2)-1])
a2.remove(a2[len(a2)-1])
if max(a2)<min(b1):
print('YES')
else:
print('NO') |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | n=int(input())
for i in range(n):
m=input().split()
a=int(m[0])
b=int(m[1])
if a%b!=0:
r=b-(a%b)
print(r)
else:
print(0)
|
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())
z=list(input().split())
m=str()
for i in range(n):
z[i]=int(z[i])
for i in range(n):
if z[i]%2==0:
z[i]-=1
for i in range(n):
m+=str(z[i])+' '
print(m)
|
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the... | 1 | input()
b = map(int,raw_input().split())
c = sorted(b)
c.reverse()
for item in b:
print c.index(item) +1, |
Given a permutation p of length n, find its subsequence s_1, s_2, …, s_k of length at least 2 such that:
* |s_1-s_2|+|s_2-s_3|+…+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2.
* Among all such subsequences, choose the one whose length, k, is as small as possible.
If mul... | 3 | t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
ans=[arr[0]]
i=1
while(i<n-1):
if abs(arr[i]-ans[-1])+abs(arr[i+1]-arr[i])>abs(arr[i+1]-ans[-1]):
ans.append(arr[i])
i+=1
ans.append(arr[-1])
print(len(ans))
print(*ans)
|
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and foun... | 3 | s = input()
s = s[0] + s[2] + s[4] + s[3] + s[1]
ans = str((int(s) ** 5) % 100000)
ans = ('0' * (5 - len(ans))) + ans
print(ans) |
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces ... | 3 | n, *lst = list(map(int, input().split()))
dp = [float("-inf")] * (n+1)
dp[0] = 0
for i in range(1, n+1):
maxx = float("-inf")
for x in lst:
if i - x >= 0:
maxx = max(1+ dp[i-x], maxx)
if maxx != float("-inf"):
dp[i] = maxx
print(dp[n])
|
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.
Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p.
Now the elimination rou... | 3 | import itertools
p, x, y = map(int, input().split())
d = (x - y) // 50
p -= 26
i0 = (x // 50 - d) % 475
for k in itertools.count(-d):
i = i0
for _ in range(25):
i = (i * 96 + 42) % 475
if i == p:
print(0 if k <= 0 else (k + 1) // 2)
exit()
i0 += 1
if i0 >= 475:
... |
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 | def winner(s):
if s.count('A') > s.count('D'):
return "Anton"
elif s.count('D') > s.count('A'):
return "Danik"
return "Friendship"
n = int(input())
print(winner(input()))
|
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.
However, all is not... | 3 | N = int(input())
S = input()
res = 1
for i in range(1, N):
res += S[i] != S[i-1]
print(min(res+2, N)) |
Statement: Security is the major factor, which is prohibiting hackers letting into bank accounts online. But still, we have breached 2nd level security of SBIS bank and a final level is kept for you. Your task is simple, we are receiving an integer token every time we try to send an authorization request. After analysi... | 1 | t=input()
for j in range (t):
z=raw_input()
x=[]
for i in range(len(z)):
if z[i]=='2':
x.append('cde')
if z[i]=='7':
x.append('acf')
if z[i]=='6':
x.append('b3')
if z[i]=='9':
x.append('c6a')
print ''.join(x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.