problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | a = input()
l = a.split('+')
l.sort()
print('+'.join(l)) |
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string s.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" <image>... | 3 | n = int(input())
s = list(input())
for i in range(n):
if s[i] == '1':
for j in range(i+1, n):
if s[j] == '1':
s[j] = ''
print(''.join(s)) |
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | t = int(input())
for testcase in range(t):
n = int(input())
s = input()
lef,rit,s1=0,0,0
for i in range(n-1):
if s[i]>s[i+1]:
s1=1
break
if s1==0:
print(s)
else:
for i in range(n):
if s[i]=='1':
lef=i
bre... |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | def compare_words(word1,word2):
word1 = word1.lower();
word2 = word2.lower();
if word1<word2:
print('-1');
elif word1==word2:
print('0');
else:
print('1');
def read_line():
word1 = input();
word2 = input();
return word1,word2;
if __name__... |
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ... | 3 | from sys import stdin
c=int(stdin.readline().strip())
pos=[-1 for i in range(200)]
for caso in range(c):
n=int(stdin.readline().strip())
s=list(map(int,stdin.readline().strip().split()))
for i in range(n):
pos[s[i]]=i
op=0
vis=[False for i in range(n+2)]
for i in range(1,n+1):
... |
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | x,y=-1,-1
for i in range(5):
t=input().strip().split()
if '1' in t:
x=i
y=t.index('1')
print(abs(x-2)+abs(y-2)) |
You have a digit sequence S of length 4. You are wondering which of the following formats S is in:
* YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order
* MMYY format: the two-digit representation of the month and the last t... | 3 | S=input()
s1=int(S[0:2])
s2=int(S[2:5])
if 1<=s1<=12:
print("AMBIGUOUS" if 1<=s2<=12 else "MMYY")
else:
print("YYMM" if 1<=s2<=12 else "NA") |
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0.
On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2... | 3 | # cook your dish here
import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
import math
import collections
from sys import stdin,stdout,setrecursionlimit
import bisect as bs
setrecursionlimit(2**20)
M = 10**9+7
T = int(stdin.readline())
# T = 1
def DFSr(i,j):
m[i][j] += 1
if... |
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure:
* The crow sets ai initially 0.
* The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi... | 1 | # # # # l = map(int,raw_input().split())
# # # # ans=0
# # # # l[0]=max(l[0],l[2])
# # # # l[1]=min(l[1],l[3])
# # # # ans+=l[1]-l[0]+1
# # # # if(ans<=0):
# # # # print 0
# # # # else:
# # # # if(l[4]>=l[0] and l[4]<=l[1]):
# # # # print ans-1
# # # # else:
# # # # print ans
# # # n=int(raw_input())
# # # l=ma... |
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 3 | n= [int(i) for i in input().split()]
list1 = [int(i) for i in input().split()]
list1.sort()
curr = 1
maxim =0
num =-1
for i in range(len(list1)):
if num != list1[i]:
num = list1[i]
maxim = max(curr, maxim)
curr = 1
else:
curr += 1
maxim = max(curr, maxim)
pr... |
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())
m=[]
l=0
for i in range(n):
k=str(input())
m.append(k)
for j in range(0,len(m)):
if m[j]=="X++" or m[j]=="++X":
l+=1
if m[j]=="X--" or m[j]=="--X":
l-=1
print(l) |
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 | """
Satwik_Tiwari ;) .
21st AUGUST , 2020 - FRIDAY
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO,... |
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But t... | 1 | #A. Caisa and Sugar
a,b = map(int,(raw_input().strip().split()))
def tim(a,b):
c = 0
m = True
for x in xrange(a):
d,e = map(float,(raw_input().strip().split()))
d *= 100
t = d+e
if t<=b*100:
m = False
if c < (b*100 -t)%100:
c = (b*100 -... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n,t=map(int,input().strip().split())
line=list(input())
for i in range(t):
line2=line.copy()
for j in range(len(line)-1):
if line2[j]=="B" and line2[j+1]=="G":
line[j], line[j+1] = line[j+1], line[j]
"".join(line)
print(''.join(line))
|
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage... | 1 | import fileinput
readline = fileinput.input()
def rotate90(sqr):
newSquare = [list() for x in range(len(sqr))]
for i in range(len(sqr)):
for j in range(len(sqr)):
newSquare[len(sqr)-i-1].append(sqr[j][i])
return newSquare
def compareSquares(sqr1,sqr2):
for i in range(len(sqr1)):
... |
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 | def solution(arr, n , h):
ctr = 0
for i in arr:
if i <= h:
ctr += 1
else:
ctr += 2
return ctr
if __name__ == "__main__":
n, h = map(int, input().split())
arr = list(map(int, input().split()))
print(solution(arr, n, h)) |
Ron is a happy owner of a permutation a of length n.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is... | 1 | import sys
if sys.subversion[0] == "PyPy":
import io, atexit
sys.stdout = io.BytesIO()
atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
sys.stdin = io.BytesIO(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip()
RS = raw_input
RI = lambda x=int: map(x,RS().split(... |
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds:
* divide the number x by 3 (x must be divisible by 3);
* multiply the number x by 2.
After each operation, Polycarp writes down the result on the boar... | 3 | n = int(input())
li = list(map(int, input().split()))
g = {}
def dfs(e, v, order):
if e not in v:
v[e] = 1
if e % 3 == 0:
if (e // 3) in g:
order.append(e // 3)
dfs(e // 3, v, order)
if e * 2 in g:
order.append(e * 2)
dfs(... |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | 3 |
import collections
from functools import lru_cache
def read():
return input().strip()
def readInt():
return int(input().strip())
def readList():
return list(map(int, input().strip().split()))
t = readInt()
for i in range(t):
n = readInt()
print(" ".join(map(str, [i for i in range(1, n+1)])... |
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add... | 3 | def get_input():
s = input()
first_stick = s[0:s.find('+')]
second_stick = s[(s.find('+')+1): s.find('=')]
first_number = len(first_stick)
second_number = len(second_stick)
#print('the first number is: %d' %(first_number))
#print('the 2nd number is: %d' %(second_number))
result_stick = s... |
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels:... | 1 | n = int(raw_input())
p = map(int, raw_input().split())
fail = 0
vowels = set(list("aeiouy"))
for i, line in enumerate([raw_input().strip() for _ in xrange(n)]):
cnt_vowels = 0
for word in line.split():
tmp = len(filter(lambda c: c in vowels, list(word)))
cnt_vowels += tmp
if p[i] != cnt_vowe... |
Many of us are familiar with collatz sequence. Know the problem is, There is a fight going between the students of the class they have splitted up into two groups the odd rulers and the even rulers. To resolve this fight sir will randomly pick up the numbers and are written on the board. Teacher stated that if the tota... | 1 | for tc in range(int(input())):
n=input()
esum,osum,count=0,1,0
while n!=1:
if n%2==0:
esum+=n
n=n//2
else:
osum+=n
n=3*n+1
count+=1
if esum%count>osum%count:
print('Even Rules')
elif esum%count<osum%count:
print('Odd Rules')
else:
print('Tie')
#print(esum,osum,count) |
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number... | 3 | n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
for i in range(n):
a[i] -= b[i]
a.sort(reverse=True)
i,j=0,n-1
tot=0
while i <= j:
while a[i] + a[j] <= 0 and j > i:
j -= 1
tot += j - i
i += 1
print(tot)
|
The only difference between easy and hard versions is constraints.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
*... | 1 | "Template made by : https://codeforces.com/profile/c1729 , github repo : https://github.com/cheran-senthil/PyRival"
from __future__ import division, print_function
import bisect
import math
import itertools
import sys
from atexit import register
if sys.version_info[0] < 3:
from io import BytesIO as stream
else:
... |
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins.
Constraints
* N is an integer between 1 and 10000 (inclusive).
* A is an integer between 0 and 1000 (inclusive).
Input
Input is given from Standard Input in the following format:
N
A
Output... | 3 | a=int(input())
b=int(input())
if a%500 <= b:
print("Yes")
else:
print("No") |
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.... | 1 | print sum([1 for _ in xrange(int(raw_input())) if sum(map(int, raw_input().split()))>=2]) |
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must b... | 3 | def gen(k, n, p):
if k == n:
ans.append(p)
return
gen(k + 1, n, p + [1])
gen(k + 1, n, p + [0])
n, l, r, x = map(int, input().split())
m = list(map(int, input().split()))
ans = []
count = 0
gen(0, n, [])
for i in range(len(ans)):
now = []
for j in range(len(ans[i])):
if ans[... |
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».
The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | 1 | def to_binary(number):
result = []
if number <= 1:
result.append(number)
else:
while True:
quotient = number / 2
reminder = number % 2
result.append(reminder)
if quotient == 1:
result.append(1)
break
... |
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 | while True:
try:
from sys import stdin, stdout
n = stdin.readline()
n = int(n)
print "NO\n" if n % 2 > 0 or n < 3 else "YES\n"
except:
break
if __name__ == '__main__':
pass |
Chef is playing a game on a sequence of N positive integers, say A1, A2, ... AN. The game is played as follows.
If all the numbers are equal, the game ends.
Otherwise
Select two numbers which are unequal
Subtract the smaller number from the larger number
Replace the larger number with the result from above (see the e... | 1 | from fractions import gcd
for t in range(int(raw_input())):
n=int(raw_input())
ans=0
N=map(int,raw_input().split())
for i in N:
ans=gcd(ans,i)
print ans |
Alice has N boxes, and each box has certain non zero number of chocolates. These boxes are numbered from 1 to N.
Alice is planning to go to wonderland. She wants to carry exactly K number of chocolates and she can carry only 2 boxes. So she wants to know the number of ways in which she can select 2 boxes such that t... | 1 | def go(arr, k):
count = 0
occurences = {}
i = 0
for n in arr:
if n < k:
try:
occurences[n] += 1
except Exception:
occurences[n] = 1
while occurences:
n, n_count = occurences.popitem()
m = k - n
m_count = occurences.get(... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | n=int(input())
count=0
while n:
if n>=5:
n-=5
count+=1
elif n>=4:
n-=4
count+=1
elif n>=3:
n-=3
count+=1
elif n>=2:
n-=2
count+=1
else:
n-=1
count+=1
print(count)
|
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows:
<image>
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain... | 1 | R, C = map(int, raw_input().split())
a = [raw_input() for i in xrange(R)]
print len([(i, j) for i in xrange(R) for j in xrange(C) if 'S' not in a[i] or 'S' not in [a[k][j] for k in xrange(R)]])
|
There are n children numbered from 1 to n in a kindergarten. Kindergarten teacher gave a_i (1 ≤ a_i ≤ n) candies to the i-th child. Children were seated in a row in order from 1 to n from left to right and started eating candies.
While the i-th child was eating candies, he calculated two numbers l_i and r_i — the num... | 3 | n=int(input())
l=[int(x) for x in input().split()]
r =[int(x) for x in input().split()]
flag=1
a=[n-l[i]-r[i] for i in range(n)]
for i in range(n):
cl=0
cr=0
for j in range(i):
if a[j]>a[i]:
cl+=1
for k in range(i+1,n):
if a[k]>a[i]:
cr+=1
if cl!=... |
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are n stages available. The rock... | 1 | n, k = map(int, raw_input().split())
s = sorted(raw_input())
count = ord(s[0]) - ord('a') + 1
last = ord(s[0]) - ord('a')
c = 1
for i in range(1, len(s)):
if c >= k:
break
if ord(s[i]) - ord('a') - last > 1:
last = ord(s[i]) - ord('a')
count += last + 1
c += 1
if c < k:
pri... |
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separat... | 3 | #
n=int(input())
a=list(map(int,input().split()))
a=sorted(a)
if a[0]==a[-1]:
print(-1)
else:
print(*a) |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 |
n = int(input())
lst = input().split()
lst = [int(x) for x in lst[:]]
rlst = lst[:]
rlst.reverse()
#print(rlst)
if max(lst)==min(lst):
print(0)
else:
maxi = lst.index(max(lst))
mini = rlst.index(min(lst))
mini = n-mini-1
#print(maxi)
#print(mini)
if maxi < mini:
ans = maxi + (n-mini-1)
print(ans)
els... |
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements.
Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu... | 3 | for _ in range(int(input())):
X = list(map(int, input().split()))
Numbers = list(map(int, input().split()))
Temp = X[1]
Sequence = []
MyDict = {}
MySet = list(sorted(set(Numbers), reverse=True))
Size = len(MySet)
Index = 0
while Temp != 0:
if Index == Size:
MyDict... |
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number a, the second player wrote number b. How many ways ... | 3 | a,b=map(int,input().split())
wina=0
winb=0
draw=0
for i in range(1,7):
if abs(i-a)==abs(i-b):
draw+=1
elif abs(i-a)>abs(i-b):
winb+=1
else:
wina+=1
print(wina,draw,winb) |
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki... | 1 |
n = raw_input()
for i in range(len(n)):
if n[i] == "." and n[i-1] == "9":
print "GOTO Vasilisa."
break
elif n[i] == "." and int(n[i+1]) < 5:
print int(n.split(".")[0])
break
elif n[i] == "." and int(n[i+1]) >= 5:
print int(n.split(".")[0]) + 1
break
|
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≤ i ≤ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc... | 3 | def printres(res):
print("YES")
print(' '.join(map(str, res)))
def main():
cc = [int(a) for a in input().split()]
nz = []
for i,c in enumerate(cc):
if c > 0:
nz.append(i)
if len(nz) == 1:
if cc[nz[0]] == 1:
printres([nz[0]])
else:
prin... |
The squirrel Chokudai has N acorns. One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.
His plan is as follows:
1. Get out of the nest with N acorns in his hands.
2. Go to Exchange A and do some trades.
3. Go to Exchange B and do some trades.
4. Go to Exchange A and do some... | 1 | import sys
range = xrange
input = raw_input
def main():
n = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
DP = [0]*(n+1)
DP[n] = n
for j in range(3):
sell = A[j]
extra = B[j] - sell
if extra > 0:
for i in reversed(range(sell,len(DP)))... |
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | 3 | n = int(input())
ls = list(map(int, input().split()))
ls.sort()
res = set()
for elt in ls:
if elt>1 and elt-1 not in res:
res.add(elt-1)
elif elt not in res:
res.add(elt)
elif elt+1 not in res:
res.add(elt+1)
print(len(res))
|
New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.
Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly — the part which take... | 3 | q = int(input())
for rw in range(q):
n,s = map(int,input().split())
l = list(map(int,input().split()))
pref = [0] * n
pref[0] = l[0]
for i in range(1,n):
pref[i] = pref[i-1] + l[i]
if sum(l) <= s:
print(0)
else:
wyn = 1
best = 0
#print(pref)
for i in range(n):
le = i
p = n - 1
mid = n - 1
... |
You are given two integers A and B as the input. Output the value of A + B.
However, if A + B is 10 or greater, output `error` instead.
Constraints
* A and B are integers.
* 1 ≤ A, B ≤ 9
Input
Input is given from Standard Input in the following format:
A B
Output
If A + B is 10 or greater, print the string `e... | 3 | A,B=map(int,input().split())
print("error" if 10<=A+B else A+B)
|
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 | k,n,w = input().split()
k,n,w = int(k), int(n), int(w)
s = (w*(w+1)/2)*k
res = n-s
if res>0:
print(0)
else:
print(int(abs(res))) |
In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N. M bidirectional roads connect these cities. The i-th road connects City A_i and City B_i. Every road connects two distinct cities. Also, for any two cities, there is at most one road that directly connects them.
One day, it ... | 3 | # 問題の趣旨:できるだけ辺が少なくなるように2つの完全グラフに分けたい
# まず、2つの完全グラフに分けられるのかを調べる必要がある。
# これが不可能であれば-1を出力して即座に終了。
# 分けられる場合は、できるだけ街の数を均等にしたい。
# 以下のアルゴリズムを考える。
# まずお互い繋がっていない都市の組A,Bを選ぶ。
# すると、Aにしか繋がっていない街、Bにしか繋がっていない街、
# 両方に繋がっている街の3グループに分かれる。
# 最初の2グループについてはグループのサイズを保存しておく。
# 最後のグループが空でない場合は、このグループに対してまた同様の処理を行う。
# 街がなくなるか、両方に繋がっている街のグル... |
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 ... | 1 | n, k = map(int, raw_input().strip().split(' '))
xs = map(int, raw_input().strip().split(' '))
M = 200002
d = [[] for i in range(M)]
for x in xs:
count = 0
d[x].append(0)
while x > 0:
x /= 2
count+=1
d[x].append(count)
ans = 1000000000
for x in xrange(M):
if len(d[x]) < k:
continue
d[x].sort(... |
We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.
It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).
Consider the following action:
* Ch... | 3 | n,m,k=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
a=[0]
b=[0]
for i in range(n):
a.append(a[i]+A[i])
for i in range(m):
b.append(b[i]+B[i])
j=m
ans=0
for i in range(n+1):
if a[i]>k:
break
while b[j]>(k-a[i]):
j-=1
ans=max(ans,j+i)
print(ans) |
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed... | 3 | from decimal import *
import math
def main():
(l, r, k) = (int(x) for x in input().split())
solver(l, r, k)
def solver(l, r, k):
getcontext().prec = 40
dl = Decimal(l)
dr = Decimal(r)
dk = Decimal(k)
start = math.ceil(dl.ln() / dk.ln())
raw2 = dr.ln() / dk.ln()
if almostEqual(raw2, int(raw2) + 1):
end = i... |
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (... | 3 | a, b, s = list(map(int, input().split()))
x = s - (abs(a) + abs(b))
if x < 0 or x % 2:
print('No')
else:
print('Yes') |
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i.
This year 2D decided to cultivate a new culture, but what exactly he d... | 3 | n = int(input())
a = list(map(int, input().split()))
a.sort()
sm = sum(a)
ans = sm
for i in range(n):
s = sm
x = a[0]
y = a[i]
for j in range(1, y + 1):
if y % j == 0:
q = x * j
w = y // j
m = s - x - y + q + w
if m < ans: ans = m
print(ans)
|
You are given a string S of length 3 consisting of `a`, `b` and `c`. Determine if S can be obtained by permuting `abc`.
Constraints
* |S|=3
* S consists of `a`, `b` and `c`.
Input
Input is given from Standard Input in the following format:
S
Output
If S can be obtained by permuting `abc`, print `Yes`; otherwis... | 1 | s = raw_input()
if (s[0] != s[1]) and (s[0] != s[2]) and (s[1] != s[2]):
print "Yes"
else:
print "No"
|
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 | #python3
word = str(input())
mid = len(word) / 2
low = 0
upper = 0
for o in word:
if (o.islower()):
low += 1
if (low >= mid):
print(word.lower())
break
else:
upper += 1
if (upper > mid):
print(word.upper())
break
|
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by... | 1 | #!/usr/bin/env python
import sys
(a, b, n) = [int(i) for i in raw_input().split()]
a *= 10
for i in range(10):
if (a + i) % b == 0:
a += i
print str(a) + '0' * (n - 1)
sys.exit()
print -1 |
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 | s=str(input())
n=0
for i in range(len(s)):
if ord(s[i])>=97:
n=n+1
N=len(s)-n
if N>n:
s=s.upper()
else:
s=s.lower()
print(s)
|
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on).
There are lanterns on the... | 3 | t=int(input())
for i in range(0,t):
a=list(map(int,input().split()))
L=a[0]
v=a[1]
l=a[2]
r=a[3]
p=[]
'''if l%v!=0 and r%v!=0:
print(L-((r-l)//v))
elif l%v!=0 or r%v!=0:
print(L-((r-l)//v)-1)
elif l%v==0 and r%v==0:
print(L-((r-l)//v)-2)'''
print(L//v-r//v... |
You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.
Constraints
* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N... | 3 | input();s=input();k=s[int(input())-1]
for x in s:print(k if k==x else'*',end='') |
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | import sys
sys.setrecursionlimit(10**7)
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip() # ignore trailing spaces
t = ni()
for i in range(t):
ans = 10 ** 13
n = ni()
s = na()
s.sort()
for i in range(len(s) - 1)... |
You are given an array [a_1, a_2, ..., a_n] such that 1 ≤ a_i ≤ 10^9. Let S be the sum of all elements of the array a.
Let's call an array b of n integers beautiful if:
* 1 ≤ b_i ≤ 10^9 for each i from 1 to n;
* for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or... | 3 | import sys,os,io
input = sys.stdin.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
T = int(input())
ans = [0]*T
for t in range(T):
n = int(input())
A = list(map(int,input().split()))
B = [0]*n
for i in range(n):
B[i] = 1<<(A[i].bit_length()-1)
print(*B) |
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o... | 3 | n, m, k = [int(x) for x in input().split()]
P = [int(x) for x in input().split()]
curPage = (P[0] - 1)//k + 1
itemCount = 1
shift = 0
res = 0
for i in range(1, len(P)):
p = P[i];
pos = p - shift
page = (pos - 1)//k + 1
if curPage == page:
itemCount += 1
else:
# curPage < page
... |
Let's play Amidakuji.
In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines.
<image>
In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first... | 3 | w = int(input())
c = [i for i in range(1, w + 1)]
n = int(input())
for i in range(n):
a, b = map(int, input().split(","))
r = c[a - 1]
c[a - 1] = c[b - 1]
c[b - 1] = r
for i in range(w):
print(c[i])
|
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 | if __name__ == "__main__":
int(input())
cols = map(int, input().split(" "))
print(*sorted(list(cols)), sep = ' ') |
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a wi... | 3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 18:49:02 2020
@author: dennis
"""
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
... |
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there ... | 3 | ###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ... |
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | 3 | import sys
input = lambda: sys.stdin.readline().strip()
n, k = map(int, input().split())
S = list(input())
if n==1 and k==1: print(0)
elif k==0: print(''.join(S))
else:
cnt = 0
if S[0]!='1':
S[0] = '1'
cnt+=1
for i in range(1, n):
if cnt==k: break
if S[i]!='0':
S... |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | test_cases=int(input())
for _ in range(test_cases):
n,k=map(int,input().split())
a= list(map(int,input().split()))
b= list(map(int,input().split()))
answer=sum(a)
a.sort()
b.sort(reverse=True)
for i in range(k):
if (b[i]>a[i]):
answer=answer+b[i]-a[i]
print(answer) |
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | 3 | t = int(input())
for i in range(t):
coins = int(input())
val = []
diff = []
for j in range(1,coins+1):
val.append(2**j)
for j in range(1,coins):
h1 = val[0:int(coins/2)]
h2 = val[int(coins/2):int(coins+1)]
a = sum(h1)
b = sum(h2)
diff.append(a)
diff.append(b)
val[j-1],val[j]=val[j],val[... |
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). F... | 3 | import array
t=int(input())
for i in range(1,t+1):
n,x,y,d=map(int,input().split())
z1=(n-x)//d+(0 if(n-x)%d==0 else 1)+((n-y)//d if (n-y)%d==0 else 10000000000)
z2=(x-1)//d+(0 if(x-1)%d==0 else 1)+((y-1)//d if (y-1)%d==0 else 10000000000)
if (y-x)%d==0:
print(abs((y-x)//d))
elif (n-y)%d==0 ... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | import sys;
inp=sys.stdin.read().split()
n = int(inp[0])
inp = inp[1:]
sentence = ""
if 1 <= n <= 100:
for x in inp:
if len(x) <= 10:
sentence += f"{x}\n"
else:
length = len(x)-2
sentence += f"{x[0]}{length}{x[len(x)-1]}\n"
print(sentence) |
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the ... | 3 | for _ in range(int(input())):
n,k=map(int,input().split())
p=n-1
ext=k%p
tim=k//p
if(ext==0):
print(int(n*tim+ext-1))
else:
print(int(n*tim+ext)) |
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim... | 1 | from __future__ import division
from collections import Counter as ctr
from math import ceil, log, factorial, sqrt
# reads a line of input and converts into a list of ints
# 1 1 3 => [1, 1, 3]
def rl():
return [int(i) for i in raw_input().split()]
# reads n lines of input (if n defined) and returns a list of strin... |
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 | x = input()
if(x<=2):
print "NO"
elif(x%2 == 0):
print "YES"
else:
print "NO"
|
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 | limak,bob = input().split(" ")
limak = int(limak)
bob = int(bob)
year = 0
while limak <= bob:
limak *= 3
bob *= 2
year += 1
print(year)
|
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | for _ in range(int(input())):
m,n=map(int,input().split())
k=abs(m-n)
if k%10==0:
print(k//10)
else:
print((k//10)+1) |
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | 3 | s1 = list(map(int, input().split(":")))
s2 = list(map(int, input().split(":")))
hours = s1[0] + s2[0]
minutes = s1[1] + s2[1]
if hours % 2 == 1:
minutes += 60
if minutes > 118:
minutes -= 120
hours += 1
h = str(hours//2)
m = str(minutes//2)
ans = "0" * (2-len(h)) + h + ":" + "0" * (2-len(m)) + m
print(an... |
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to trans... | 3 | def func(n,m):
if n>m or m%n != 0:
return -1
temp = m//n
c2=c3=0
while temp%2 == 0 :
c2+=1
temp//=2
while temp%3 == 0 :
c3+=1
temp//=3
if temp == 1 :
return c2+c3
else :
return -1
n,m = map(int,input().split())
c = func(n,m)
print(c) |
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 | import math
if __name__ == "__main__":
n, m = tuple(map(int, input().split()))
kids = list(map(int, input().split()))
mx = -1
mx_pos = 0
for i, kid in enumerate(kids):
if math.ceil(kid / m) >= mx:
mx = math.ceil(kid / m)
mx_pos = i
print(mx_pos + 1) |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | s, n = map(int, input().split())
li = [list(map(int, input().split())) for i in range(n)]
li.sort()
for p in li:
if s <= p[0]:
print("NO")
quit()
s += p[1]
print("YES") |
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically.
<image>
A pyramid with N=4 steps
Snuke wrote a per... | 3 | n,x=map(int,input().split())
if x==1 or x==2*n-1:
print("No")
else:
print("Yes")
if n==2:
b=[1,2,3]
else:
if x==2:
b=[i for i in range(2*n-1,n,-1)]+[i for i in range(1,n+1)]
elif x==2*n-2:
b=[i for i in range(n,2*n)]+[i for i in range(n-1,0,-1)]
el... |
As you have noticed, there are lovely girls in Arpa’s land.
People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.
<image>
Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are a... | 3 | def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
n = int(input())
a = list(map(int, input().split()))
for i in range(len(a)):
a[i] -= 1
lens = []
for i in range(len(a)):
now = i
l = 0
for j in range(3 * n):
l += 1
now = a[now]
if now == i:
br... |
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero:
<image>
Petr called his car dealer, who in... | 3 | n=int(input())
a=[]
for i in range(0,n):
now=int(input())
a.append(now)
ok=0
for i in range(0,1<<n):
tot=0
for j in range(0,n):
if (i>>j)&1==1:
tot=(tot+a[j])%360
else:
tot=(tot+360-a[j])%360
#print("tot ",tot)
if tot==0:
ok=1
if ok==1:
print... |
Boboniu gives you
* r red balls,
* g green balls,
* b blue balls,
* w white balls.
He allows you to do the following operation as many times as you want:
* Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the b... | 3 | for _ in range(int(input())):
r,g,b,w= list(map(int, input().split()))
m = min(r,g,b)
c = 0
for i in [r,g,b]:
if(i%2 != 0):
c+=1
if(m == 0):
if(w%2!=0):
c+=1
if(c>1):
print("No")
else:
print("Yes")
contin... |
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.
Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa... | 3 | n, m = map(int, input().split())
a = list(map(int, input().split()))
res = 0
for i in range(m):
l, r = map(int, input().split())
# print(sum(a[(l-1):r]))
if sum(a[l-1:r]) > 0:
res += sum(a[l-1:r])
print(res)
|
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... | 3 | n, d = list(map(int, input().rstrip().split()))
li = []
for i in range(n):
li += [list(map(int, input().rstrip().split()))]
li.sort(key=lambda x: x[0])
j = 0
f = 0
ans = li[0][1]
i = 0
while i < n:
while li[i][0] - li[j][0] >= d:
f -= li[j][1]
j += 1
f += li[i][1]
ans = max(ans, f)
i... |
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 | testTakers = int(input())
answerList = input()
for x in answerList:
if x == '1':
print("HARD")
exit()
print("EASY") |
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the mini... | 3 | S = input()
print(min([abs(753 - int(S[i] + S[i+1] + S[i + 2])) for i in range(len(S) - 2)])) |
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm.
The dorm has exactly one straight dryer — a 100 ce... | 3 | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n = mint()
a = []
for i in range(n):
a.append(tuple(mints()))
r = 0
for i in range(*a[0]):
r += 1
for j in range(1,len(a)):
z = a[j]
if z[0]<=i and z[1]... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | import sys
import math
import re
import io
#For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.
def solve(n):
ans = io.StringIO()
for i in range(n):
if i % 2 == 0:
ans.write("I hat... |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 | t = int(input())
for i in range(t):
n = int(input())
print(int(n/2)+n%2) |
A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means... | 3 | # python3
n = input()
a = list(map(int, input().split()))
len=0
n=int(n)
len=0
for i in range (1,n):
sc = a[i]-a[i-1]
if(sc>0):
len=i
break
if(sc<0):
len=i
break
fl=1;
if(len==0):
len=n
r=n%len
if(r==0):
lol=1
else:
print("NO")
exit(0)
for i in range (1... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | a = input()
x = list()
flag=0
for i in range(0,len(a)):
if a[i]=='4' or a[i]=='7':
flag+=1
if flag==4 or flag==7:
print("YES")
else:
print("NO")
|
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can:
* either choose position pos (1 ≤ pos ≤ n) and increase v_{pos} by k^i;
* or not choose any posit... | 1 | for _ in range(input()):
n, k = map(int, raw_input().split())
arr = map(int, raw_input().split())
dic = {}
for i in range(n):
pw = 0
while arr[i]:
if pw in dic:
dic[pw] += arr[i]%k
else:
dic[pw] = arr[i]%k
arr[i] /= k
pw += 1
if (not dic) or (max(dic.values()) < 2):
print "YES"
else:
p... |
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a... | 3 | N = int(input())
d = 1
pl = 0
mn = 0
apl = 0
amn = 0
for k in map(int,input().split()):
if k < 0: d = d * (-1)
if d < 0:
apl += mn
amn += pl
else:
apl += pl
amn += mn
if d < 0:
mn += 1
amn += 1
else:
pl += 1
apl += 1
print(amn, apl) |
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card.
Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with num... | 3 | from collections import Counter
n = int(input())
c = Counter()
for _ in range(n):
c[int(input())] += 1
if len(c) != 2 or list(c.values())[0] != list(c.values())[1]:
print('NO')
else:
print('YES')
print(*c.keys()) |
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of... | 1 | def main():
n, m, a, b = raw_input().split()
n = int(n)
m = int(m)
a = int(a)
b = float(b)
if b/m >= a:
print a*n
return
else:
q = n/m
n %= m
if b < a*n:
print int(q*b + b)
else:
print int(a*n+q*b)
if __name__ == '__main__': main()
|
Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted ... | 3 | def the_Artful():
n=int(input())
x=list(map(int,input().split()));
y=list(map(int,input().split()));
cpt=0
c1=set(x+y)
for i in range(n):
for j in range(n):
h=x[i]^y[j]
if h in c1:
cpt+=1
if (cpt%2==0):
print('Karen')
else:
... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 3 | m,n=map(int,input().split()[:2])
c='.'
for i in range(m):
if i%2==0:
print('#'*n)
else:
if c=='.':
print('.'*(n-1),end='')
print('#',end='')
c='#'
print(end='\n')
else:
print('#',end='')
print('.'*(n-1),end='')
... |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | 3 | for _ in range(int(input())):
n = int(input())
print(len(set(list(map(int,input().split()))))) |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | l = int(input())
list = input().split()
add = 0
for i in range(l):
add += int(list[i])
result = add / l
print(result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.