problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | n=int(input())
s1="I hate it"
s2="I hate that"
s3="I love it"
s4="I love that"
if n==1:
print(s1)
else:
for i in range(n-1):
if i%2==0:
print(s2,end=" ")
else:
print(s4,end=" ")
if n%2==0:
print(s3,end=" ")
else:
print(s1,end=" ") |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | S = input()
R = ""
for k in S.lower():
if k not in "aeiouy":
R+='.'+k
print(R)
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 1 | from decimal import Decimal
from math import ceil
n,m,a = raw_input().split(" ")
n = Decimal(n)
m = Decimal(m)
a = Decimal(a)
print int(ceil(n/a)*ceil(m/a)) |
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())
ans = 0
while n > 0 :
n -= 1
c = list(map(int, input().split()))
t = 0
for i in c :
if i == 1 : t += 1
if t >= 2 : ans += 1
print(ans)
|
You are given three integers a, b, k.
Find two binary integers x and y (x ≥ y) such that
1. both x and y consist of a zeroes and b ones;
2. x - y (also written in binary form) has exactly k ones.
You are not allowed to use leading zeros for x and y.
Input
The only line contains three integers a, b, and k (... | 3 | a, b, k = input().split()
a = int(a)
b = int(b)
k = int(k)
z = a
o = b
n = a + b
s1 = []
s2 = []
for i in range(n):
s1.append('0')
s2.append('0')
s1[0] = '1'
s2[0] = '1'
b -= 1
if a == 0 and b == 0 and k == 0:
print("YES")
print("1")
print("1")
exit(0)
if k > n - 2:
print("NO")
exit(0)
if b == 0:
if k ... |
"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=input().split()
n=int(n)
k=int(k)
list1=[]
a=input().split()
for i in a:
list1.append(int(i))
if max(list1)<=0 :
print(0)
else:
if list1[k-1]!=0:
number=0
for x in range(n):
if list1[x]>=list1[k-1]:
number+=1
print(number)
else:
number=0
... |
When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.
Constra... | 3 | print(input()[:3]) |
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 3 | le=int(input())
li=list(map(int,input().split()))
mxm=1
rat=1
for x in range(1,len(li)):
if(li[x-1]<li[x]):
rat+=1
else:
rat=1
mxm=rat if rat>mxm else mxm
print(mxm) |
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated i... | 3 | n, m = (int(x) for x in input().split())
if n < m:
print(-1)
else:
print((int((n-0.5)/(2*m))+1)*m) |
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is... | 3 | class Node:
def __init__(self, num, left, right):
self.value = num
self.left = left
self.right = right
EmptyTree = None
def make_node(num, left, right):
return Node(num, left, right)
def value(tree):
return tree.value
def left(tree):
return tree.left
def right(tree):
ret... |
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
Input
The first line contains a single integer n (1 ≤ n ≤ ... | 1 | def duplicateRemover(arr,n):
newArray = []
for i in range(n-1,-1,-1):
if(arr[i] not in newArray):
newArray.append(arr[i])
return newArray
n = int(raw_input())
lista = map(int,raw_input().split())
cleanArray = duplicateRemover(lista,n)
if len(cleanArray) == 1:
print 1
print cleanArray[0]
el... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | t=int(input())
for _ in range(0,t):
n=int(input())
a=list(map(int,input().split()))
a.sort()
if n==1:
print("YES")
else:
i=0
p=0
while i<len(a)-1:
if abs(a[0]-a[1])<=1:
a.pop(0)
else:
p=1
break
... |
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.
<image>
There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, .... | 3 | def inp():
return map(int, input().split())
n = int(input())
total, min = 0, 0
for i in range(n):
a, p = inp()
if (i == 0 or p < min):
min = p
total+=min*a
print(total)
|
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).
At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he... | 3 | import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.w... |
There are N integers, A_1, A_2, ..., A_N, written on a blackboard.
We will repeat the following operation N-1 times so that we have only one integer on the blackboard.
* Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.
Find the maximum possible value of the... | 3 | n=int(input())
a=list(map(int,input().split()))
a.sort()
hu=0
for b in a:
if b<0:
hu+=1
else:
break
if hu==0:
hu=1
if hu==n:
hu=n-1
ansl=[]
nowl=a[0]
for i in range(hu,n-1):
ansl.append((nowl,a[i]))
nowl-=a[i]
nowr=a[n-1]
for i in range(1,hu):
ansl.append((nowr,a[i]))
no... |
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right.
The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar... | 3 | n = int(input())
s = input()
a = [0 for i in range(10)]
def f(a, c):
for i in range(len(a)):
if c=='R':
if a[-i-1] == 0:
a[-i-1] = 1
break
else:
if a[i] == 0:
a[i] = 1
break
return a
for i in s:
if i.isdigit():
a[int(i)] = 0
else:
f(a, i)
print(''.join... |
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 | #Beautiful Matrix
for i in range(1,6):
lst=list(map(int,input().split()))
if 1 in lst:
idx=lst.index(1)+1
print(abs(i-3)+abs(idx-3))
break
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n = int(input())
f = True
c = [None] * n
for i in range(n):
c[i] = list(map(int, input().split()))
k = []
for i in range(3):
for j in range(n):
k.append(c[j][i])
if sum(k) != 0:
f = False
break
k.clear()
if f == True:
print('YES')
else:
print('NO')
|
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, …, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As... | 3 | n=int(input())
l=list(map(int,input().split()))
a=[l[0]]
for i in range(1,n):
a.append(l[i]-l[i-1])
lens=[]
for i in range(n):
flag=False
for j in range(i+1,n):
if(a[j%(i+1)]!=a[j]):
flag=True
break
if flag==False:
lens.append(i+1)
print(len(lens))
for i in lens:... |
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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 14:49:42 2018
@author: LX
"""
math = input()
sequence = ''
for i in range(0,len(math),2):
sequence += math[i]
new = sorted(sequence)
print('+'.join(new)) |
To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:
* 1 yen (the currency of Japan)
* 6 yen, 6^2(=36) yen, 6^3(=216) yen, ...
* 9 yen, 9^2(=81) yen, 9^3(=729) yen, ...
At least how many operations are required to withdraw exa... | 3 | N = int(input())
min_ = N
for i in range(N+1):
x = 0
n = i
while n > 0:
x += n % 6
n //= 6
n = N-i
while n > 0:
x += n % 9
n //= 9
min_ = min(min_, x)
print(min_)
|
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to at most once discard two or three cards wi... | 3 | disc = [0]
x=list(map(int, input().split(' ')))
x.sort()
for i in list(set(x)):
if x.count(i) >= 3:
disc.append(3 * i)
if x.count(i) == 2:
disc.append(2*i)
print(sum(x)-max(disc))
|
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 | import math as m
arr=list(map(int,input().split()))
k=arr[0]
n=arr[1]
w=arr[2]
x=k*w*(w+1)/2
y=x-n
z=m.ceil(y)
if z<=0 :
print("0")
else :
print(z) |
Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E).
Constraints
* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 100,000
* 0 ≤ wi ≤ 10,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-... | 3 | import heapq
def prim_heap(v):
used = [True] * v #True:不使用
edgelist = []
for e in edge[0]:
heapq.heappush(edgelist,e)
used[0] = False
res = 0
while len(edgelist) != 0:
minedge = heapq.heappop(edgelist)
if not used[minedge[1]]:
continue
v = minedge[1]
... |
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.
It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to bui... | 3 | def getilist():
return list(map(int, input().split()))
n = int(input())
a = sorted(getilist())
lb = 3e9
c = 0
for i in range(n-1):
t = abs(a[i] - a[i+1])
if t == lb:
c += 1
if t < lb:
lb = t
c = 1
print(lb, c)
|
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 | string1 = input().lower()
string2 = input().lower()
x = 0
n = 0
while x < len(string1):
if ord(string1[x]) > ord(string2[x]):
print("1")
break
elif ord(string1[x]) < ord(string2[x]):
print("-1")
break
x += 1
n += 1
if n == len(string1):
print("0") |
Print the circumference of a circle of radius R.
Constraints
* 1 \leq R \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
R
Output
Print the circumference of the circle. Your output is considered correct if and only if its absolute or relative error ... | 3 | i = int(input())
print(i*2*3.141) |
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th... | 1 | n=input();a=raw_input()
x=sum(1 for i,j in zip(sorted(a[:n]),sorted(a[n:])) if i>j)
y=sum(1 for i,j in zip(sorted(a[:n]),sorted(a[n:])) if i<j)
print 'YNEOS'[(x-n)*(y-n)!=0::2] |
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows t... | 3 | import math,sys
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
def Pr(x): sys.stdout.write(str(x)+'\n')
#sys.setrecurs... |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | n = int(input())
arr = list(map(int,input().split()))
count1 = arr.count(1)
count2 = arr.count(2)
count3 = arr.count(3)
count = arr.count(4) + count3 + int(count2/2)
count2 -= int(count2/2)*2
if (count1 == 0 and count2 == 1):
count += 1
count2 -= 1
if(count1>0):
if(count3 > 0):
if(count3>=count1):
count3 -= cou... |
You are given a string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is... | 3 | import random
t = int(input())
while t > 0:
s = list(input())
if s != s[::-1]:
print("".join(s))
else:
if s.count(s[0]) == len(s):
print(-1)
else:
while s == s[::-1]:
random.shuffle(s)
print("".join(s))
t -= ... |
You are given a tree (connected graph without cycles) consisting of n vertices. The tree is unrooted — it is just a connected undirected graph without cycles.
In one move, you can choose exactly k leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them w... | 3 | from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io impor... |
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least nu... | 3 | s = input()
t = input()
x0 = ord(s[0])
y0 = int(s[1])
x = ord(t[0])
y = int(t[1])
move = ""
n = 0
while True:
if (x == x0) and (y == y0):
break
if x > x0:
move += "R"
x0 += 1
elif x < x0:
move += "L"
x0 -= 1
if y > y0:
move += "U"
y0 += 1
elif ... |
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 | from sys import stdin
from collections import defaultdict
n = int(stdin.readline())
a = list(map(int, stdin.readline().rstrip().split(" ")))
b = list(map(int, stdin.readline().rstrip().split(" ")))
ad = {}
bd = {}
for i in range(n):
ad[a[i]] = i
bd[b[i]] = i
diffs = defaultdict(lambda : 0)
keys = list(ad.key... |
AtCoder Mart sells 1000000 of each of the six items below:
* Riceballs, priced at 100 yen (the currency of Japan) each
* Sandwiches, priced at 101 yen each
* Cookies, priced at 102 yen each
* Cakes, priced at 103 yen each
* Candies, priced at 104 yen each
* Computers, priced at 105 yen each
Takahashi wants to buy s... | 3 | x=int(input())
a=x//100
if a*100<=x<=a*100+(a*5):
print(1)
else:
print(0) |
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or... | 3 | def fastpow(base, exp, mod):
res = 1;
while exp > 0:
if (exp % 2) == 1:
res = (res * base) % mod
base = (base * base) % mod
exp //= 2
return res % mod
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
ans = fastpow(2, (a-1), 1000000007)
ans = fastpow(ans, (b-1... |
We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.
You are given Q queries.
In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.
Constraints
* 1≤Q≤10^5
* 1≤l_i≤r_i≤10^5
* l_i and r_i are odd.
* All input values ... | 3 | a=[0 for i in range(10**5+5)]
for i in range(3,10**5+3,2):
for j in range(3,int(i**0.5)+1,2):
if i%j==0 and j!=i:
break
else:
a[i]=1
a[3],a[2]=1,1
b=[0 for i in range(10**5+5)]
for i in range(3,10**5+3,2):
b[i]=a[i] and a[(i+1)//2]
c=[0]
for i in range(len(b)):
c.append(c[i]+... |
There are n students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ce... | 3 | n, k = map(int, input().split())
d = n // 2 // (k + 1)
c = k * d
print(d, c, n - d - c)
|
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 | n=int(input())
a=[]
for i in range (0,n):
a.append(input())
for i in range (len(a)):
if len(a[i])<=10:
print (a[i])
else:
x=len(a[i])
b=x-1
y=x-2
print(a[i][0]+str(y)+a[i][b])
|
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | #318A.Even Odds
sb=str(input())
sb=sb.split(' ')
n=int(sb[0])
k=int(sb[1])
import math
i=math.ceil(n/2)+0.5
if k<i:
print(str(2*k-1))
else:
print(str(2*k-2*math.ceil(n/2)))
|
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.
Each player can double his bid any number of times and triple his bid any number of ... | 3 | n = int(input())
a = list(map(int, input().split()))
for i in range(n):
while a[i] % 2 == 0:
a[i] = a[i] // 2
while a[i] % 3 == 0:
a[i] = a[i] // 3
f = True
for i in range(1, n):
if a[i] != a[i - 1]:
f = False
break
print('Yes' if f else 'No')
|
Input
The input contains a single integer a (0 ≤ a ≤ 63).
Output
Output a single number.
Examples
Input
2
Output
2
Input
5
Output
24
Input
35
Output
50 | 1 | if __name__== "__main__":
input = int(input())
bin_input = str(bin(input))[2:]
bin_input = bin_input.rjust(6,'0')
string_order = [0, 5, 3, 2, 4, 1]
bin_output = ""
for order in string_order:
bin_output += bin_input[order]
print(int(bin_output,2)) |
Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week.
Write a program which computes the amount of the debt in n weeks.
Input
An integer n (0 ≤ n ≤ 100) is g... | 3 | n=int(input())
m=100000
for i in range(n):
m=m*1.05
if m%1000==0:
pass
else:
m=m-m%1000+1000
print(int(m))
|
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 3 | a, b = map(int, input().split(' '))
out = a
nam = 0
while a>0:
a, nam = divmod(a+nam, b)
out += a
print(out) |
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose s... | 3 | for _ in range(int(input())):
for i in range(9):
row = input().replace('1','2')
print(row) |
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered ... | 3 | n = [int(j) for j in input().split()]
w = 0
for k in range(n[0]):
s = [int(j) for j in input().split()]
for j in range(n[1]):
if s[2*j] + s[2*j+1] > 0:
w += 1
print(w) |
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t... | 3 | n,a,b,c = [int(i) for i in input().split()]
if n%4==0:
print(0)
if (n+1)%4==0:
if 3*c<=a and 3*c<=b+c:
print(3*c)
if b+c<a and b+c<3*c:
print(b+c)
if a<=b+c and a<3*c:
print(a)
if (n+2)%4==0:
if 2*c<=b and 2*a>=2*c:
print(2*c)
elif 2*a<2*c and 2*a<b:
p... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | # Tram
n = int(input())
passengers = 0
max_passengers = 0
for i in range(n):
ai, bi = map(int, input().split())
passengers -= ai
passengers += bi
if passengers > max_passengers:
max_passengers = passengers
print(max_passengers) |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | for _ in range(int(input())):
n=int(input())
a=[int(x) for x in input().split()]
a.sort()
flag=0
for i in range(n-1):
if a[i]==a[i+1] or a[i]==a[i+1]-1:
continue
flag=1
break
if flag==1:
print("NO")
else:
print("YES") |
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.
To make a toast, each friend needs nl ... | 3 | #author: SanskarxRawat
n,k,l,c,d,p,nl,np=map(int,input().strip().split())
print(min(k*l//nl,c*d,p//np)//n)
|
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 a+b > 9 else a+b) |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | for s in[*open(0)][1:]:n=int(s);print(*n%4and['NO']or['YES']+[*range(2,n+1,2)]+[n+n//2-1]+[*range(1,n-1,2)]) |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 1 | #http://codeforces.com/problemset/problem/160/A
def twinCoins():
int(raw_input())
l = map(int, raw_input().strip().split())
s1 = sum(l)
s2 = 0
count = 0
l.sort(reverse=True)
for e in l:
s2 += e
s1 -= e
count += 1
if s2 > s1:
return count
print twinCoins()
|
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | def solve():
n, m = map(int, input().split())
a = [[] for _ in range(n)]
for i in range(n):
a[i] = list(map(int, input().split()))
row, col = 0, 0
for i in range(n):
flag = True
for j in range(m):
if a[i][j] == 1:
flag = False
break... |
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times.
Greg now only does three types of exercises: "chest" exercises,... | 3 | n=int(input())
b=list(map(int,input().split()))
j=1
ch=0
bi=0
ba=0
for i in range (n):
if j%3==1:
ch=ch+b[i]
if j%3==2:
bi=bi+b[i]
if j%3==0:
ba=ba+b[i]
j=j+1
if ba>bi and ba>ch :
print("back")
if bi>ba and bi>ch:
print("biceps")
if ch>ba and ch>bi:
print("chest") |
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | x = int(input())
for i in range(x):
y = str(input())
print((23 - int(y[0:2]))*60 + 60 - int(y[-2:])) |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 1 | n = input()
k = n / 4
if n % 4 == 0:
print(k - 1)
elif n % 4 == 2:
print(k)
else:
print(0)
|
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0.
The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied:
* The length of s is 1, and it consists of the character c (i.e. s_1=c);
* The lengt... | 3 | import string
t=int(input())
def find_num(s,i,suma):
#print(s,suma)
if len(s)==1:
if s[0]==string.ascii_lowercase[i]:
return 0
else:
return 1
else:
x=len(s)//2
s1=s[:x]
s2=s[x:]
c1=x-s1.count(string.ascii_lowercase[i])
c2=x-s2.count(string.ascii_lowercase[i])
suma+=min(c1+find_num(s2,i+1,suma)... |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 1 | #coding: utf-8
s1 = raw_input()
s2 = raw_input()
pile = raw_input()
if(len(s1)+len(s2)!=len(pile)):
print 'NO'
else:
array_s1 = []
array_s2 = []
array_pile = []
for letter in s1:
array_s1.append(letter)
for letter in s2:
array_s2.append(letter)
for letter in pile:
array_pile.append(letter)
array_s1.sort... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | forbidden = ["A", "O", "Y", "E", "U", "I", "a", "o", "y", "e", "u", "i"]
string = input()
string = "".join("." + x.lower() for x in string if x not in forbidden)
print(string)
|
When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.
You, the smartwatch, has found N routes to his home.
If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.
Find the smallest cost of a route that takes not l... | 3 | n,l = map(int,input().split())
ct = []
for i in range(n):
c,t = map(int,input().split())
if t <= l:
ct.append(c)
try:
print(min(ct))
except:
print('TLE') |
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | def randomize (arr, n):
arr=sorted(arr,reverse=True)
return arr
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
if(n==1):
print(*a)
else:
print(*randomize(a,n)) |
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 21:05:53 2020
@author: alexi
"""
#http://codeforces.com/problemset/problem/697/A
def pine_apple():
time = input().split()
time = [int(i) for i in time]
if time[0] == time[2]:
print("YES")
elif time[0] > time[2]:
print("NO")
... |
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | t=int(input())
for i in range(t):
n=int(input())
if(n==1):
print(0)
else:
a=0
b=0
while(n%2==0):
n=n//2
a+=1
while(n%3==0):
n=n//3
b+=1
if(n==1):
x=b-a
y=b
if(x>=0 and y>=0):
... |
Takahashi has many red balls and blue balls. Now, he will place them in a row.
Initially, there is no ball placed.
Takahashi, who is very patient, will do the following operation 10^{100} times:
* Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.
How ... | 1 | s=raw_input()
s=s.split(" ")
n=int(s[0])
a=int(s[1])
b=int(s[2])
q=n/(a+b)
r=n%(a+b)
if(r<a):print q*a+r
else:print (q*a+a)
|
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The on... | 3 | def result(n):
return 2 ** (n+1) - 2
if __name__ == "__main__":
n = int(input())
print("%d" % result(n)) |
Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minut... | 3 | tot=input().split()
n=int(tot[0])
P1=int(tot[1])
P2=int(tot[2])
P3=int(tot[3])
T1=int(tot[4])
T2=int(tot[5])
time_cuts=[]
for i in range(n):
cut=input().split()
cut[0]=int(cut[0])
cut[1]=int(cut[1])
time_cuts.append(cut)
energy=0
for i in range(n):
energy=energy+(time_cuts[i][1]-time_cuts[i][0])*P1
for... |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d... | 3 | maxn = 100000+10
ans = [0 for i in range(maxn)]
vis = [0 for i in range(maxn)]
s = input()
arr = s.split()
n = int(arr[0])
k = int(arr[1])
ans[0] = 1
cnt = k
for i in range(1, k+1):
tmp = ans[i-1] + cnt
if tmp > k+1 or vis[tmp]==1:
tmp = ans[i-1]-cnt
vis[tmp] = 1
ans[i] = tmp
cnt -= 1
prin... |
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including t... | 3 | h,w=map(int,input().split())
num=0
s=[str(input()) for i in range(h)]
for i in range(h):
num+=s[i].count("#")
if num>h+w-1:
print("Impossible")
exit()
print("Possible")
|
We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq i < N ) holds.
Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others.
Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible ... | 3 | from collections import defaultdict
n, x, d = map(int, input().split())
if d == 0:
if x == 0:
ans = 1
else:
ans = n + 1
else:
if d < 0:
x, d = -x, -d
intervals = defaultdict(list)
for i in range(n + 1):
# [l, r]
l = i * (i - 1) // 2
r = i * (2 * n - ... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | def hasDistinctDigits(n):
x = str(n)
return list(sorted(set(x))) == list(sorted(x))
n = int(input())
n += 1
while(hasDistinctDigits(n) == False):
n += 1
print(n)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | word = input()
word_list = list(word)
if word.istitle() and 2 <= len(word_list):
pass
elif word.isupper():
word = word.lower()
elif word_list[0].islower():
word_list_mod = word_list
word_list_mod.remove(word_list_mod[0])
word_list_mod_check = []
for i in word_list_mod:
word_list_mod_chec... |
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai ≤ bi).
Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola... | 3 | n = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]
x = y = -1 # x <= y
for z in B:
if x <= y <= z:
x, y = y, z
elif x <= z < y:
x, y = z, y
else:
x, y = x, y
print('YES' if x+y >= sum(A) else 'NO')
|
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be ... | 3 | n=int(input())
s=set()
a=map(int,input().split())
for i in a:
s.add(i)
while n in s:
print(n,end=' ')
n-=1
print()
|
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.
Natasha doesn't like when Vanya spends a long time pla... | 1 | n,x=map(int,raw_input().split())
print (abs(sum(map(int,raw_input().split())))+x-1)/x |
Phoenix has collected n pieces of gold, and he wants to weigh them together so he can feel rich. The i-th piece of gold has weight w_i. All weights are distinct. He will put his n pieces of gold on a weight scale, one piece at a time.
The scale has an unusual defect: if the total weight on it is exactly x, it will ex... | 1 |
# Author : raj1307 - Raj Singh
# Date : 02.05.2021
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())... |
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
Input
The single line of the input contains a pa... | 3 | #!/usr/bin/env python3
import sys
def get_ints():
return map(int, sys.stdin.readline().strip().split())
m, s = get_ints()
if (s==0 and m==1):
print("0 0")
elif (s==0 or s>9*m):
print("-1 -1")
elif (m==1):
print(str(s) + " " + str(s))
elif (s==1):
print(str(1)+"0"*(m-1) + " " + str(1)+"0"*(m-1))
e... |
Everybody knows of [spaghetti sort](https://en.wikipedia.org/wiki/Spaghetti_sort). You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you...
You come up with... | 3 | n=int(input())
a=list(map(int,input().split()))
for i in range(n-1):
if abs(a[i]-a[i+1])>=2:
exit(print('NO'))
print('YES') |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | def func(n):
if n % 2 == 0:
print(4, n-4, sep=' ')
else:
print(n-9, n-(n-9), sep=' ')
n = int(input())
func(n)
|
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white.
You think that this picture is not interesting enough. You consider a picture to be interesting... | 1 | n = input()
for i in xrange(n):
r, c = map(int, raw_input().split())
mcount_r=mcount_c=0
index_r=[]
index_c=[]
ans=[]
grid = []
for j in xrange(r):
grid.append(raw_input())
for u in xrange(r):
rs=0
for v in xrange(c):
if grid[u][v]=='*':
... |
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.
More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and ... | 3 | from sys import exit
n, m = map(int, input().split())
a = input()
b = input()
c = []
d = [0] * n
c = [i for i in range(n) if a[i] == b[i]]
l = len(c)
for i in range(min(l, n-m)):
d[c[i]] = a[c[i]]
if l < n-m:
u = n-m-l
if l + u + u > n:
print(-1)
exit(0)
else:
u = n-m-l
f... |
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 | def strength(drake):
return drake[0]
s, n = list(map(int, input().split()))
dragons = []
for i in range(n):
dragons.append(list(map(int, input().split())))
dragons.sort(key=strength)
isAlive = True
for drake in dragons:
if s <= drake[0]:
isAlive = False
break
else:
s += drake[... |
You are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k.
In one move, you can choose one lamp and change i... | 3 | for _ in range(int(input())):
n,k = map(int,input().split())
l = list(map(int,list(input())))
prefix = []
ans = 0
for i in range(n):
ans += l[i]
prefix.append(ans)
dp = [0 for i in range(n)]
# print(l)
l = l[::-1]
prefix1 = []
ans = 0
for i in range(n):
ans += l[i]
prefix1.append(ans)
for j in range... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | s = input().lower()
q = 'aeiouy'
for i in s:
if i not in q:print('.',i,sep='',end='') |
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move... | 3 | def solve():
n=int(input())
m = (n+1)>>1
res = m*(m+1)*(2*m + 1)
res /= 6
res -= m*m
print(int(8*res))
t=int(input())
for _ in range(t):
solve()
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 1 | s=raw_input()
vowels=["A", "O", "Y", "E", "U", "I","a", "o", "y", "e", "u", "i"]
s=list(s)
s=[x for x in s if x not in vowels]
s='.'.join(s).lower()
print '.'+s |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 |
T = int(input());
for i in range(T):
n,k = map(int,input().split());
a = list(map(int,input().split()));
b = list(map(int,input().split()));
a.sort();
b.sort();
j = len(b)-1;
for i in range(n):
if a[i] < b[j] and k:
a[i] = max(a[i],b[j]);
k = k ... |
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.
You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.
Input
The f... | 3 | import math
n=int(input())
nums=list(map(int,input().split()))
l=[1]*1000001
l[1]=0
root=int(math.sqrt(1000000))
for i in range(2,root+1):
if l[i]==1:
for j in range(i*i,1000001,i):
l[j]=0
for x in nums:
r=int(math.sqrt(x))
if r*r==x and l[r]==1:
print("YES")
else:
p... |
Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | 3 | r,g,b,n=map(int,input().split())
dp=[0]*(n+1)
dp[0]=1
for x in [r,g,b]:
for i in range(n+1):
if i+x<=n:dp[i+x]+=dp[i]
print(dp[n]) |
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 | t = int(input())
for i in range(t):
a, b = list(map(int, input().split()))
if (a%b) == 0:
print(0)
else:
print(b - (a % b))
|
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.
There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea... | 3 | n=int(input())
for i in range(n):
a,b=[int(x) for x in input().split(' ')]
c=abs(a-b)
d=0
d+=int(c/5)
c=c%5
d+=int(c/2)
c=c%2
d+=c
print(d)
|
Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configura... | 1 | n = input();
n = int(n);
a = list(map(int,raw_input().split()));
k = sum(a)/n;
moves = 0;
for i in range(n):
if(a[i] > k):
a[i+1]+=a[i]-k;
moves+=a[i]-k;
elif(a[i] < k):
a[i+1]-=k-a[i];
moves+=k-a[i];
print moves;
|
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | 3 | [a,b]=list(map(int,input().split()))
ans=[str(min(a,b)),str(((a+b)-(2*min(a,b)))//2)]
print(' '.join(ans))
|
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m.
Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | def solve():
n,m=map(int,input().split())
*a,=map(int, input().split())
*b,=map(int, input().split())
sa=set(a);sb=set(b)
if sa&sb:
print("YES")
for c in sa&sb:
print(1,c)
break
else:
print("NO")
t =int(input())
for _ in range(t):
sol... |
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.
Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.
Dima can buy boxes at a factory. The factory pr... | 3 | N,K = map(int,input().split())
l = list(map(int,input().split()))
min1 = float("inf")
for i in range(K):
r = N%l[i]
min1 = min(min1,r)
if min1 == r:
index = i+1
print(index,N//l[index-1]) |
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is ... | 3 | L = [int(input()) for i in range(5)]
l = []
for i in L:
if i%10==0:
l.append(0)
else:
l.append(10-i%10)
print(sum(L)+sum(l)-max(l)) |
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()
b=len(a)
c=[]
d=[]
count=0
for i in range(0,b):
if a[i]=='1' or a[i]=='2' or a[i]=='3':
c.append(a[i])
c.sort()
for i in c:
if i==len(c):
d.append(i)
else:
d.append(i)
count=count+1
if count==len(c):
break
d.append('+')
print(''.join(d)) |
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems.
Polycarp has a list of n contests, th... | 3 | from sys import stdin,stdout
from collections import Counter
def ai(): return list(map(int, stdin.readline().split()))
def ei(): return map(int, stdin.readline().split())
def ip(): return int(stdin.readline().strip())
def op(ans): return stdout.write(str(ans) + '\n')
n = ip()
li = ai()
li.sort()
days = 0
k = 1
for i ... |
Princess'Marriage
Marriage of a princess
English text is not available in this practice contest.
A brave princess in a poor country, knowing that gambling payouts are determined by the parimutuel method, felt more familiar with gambling and was convinced of her victory in gambling. As a result, he spent more money t... | 3 | while True:
n, m = map(int, input().split())
dpList = []
if (n,m) == (0,0):
break
for i in range(n):
row = list(map(int,input().split()))
dpList.append(row)
dpList = sorted(dpList, key = lambda x:x[1], reverse = True)
num = 0
for i in range(n):
if m >= dpList[... |
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th... | 1 | import re
class Form(object):
def parse(self, s=None):
if isinstance(s, basestring):
self.s = s
self._parse()
def _parse(self):
raise NotImplementedError("Please Implement this method")
def build(self):
if self.r is None or self.c is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.