problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer.
Input
A single line with a positive integer k (1 β€ k β€ 10 000).
Output
A single number, denoting the k-th smallest perfect integer.... | 3 | # Python3 program to find n-th
# number with sum of digits as 10.
def findNth(n):
count = 0;
curr = 19;
while (True):
# Find sum of digits in
# current no.
sum = 0;
x = curr;
while (x > 0):
sum = sum + x % 10;
x = int(x / 10);
# If sum is 10, we increment
# count
if (sum == 10):
... |
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r... | 3 | mod = 1000000007
n,m = map(int, input().split())
def fib(n):
a,b = 1,1
for i in range(n):
a,b = b,(a+b)%mod
return a
res = (2*(fib(n) + fib(m) - 1)) % mod
print(res)
|
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | 1 | '''
Created on Jan 1, 2013
@author: Evan
'''
string = raw_input()
best = ""
skipped = False
for c in string:
if c != "0" or skipped == True:
best += c
else:
skipped = True
if best==string:
print best[1:]
else:
print best |
Snuke has N hats. The i-th hat has an integer a_i written on it.
There are N camels standing in a circle. Snuke will put one of his hats on each of these camels.
If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No... | 3 | n = int(input())
a = list(map(int,input().split()))
s = 0
for i in range(n):
s ^= a[i]
if s == 0:
ans = 'Yes'
else:
ans = 'No'
print(ans)
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | n=int(input())
okk=False
for m in range(1,n+1):
ok=True
j=m
while m:
s=int(m%10)
m=int(m/10)
if s!=4 and s!=7:
ok=False
break
if ok and n%j==0:
okk=True
break
if okk:print("YES")
else :print("NO")
|
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | 3 | t = int(input())
c = []
for i in range(t):
n = int(input())
a = input().split(" ")
for i in range(n):
a[i] = int(a[i])
k = []
for i in range(max(a)+1):
k.append(0)
for i in range(n):
k[a[i]] +=1
d = 0
for i in range(max(a)+1):
if k[i] != 0:
d+=... |
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 | import sys
# try:
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
# except:
# pass
input = sys.stdin.readline
for tt in range(int(input())):
# n = int(input())
# a,b = map(int,input().split())
# l = list(map(int,input().split()))
l = []
for i in range(9):
temp = [int(i) for i in ... |
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 | x= input("")
x_list=[]
for i in range(0,len(x)):
x_list=x.split("+")
x_list.sort()
print("+".join(x_list)) |
Takahashi has N blue cards and M red cards. A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.
Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will ea... | 3 | N = int(input())
s = [input() for _ in range(N)]
M = int(input())
t = [input() for _ in range(M)]
print(max(max([s.count(e)-t.count(e) for e in s+t]),0))
|
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 β€ k β€ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | for _ in range(int(input())):
x, y, n = map(int, input().split())
d = n - n % x + y
if d <= n:
print(d)
else:
print(d - x)
|
In this problem, you are given a string of N characters(1-indexed), and an integer D. You perform multiple operations on this string. In the first operation you select the first D characters of the string, ie. the substring S[1...D] and reverse it. The other characters remain unchanged. Thus, after the first operation ... | 1 | t = input()
for z in range(t):
s = raw_input().strip()
d = input()
temp = s[:d-1]
if (len(s)+d)%2==0:
temp = temp[::-1]
print s[d-1:]+temp |
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 β
n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | 3 | import math
for q in range(int(input())):
n=int(input())
ans = 1/(2*math.sin(math.radians(180/(4*n))))
print(ans) |
Jzzhu has invented a kind of sequences, they meet the following property:
<image>
You are given x and y, please calculate fn modulo 1000000007 (109 + 7).
Input
The first line contains two integers x and y (|x|, |y| β€ 109). The second line contains a single integer n (1 β€ n β€ 2Β·109).
Output
Output a single integer... | 3 | x, y = map(int, input().rstrip().split())
n = int(input())
li = [x, y, y - x, -x, -y, x - y]
i = n % 6
print(li[i - 1] % 1000000007) |
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address (vasya@gmail.com).
It is known that a proper email address contains only such symbols a... | 3 | s = input()
c1 = s[0]
c2 = s[-1]
s = s[1:-1]
s = s.replace("dot", ".")
s = s.replace("at", "@", 1)
print(c1 + s + c2)
# Your last C/C++ code is saved below:
# #include <iostream>
# using namespace std;
# #define ll long long
# #define fi first
# #define se second
# typedef vector <>
# typedef vector <ii> vii
... |
You are given an array of n elements, you must make it a co-prime array in as few moves as possible.
In each move you can insert any positive integral number you want not greater than 109 in any place in the array.
An array is co-prime if any two adjacent numbers of it are co-prime.
In the number theory, two integer... | 3 | N = int(input())
a = list(map(int, input().split()))
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
ans = []
for i in range(N):
ans.append(a[i])
if i < N - 1 and gcd(a[i], a[i + 1]) != 1:
ans.append(1)
print(len(ans) - N)
print(*ans)
|
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(i, x): add x to ai.
* getSum(s, t): print the sum of as, as+1,...,at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 β€ n β€ 100000
* 1 β€ q β€ 100000
* If comi is 0, then 1 β€ xi... | 3 | line = input()
n, q = list(map(int, line.split()))
N = 1
while N < n + 1:
N *= 2
a = [0 for _ in range(0, 2 * N - 1)]
def update(k, v):
k += N - 1
a[k] += v
while k > 0:
k = (k - 1) // 2
a[k] = a[k * 2 + 1] + a[k * 2 + 2]
def query(x, y, k, l, r):
if r <= x or y <= l:
retur... |
You are given an array of integers a_1,a_2,β¦,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1β€ tβ€ 2 β
10^4) β the number of test cases. The description of the test cases ... | 3 | import sys
from functools import reduce
from operator import mul
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
t = int(input())
for i in range(t):
n = int(input())
A = list(map(int, input().strip().split(' ')))
A.sort()
print(
max(
reduce(mul, A[:5], 1),
reduce(mul, A[:4] + ... |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n=int(input())
k=9
counter=1
sum=0
def count(n,m):
global k
global counter
global sum
if n==k:
sum+=counter
k=m
for i in range(n):
p=input()
n=p[0]
m=p[1]
count(n,m)
sum+=counter
print(sum) |
Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.
Constraints
* S and T are strings consisting of lowercase English letters.
* The lengths of S and T are between 1 and 100 (inclusive).
Input
Input is gi... | 3 | print("".join(reversed(input().split()))) |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | def main():
w = int(input())
if w % 2 == 0 and w != 2:
print("YES")
else:
print("NO")
if __name__ == '__main__':
main() |
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.
Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all... | 3 | n = int(input())
h = [int(s) for s in input().split()]
# list of maxima: element i is max(h[i:])
m = [0] * n
m[n-1] = h[n-1]
for i in reversed(range(n-1)):
m[i] = max(h[i], m[i+1])
a = [max(0, m[i+1]+1 - h) for i, h in enumerate(h[:-1])] + [0]
print(" ".join(str(x) for x in a))
|
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents t... | 1 |
def gcd(a, b):
if a < b:
return gcd(b, a)
if b == 0:
return a
return gcd(b, a % b)
def solve(c):
n = len(c)
sum = c[0] * n
for i in xrange(1, n):
sum += abs(c[i] - c[i-1]) * ((i + 1) * (n - i) + (n - i) * i);
g = gcd(sum, n)
print sum / g, n / g
if __name__ ... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | l=list(map(str,input()))
m=[]
k=len(l)
for i in range(k):
if l[i] not in m:
m.append(l[i])
n=len(m)
if(n%2==1):
print("IGNORE HIM!")
else:
print("CHAT WITH HER!") |
The educational program (AHK Education) of the Aiz Broadcasting Association broadcasts a handicraft program for children, "Play with Tsukuro". Today is the time to make a rectangle with sticks, but I would like to see if I can make a rectangle using the four sticks I prepared. However, the stick must not be cut or brok... | 3 | a = [int(i) for i in input().split()]
a.sort()
if a[0] == a[1] and a[2] == a[3]:
print("yes")
else:
print("no")
|
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 | n = int(input())
value = 0
ans = 0
if n == 1:
print("1")
else:
for i in range(1,n+1,1):
for j in range(1,i+1,1):
value = value + j
if value > n:
ans = i-1
break
print(ans) |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | def alpha ():
inp= input()
pointer=0
counter =0
i=0
for i in range(len(inp)) :
if abs( pointer - (ord(inp[i])-97)) < abs( 26 - abs( pointer - (ord(inp[i])-97))) :
counter+=abs( pointer - (ord(inp[i])-97))
else :
counter+= abs( 26 - abs( pointer - ... |
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of... | 3 | from collections import defaultdict
t = int(input())
for _ in range(t):
n = int(input())
b = list(map(int, input().split()))
b = list(map(lambda x: x-1, b))
flag = [False]*(2*n)
for bi in b:
flag[bi] = True
pair = defaultdict(int)
f = True
for bi in b:
... |
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | 3 | s = input()
cnt = sum(s.count(i) % 2 for i in s)
if cnt%2==1 or cnt ==0:
print("First")
else:
print("Second")
|
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 β₯ w_2. In this game, exactly one ship is used... | 3 | mass = list(map(int, input().split(" ")))
dlina_1 = mass[0]
visot_1 = mass[1]
dlina_2 = mass[2]
visot_2 = mass[3]
temp = max(dlina_1, dlina_2)
temp_1 = visot_1 + visot_2
square = (temp + 2) * (temp_1 + 2)
square_min = temp * temp_1
print(square - square_min)
|
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.
There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from c... | 3 | from __future__ import division, print_function
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import BytesIO, IOBase
# FastIO for PyPy2 and PyPy3 by Pajenegod,
class FastI(object):
def __init__(self, fd=0, buffersize=2**14):
... |
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and... | 3 | n = int(input())
temparr = input()
temparr = temparr.split()
arr = []
for i in temparr:
arr.append(int(i))
arr = sorted(arr)
maxelem = arr[-1]
dp = [0] * (maxelem + 1)
curelem = 0
total = 0
for i in arr:
if i != curelem:
dp[curelem] = total
total = i
curelem = i
else:
t... |
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can ... | 1 | ret = [int(i) for i in raw_input().split()]
n = ret[0]
x = ret[1]
y = ret[2]
a = []
c = []
d = []
#e = []
mydict = {}
mydict2 = {}
mysum = 0
for i in range(ret[0]):
pos = [int(j) for j in raw_input().split()]
a.append(pos)
#print a
for i in range(ret[0]):
if (a[i][0]-x) != 0:
k = float(a[i][1]-y)/fl... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
raw =[int(x) for x in input().split(' ')]
res = [x%2 for x in raw]
if res.count(0)==1:
for i in range(n):
if res[i]==0:
prt = i+1
break
else:
for i in range(n):
if res[i]==1:
prt = i+1
break
print(prt) |
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and... | 1 | """
Satwik_Tiwari ;) .
28 june , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOB... |
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n β
n!.
Let 1 β€ i β€ j β€ n β
n! be a pair of indices. We call the... | 3 | import math
def factorial(n):
for i in range(1,n + 1):
factorial = factorial*i
return factorial
def f(n):
l = factorial(n)*n
ans = l * (l-n+2) // 2
for i in range(1,n):
ans -= factorial(n)//factorial(i+1)*n*(i*(n-i)-1)
return ans
def solve(n):
M = 998244353
p = n
a... |
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."
The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could h... | 1 | values = raw_input().split()
n = int(values[0])
m = int(values[1])
if (n == 0) and (m > 0):
print("Impossible")
else:
print("{0} {1}".format(max(n, m), n + max(0, m - 1))) |
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of a... | 3 | n = input()
s = [[], [], [0]]
s_1 = 0
for el in map(int, input().split()):
if el < 0:
s[0].append(el)
elif el > 0:
s[1].append(el)
if len(s[1]) == 0:
s[1] = s[0][:2]
s[0] = s[0][2:]
if len(s[0]) % 2 == 0:
s[2].append(s[0][0])
s[0] = s[0][1:]
for el in s:
print(len(el), " ".j... |
Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes.
At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| β the absolute d... | 3 | import sys, collections
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
A = list(map(int, input().split()))
A.sort()
dp = [[float('inf')] * (2 * n + 1) for _ in range(n + 1)]
for i in range(2 * n + 1):
dp[0][i] = 0
for i in range(n):
for j in ran... |
We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.
Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they w... | 3 | N, Z, W = map(int, input().split())
A = [W]+list(map(int, input().split()))
X = [0]*N
Y = [1<<30]*N
X[0] = Y[0] = abs(A[-2]-A[-1])
for i in range(1,N):
X[i] = max(abs(A[-2-i]-A[-1]), max(Y[j] for j in range(i)))
Y[i] = min(abs(A[-2-i]-A[-1]), min(X[j] for j in range(i)))
print(X[-1]) |
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 = map(int, input().split())
year = 0
while limak <= bob:
year += 1
limak *= 3
bob *= 2
print(year) |
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list.
For ex... | 3 | n = int(input())
d = list(map(int, input().split()))
d = sorted(d, reverse=True)
for i in range(n):
if d[0] % d[i] != 0:
print(d[0], d[i])
break
elif d[i] == d[i+1]:
print(d[0], d[i])
break
|
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] m... | 3 | import sys
# import math
input = sys.stdin.readline
def int_array():
return list(map(int, input().strip().split()))
def str_array():
return input().strip().split()
def lower_letters():
lowercase = [chr(i) for i in range(97, 97+26)]
return lowercase
def upper_letters():
uppercase = [chr(i) fo... |
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.
As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.
It's guaranteed that the solution always exists. If ther... | 1 | t = int(raw_input())
for _ in xrange(t):
x = int(raw_input())
if x % 2 == 0:
print "{0} {0}".format(x/2)
else:
print "{} 1".format(x - 1)
|
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r... | 3 | n,m =input().split()
n=int(n)
m=int(m)
s=list(input())
q=[]
dic={'(':1,')':-1}
for i in range(len(s)):
if len(q)==0:
q.append([i,dic[s[i]]])
elif q[-1][1]==1 and dic[s[i]]==-1:
q.pop(-1)
else:
q.append([i,dic[s[i]]])
t=n-m-len(q)
if len(q)!=0:
q.sort(reverse=True)
for... |
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());
sum = a + (a-1) // (b-1)
print(sum) |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | try:
while True:
n,m,a =map(int,input().split())
ans1=int(n/a)
if n%a!=0:
ans1+=1
ans2=int(m/a)
if m%a!=0:
ans2+=1
ans=ans1*ans2
print(ans)
except EOFError:
pass
|
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr... | 1 | import sys
n=input()
flag=0
c=''
if n%2==0:
for i in range(0,n,2):
# print i
if flag==0:
c+="aa"
flag=1
else:
c+="bb"
flag=0
print c
else:
for i in range(0,n-1,2):
# print i
if flag==0:
c+="aa"
fl... |
The Little Elephant loves chess very much.
One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8 Γ 8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doe... | 1 | flag = True
for i in range(8):
a = raw_input()
if a != 'WBWBWBWB' and a != 'BWBWBWBW':
flag = False
print 'YES' if flag else 'NO' |
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want... | 3 | n=int(input())
ml=10e9
mr=0
L=[]
for i in range(n):
t=[]
l,r=map(int,input().split())
if(l<=ml):
ml=l;
if(r>=mr):
mr=r;
t.append(l);
t.append(r);
L.append(t);
c=0
for i in range(len(L)):
if(L[i][0]==ml and L[i][1]==mr):
c=1
p=i+1
break
if(c==1):
... |
You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 β€ l β€ r β€ n) such, that among numbers al, al + 1, ..., ar there are exactly k distinct numbers.
Segment [l, r] (1 β€ l β€ r β€ n; l, r are integers) of length m = r - l + 1, satisfying the given... | 3 | n, k = map(int, input().split())
a = list(map(int, input().split()))
cnt = [0] * 1000000
diff = 0
l = 0
for r in range(n):
cnt[a[r]] += 1
if cnt[a[r]] == 1:
diff += 1
if diff == k:
while diff == k:
cnt[a[l]] -= 1
if cnt[a[l]] == 0:
print(str(l+1) + ' ... |
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter... | 1 | a, b = map(int, raw_input().split())
b %= int(a*(a+1)/2)
t = int(((1+8*b)**0.5-1)/2)
print int(b-t*(t+1)/2) |
For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) β₯ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 β₯ 5.
... | 3 | t = int(input())
for _ in range(t):
_ = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
for i in range(len(a) - 1):
if abs(a[i] - a[i + 1]) > 1:
print('Yes')
print(i + 1, ' ', i + 2)
break
if i == len(a) - 2:
print(... |
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | 1 | tam_alphabet = 26
count = 0
map_letter_quantity = [0]*tam_alphabet
word = raw_input()
for i in word:
i_ord = ord(i.lower())
map_letter_quantity[i_ord - ord('a')] += 1
for i in map_letter_quantity:
if i % 2 == 1:
count += i
if count % 2 == 1 or count == 0:
print 'First'
else:
print 'Seco... |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | n=input()
n=n.replace(", ","")
n=list(n[1:-1])
print(len(set(n))) |
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 | def ajuda(ar, el):
ar = ar + []
ar.sort()
c = sum(ar)
jog = 0
while el + sum(ar) > t:
jog += 1
ar.pop()
return jog
n, t = map(int, raw_input().split())
ps = map(int, raw_input().split())
l = []
for k in xrange(n):
print ajuda(l, ps[k]),
l.append(ps[k])
|
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | import sys
import math
from collections import defaultdict,Counter
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdout=open("CP1/output.txt",'w')
# sys.stdin=open("CP1/input.txt",'r')
# m=pow(10,9)+7
t=int(input())
for i in range(t):
a,b,c,n=map(int,input().split())
m=... |
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An ex... | 3 | from sys import stdin,stdout
from collections import deque
nmbr = lambda: int(input())
lst = lambda: list(map(int, input().split()))
PI=float('inf')
M=10**9+7
for _ in range(1):#nmbr()):
n=nmbr()
s=[input() for _ in range(n)]
dp=[[0 for _ in range(n+1)] for _ in range(n+1)]
dp[0][0]=1
for i in range... |
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the ... | 3 | #input
s=str(input())
#variables
x=b=0
r=[]
#main
for i in range(len(s)):
if s[i]=='(':
b+=1
elif s[i]==')':
b-=1
else:
b-=1
x=b
r.append(1)
if b<0:
print(-1)
quit()
if b<=x:
r[-1]+=b
x=b=0
for i in range(len(s)):
if s[i]=='(':
b+=1
elif s[i]==')':
b-=1
els... |
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can... | 3 | n,m=map(int,input().strip().split(' '))
arr=list(map(int,input().strip().split(' ')))
arr.sort()
tota=0
for i in arr:
if m!=1:
tota+=i*m
m-=1
else:
tota+=i
print(tota) |
You are given an integer n and an integer k.
In one step you can do one of the following moves:
* decrease n by 1;
* divide n by k if n is divisible by k.
For example, if n = 27 and k = 3 you can do the following steps: 27 β 26 β 25 β 24 β 8 β 7 β 6 β 2 β 1 β 0.
You are asked to calculate the minimum numbe... | 3 | from decimal import Decimal
t=int(input(''))
#t=1
a=[]
for i in range(t):
n,k=input('').split()
#n,k='999999999999999999 1'.split()
n=Decimal(n)
k=Decimal(k)
count=0
while n!=0:
if n%k==0:
n/=k
count+=1
else:
j=int(n/k)
count+=(n-j*... |
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 | def calc_min_power(a):
_min = float('inf')
_sum = 0
for v in a:
_min = min(_min, v)
_sum += v
min_power = _sum
for v in a:
for d in get_divisors(v):
min_power = min(min_power, _sum - v + v // d - _min + _min * d)
return min_power
def get_divisors(v):
divisors = set()
i = 2
while i ** 2 <= v:
if v ... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n=int(input())
x=0
for i in range(n):
pi, qi = list(map(int,input().split()))
if qi-pi >= 2:
x=x+1
print(x)
|
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into wΓ h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one β 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ... | 1 | [w, h, k] = [int(i) for i in raw_input().split()]
s = 2*w + 2*h - 4
r = s
while k>1:
s -= 16
r += s
k -= 1
print r |
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 β€ li < ri β€ n)... | 1 | s=raw_input().strip()
arr=[]
arr.append(0)
k=1
for i in range(len(s)-1):
if(s[i]==s[i+1]):
arr.append(arr[k-1]+1)
k+=1
else:
arr.append(arr[k-1])
k+=1
q=input()
for z in range(q):
l,r=map(int,raw_input().strip().split(" "))
print arr[r-1]-arr[l-1]
|
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 | k = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(k):
b[i] = a[i] - b[i]
b.sort()
s = 0
x, y = 0, len(b) - 1
while (x < y):
if (b[y] + b[x] > 0):
s += y - x
y -= 1
else:
x += 1;
print(s)
|
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 3 |
s=int(input())
n=input()
c=1
l1=[]
temp=True
for i in range(s-1):
if n[i]==n[i+1]:
c+=1
else:
if temp:
l1.append(c)
temp=False
else:
l1.append(-c)
temp=True
c=1
if temp:
l1.append(c)
else:
l1.append(-c)
print(abs(sum(l1)))
... |
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y ... | 3 | n=int(input())
a=list(input().split())
dic=[]
count=0
for val in a:
s=list(set(sorted(val)))
if s not in dic:
dic.append(s)
count+=1
print(count) |
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;
2. Delete the first number of the current s... | 1 | n,k=map(int,raw_input().split())
a,b=map(int,raw_input().split()),n
while b>1 and a[b-1]==a[b-2]:b-=1
print b-1 if b<=k else -1
|
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of... | 3 | if __name__ == '__main__':
for _ in range (int(input())):
n = int(input())
l = list(map(int, input().split()))
a = min(l)
b = max(l)
if a != 1 or b == 2*n:
print(-1)
else:
B = []
d = dict()
for i in range (n):
d.setdefault(l[i],1)
for i in range (1,(2*n)+1):
d.setdefault(i,0)
if ... |
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 | one = input().lower()
two = input().lower()
comp = [one, two]
sorted_words = sorted(comp)
if(sorted_words[0] == one):
if one == two:
print(0)
else:
print(-1)
else:
print(1) |
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll... | 3 | Result = ""
for i in range(3):
Result += str(len("".join(filter(lambda x: True if x in "aioue" else False, input()))))
print("YES" if Result == "575" else "NO")
# UB_CodeForces
# Advice: Every person have some powers that he might not know yet,
# try to find your powers
# Location: Next to my honors
# Capt... |
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
... | 1 | from collections import defaultdict
n, m = map(int, raw_input().split())
a = [raw_input().strip() for i in xrange(m)]
d = defaultdict(int)
for c in zip(*a):
d[c] += 1
mod = 1000000007
b = [1, 1]
p = [1]
for i in xrange(n):
np = [p[-1]]
for j in xrange(i + 1):
x = p[j] + np[-1]
if x >= mod:
... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a=int(input())
if a%2==0:
if a==2:
print("NO")
else:
print("YES")
else:
print("NO") |
As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest a... | 3 | # http://codeforces.com/problemset/problem/479/B
def main():
n, k = map(int, input().split())
towers = list(map(int, input().split()))
min_index = towers.index(min(towers))
max_index = towers.index(max(towers))
dif = towers[max_index] - towers[min_index]
cant = 0
operations = []
while k ... |
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.
Both the given array and required subset may contain equal values.
Input
The first line contains a single integer t (1 β€ t β€... | 3 | N=int(input())
ans=[]
for i in range(0,N):
n=int(input())
A=list(map(int,input().split()))
if n==1:
if A[0]%2==0:
ans.append([1])
ans.append([1])
else:
ans.append([-1])
else:
if A[0]%2==0:
ans.append([1])
ans.append([1])... |
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:
* The array consists of n distinct positive (greater than 0) integers.
* The array contains two elements x and y (these elements are known for you) such that x < y.
* If you sort the arr... | 3 | # cook your dish here
for t in range(int(input())):
n, x, y = map(int, input().split())
if n==2:
print(x, y)
else:
toadd=n-1
min=100000000000
d=y-x
c=(y//d)+1
min=y+(n-c)*d
k=d
for i in range(2,n):
if (y-x)%i==0:
d=(... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a = int(input())
if a/2 == a//2 and not(a == 2):
print('Yes')
else:
print('No')
|
You are given a rectangular grid with n rows and m columns. The rows are numbered 1 to n, from bottom to top, and the columns are numbered 1 to m, from left to right.
You are also given k special fields in the form (row, column). For each i, where 0 β€ i β€ k, count the number of different paths from (1, 1) to (n, m)... | 1 | N, M, K = map(int, raw_input().strip().split())
special = [[False for j in xrange(M)] for i in xrange(N)]
for k in xrange(K) :
a, b = map(int, raw_input().strip().split())
special[a - 1][b - 1] = True
dp = [[[0 for k in xrange(K + 1)] for j in xrange(M)] for i in xrange(N)]
for k in xrange(K + 1):
spe... |
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from t... | 1 | def solve(n):
if n == 1:
return [1]
if n == 2:
return [1, 2]
if n == 3:
return [1, 1, 3]
res = (n/2 + n%2) * [1]
return res + [2 * v for v in solve(n/2)]
n = int(raw_input())
print ' '.join(map(str, solve(n)))
|
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it eit... | 3 | t = int(input())
for ingles in range(t):
X = input()
X1 = X.split()
n = int(X1[0])
m = int(X1[1])
A = []
for i in range(n):
l = input()
A.append(l.split())
L1=[0]*(m+n-1)
L0=[0]*(m+n-1)
for i in range(n):
for j in range(m):
if A[i][j]=="1":
... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | str1 = str(input())
if 'H' in str1 or 'Q' in str1 or '9' in str1:
print('YES')
else:
print('NO')
|
"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 | x , n = map(int,input().split())
r = list(map(int,input().split()))
c=0
for i in r:
if i != 0 and i>= r[n-1]:
c += 1
print(c)
|
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | 3 | t = int(input())
for i in range(t):
n = int(input())
l = list(map(int,input().split()))
print(*dict.fromkeys(l)) |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | a = input()
b = input()
for i in range(len(a)):
if a[i] == b[i]:
print('0',end='')
else:
print(1,end = '') |
A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.
Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordina... | 1 | n = int(raw_input())
s = []
for i in range(0,n):
x,y = raw_input().split()
s.append((x,y))
a = map(int,raw_input().split())
y = ""
flag = 0
x = min(s[a[0]-1])
for i in range(1,n):
l = a[i]-1
if s[l][0]>x and s[l][1]>x:
y = min(s[l])
x = y
elif s[l][0]>x or s[l][1]>x:
y = max(s[l... |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 β€ r ... | 3 | k,r=map(int,input().split())
t=0
i=0
while True:
t+=k
i+=1
if t%10==0 or int(str(t)[-1])==r:
print(i)
break
|
There are N islands lining up from west to east, connected by N-1 bridges.
The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.
One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:
Request i: A dispute took place be... | 3 | n,m=map(int,input().split())
l=[list(map(int,input().split())) for _ in range(m)]
l.sort(key=lambda x : x[1])
a=0
b=0
for x in l:
if x[0]>=b:
b=x[1]
a+=1
print(a)
|
There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding dire... | 3 | # from __future__ import print_function,division
# range = xrange
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10**9)
from sys import stdin, stdout
from collections import defaultdict, Counter
M = 10**9+7
def main():
for _ in range(int(input())):
s = input().strip()
n = len(s)
... |
Tomya is a girl. She loves Chef Ciel very much.
Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p.
The current menus of Ciel's restaurant are shown the following table.
Name of Menuprice
eel flavored water1
deep-fried eel bones2
clear soup made w... | 1 | t = input()
if((1<=t)and(t<=5)):
for i in range(t):
p = input()
if((1<=p)and(p<=100000)):
count = 0
quotient = p/2048
count = count+quotient
remainder = p%2048
if(remainder>0 or quotient>0):
r_value = "{0:b}".format(remainde... |
Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.
More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by pay... | 1 | from sys import stdin, stdout
def main():
n = int(stdin.readline())
a = [0] + map(int, stdin.readline().split())
b = [0] + map(int, stdin.readline().split())
c = [0] * 2010
for i, x in enumerate(b):
c[x] = i
m = sum(map(abs, [c[x] - i for i, x in enumerate(a)])) / 2
ans = []
whil... |
"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the curr... | 3 | a,b,c,x,y = map(int,input().split())
res = min(a+b,2*c)*min(x,y)
if x > y:
res += min(a,2*c)*(x-y)
else:
res += min(b,2*c)*(y-x)
print(res) |
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation:
Choose one of these numbers and add or subtract 1 from it.
In particular, we can apply this operation to the same number several times.
We want to make the product of all these numbers equal to 1, in other wo... | 3 | n = int(input())
u = list(map(int, input().split()))
s=0
y=0
zer=0
for i in u:
if i<=-1:
y+=1
s+=abs(i+1)
elif i>=1:
s+=abs(i-1)
else:
zer+=1
s+=1
if y%2!=0:
s+=2
if zer!=0:
s-=2
print(s)
|
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | 3 | from collections import deque
n, k = map(int, input().split())
A = list(map(int, input().split()))
B = deque()
B.append(A[0])
nc = {}
for i in set(A):
nc[i] = 0
nc[A[0]] = 1
for i in range(1, n):
if nc[A[i]] == 0:
if len(B) == k:
nc[B[0]] -= 1
B.popleft()
B.append(A[i])
... |
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:... | 1 | n = int(raw_input())
def value_of(v):
v = v[::-1]
res = 0
for x in v:
res *= 10
res += x
return res
v = [0]*9
v[0] = 4
res = 1
while value_of(v) != n:
if v[0] == 4:
v[0] = 7
else:
i = 0
while v[i] == 7:
v[i] = 4
i += 1
... |
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | 3 | a,b,c=map(int,input().split())
if(b>=a+1):
b=a+1
else:
a=b-1
if(c>=b+1):
c=b+1
else:
b=c-1
if(b>=a+1):
b=a+1
else:
a=b-1
if(c>=b+1):
c=b+1
else:
b=c-1
print(a+b+c) |
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays... | 1 | f = lambda: map(int, raw_input().split())
import operator
def get(num, x, n):
l = 0; r = n-1
while l <= r:
mid = (l+r)>>1
if num[mid] >= x:
r = mid-1
else : l = mid+1
return l+1
if __name__ == '__main__':
n, m = f()
num = []
for i in xrange(n):
a, b = ... |
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 | k=int(input())
s=0
for i in range(k):
l=input()
if l=="++X" or l=="X++":
s=s+1
elif l=="--X" or l=="X--":
s=s-1
print(s)
|
A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.
You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasin... | 3 | n, d = map(int, input().split())
sequence = list(map(int, input().split()))
m = 0
for i in range(1, n):
if sequence[i] <= sequence[i-1]:
x = (sequence[i-1] - sequence[i]) // d + 1
sequence[i] += x * d
m += x
print(m) |
Problem Statement
Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and always tries to save as much paper as possible. She decided to play a ghost leg with other participants to decide the team for the Aizu training camp.
How to make Amidakuji for this training camp is as foll... | 3 | from itertools import permutations
N,M=map(int,input().split())
k=[int(input())-1 for i in range(M)]
g=[i for i in range(N)]
for i in range(N):
for j in k:
if g[i]==j:
g[i]=j+1
elif g[i]==j+1:
g[i]=j
s=10
for K in permutations(k):
G=[i for i in range(N)]
for i in rang... |
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 β€ l β€ r β€ n) with maximum arithmetic mean (1)/(r - l + 1)β_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer... | 3 | n = int(input())
a = list(map(int, input().split()))
t = max(a)
ans = 1
for i in range(n):
if a[i] != t or (i < n - 1 and a[i + 1] == a[i]): continue
for j in range(n):
if i - j < 0 or a[i - j] != t: break
ans = max(ans, j + 1)
print(ans)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.