problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | n,m=map(int,input().split())
l1=list(map(int,input().split()))
l1.sort()
l2=[]
for i in range(m-n+1):
l2.append(l1[i+n-1]-l1[i])
print(min(l2)) |
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing n... | 3 | n = int(input())
A = list(map(int,input().split()))
A.sort()
i = n-1
ans = []
while(i>=0):
if(i%2==0):
ans.append(A[i])
i-=1
i = 1
while(i<n):
if(i%2):
ans.append(A[i])
i+=1
print(*ans) |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | from sys import stdin,stdout
def fn(n,k):
if k==0:return n
if n%10!=0:return fn(n-1,k-1)
return fn(n//10,k-1)
for _ in range(1):#int(stdin.readline())):
# n=int(stdin.readline())
n,k=list(map(int,stdin.readline().split()))
print(fn(n,k)) |
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 | a1=input().split()
a2=input().split()
a3=input().split()
a4=input().split()
a5=input().split()
if '1' in a1:
print(2+abs(a1.index('1')-2))
if '1' in a2:
print(1+abs(a2.index('1')-2))
if '1' in a3:
print(abs(a3.index('1')-2))
if '1' in a4:
print(1+abs(a4.index('1')-2))
if '1' in a5:
print(2+abs(a5.in... |
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | 3 | a = input()
for x in range(int(a)):
b = input()
c = input().split(" ")
list1 = [int(i) for i in c]
if(len(set(list1))==1):
print(len(list1))
else:
print(1)
|
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | 1 | n, k = map(int, raw_input().split())
s = raw_input()
if k == 0:
print(s)
elif n == 1:
print(0)
else:
s = list(s)
if s[0] != '1':
s[0] = '1'
k -= 1
i = 1
while k and i < n:
if s[i] != '0':
k -= 1
s[i] = '0'
i += 1
print(''.join(s))
|
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a ... | 1 | from collections import defaultdict
def hist():
return [0]*26
alpha = "abcdefghijklmnopqrstuvwxyz"
atoi = {alpha[i]:i for i in xrange(26)}
pos = [[] for i in xrange(26)]
x = map(int,raw_input().split())
s = [atoi[si] for si in raw_input()]
n = len(s)
sums = defaultdict(hist)
sum = 0
ans = 0
for i in xrange(... |
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this... | 3 | from math import ceil
from statistics import median
def f(l,b):
ans=-float("inf")
for i in range(len(l)):
cnt=0
for j in range(i,len(l),b):
cnt+=l[j]
if i-1>=0:
for j in range(i,-1,-b):
# print("hjkh ",i)
if j==i:
... |
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | 3 | # this is from codeforces problem
import re
print(len(re.findall(string=input().strip(), pattern=r'%s'%input().strip())))
|
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 | from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import combinations
import functools
import sys
import math
MAX = sys.maxsize
MAXN = 10**6+10
MOD = 10**9+7
def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2: ... |
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.
There is a set S containing very important number... | 3 | t = int(input())
for q in range(t):
n = int(input())
s = set(map(int, input().split()))
f = True
for i in range(1, 1024):
s2 = set()
for j in s:
s2.add(j ^ i)
if s == s2:
print(i)
f = False
break
if f:
print(-1) |
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.
In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ... | 3 | s = list(input())
if s.count("a") == len(s):
s = "a" * 2
else:
for i in range(len(s)):
if len(s) < i + 3:
break
if s[i] == s[i + 1] and s[i + 2] == s[i + 1]:
del (s[i])
ans = ""
for ch in range(len(s)):
if len(ans) >= 2:
if s[ch] == ans[-1] and ans[-2] =... |
There are n pillars aligned in a row and numbered from 1 to n.
Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.
You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met:
... | 3 | n = int(input());
a = list(map(int, input().split()));
M = max(a);
i = a.index(M);
c = 0;
test1 = all(x<y for x, y in zip(a[0:i], a[1:]));
test2 = all(x>y for x, y in zip(a[i:], a[i+1:]));
if test1 == True and test2 == True:
print("YES");
else:
print("NO")
|
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ... | 3 | n,t = map(int,input().split())
arr = list(map(int,input().split()))
i = j = 0
sm = 0
mx = 0
while j < n:
sm += arr[j]
while sm > t:
sm -= arr[i]
i += 1
mx = max(mx,j - i + 1)
j += 1
print(mx) |
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t... | 1 | def fun(pat, M, lps):
tmp = 0
lps[0] = 0
i = 1;
while (i < M):
if (pat[i] == pat[tmp]):
tmp += 1
lps[i] = tmp
i += 1
else:
if (tmp != 0):
tmp = lps[tmp-1];
else:
lps[i] = 0
i += ... |
Given an integer x, find 2 integers a and b such that:
* 1 β€ a,b β€ x
* b divides a (a is divisible by b).
* a β
b>x.
* a/b<x.
Input
The only line contains the integer x (1 β€ x β€ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | flag=False
x=int(input())
for a in range(1, x+1):
if flag:
break
for b in range(1, x+1):
if a*b > x and a/b<x and a%b==0:
print(a,b)
flag=True
break
if flag==False:
print(-1) |
Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.
You can use the following theorem:
Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths... | 3 | input()
L=list(map(int,input().split()))
print('Yes'if 2*max(L)<sum(L) else'No') |
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... | 1 | n = input()
result = 2 ** (n + 1) - 2
print result
|
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | #617A.Elephant
distance=int(input())
import math
step=math.ceil(distance/5)
print(str(step))
|
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = xΒ·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu... | 3 | from sys import stdin
n, k = map(int, stdin.readline().split())
nums = list(map(int, stdin.readline().split()))
nums.sort()
count = 0
new = set()
for i in nums:
if i%k:
new.add(i)
else:
if i//k in new:
pass
else:
new.add(i)
print(len(new)) |
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh... | 3 | n = int(input())
a = list(map(int,input().split()))
a.sort()
dup_list = list(a)
count = 1
temp_minus = 0
for i in range(1,len(a)):
dup_list[i] = dup_list[i-1]+dup_list[i]
for i in range(1,len(dup_list)):
if (a[i]>=dup_list[i-1]-temp_minus):
count+=1
else:
temp_minus+=a[i]
print(count)
|
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a, b = map(int, input().split())
i = 0;
while b >= a:
i += 1
a *= 3
b *= 2
print(i) |
Two students of AtCoder Kindergarten are fighting over candy packs.
There are three candy packs, each of which contains a, b, and c candies, respectively.
Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.
Not... | 1 |
l = map(int,raw_input().split())
if l[0] == l[1] + l[2]:
print 'Yes'
elif l[1] == l[0] + l[2]:
print 'Yes'
elif l[2] == l[0] + l[1]:
print 'Yes'
else:
print 'No'
|
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())
s=a//b
y=a%b
count=a+s
while True:
if (s+y)//b==0:
break
else:
tmp=s
s=(s+y)//b
count+=s
y=(tmp+y)%b
print(count) |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ... | 3 | n = int(input())
s = input()
let = {}
for i in range(len(s) - 1):
if s[i] + s[i + 1] in let:
let[s[i] + s[i + 1]] += 1
else:
let[s[i] + s[i + 1]] = 1
max_el = -100000
ans = ''
for i in range(len(s) - 1):
a = s[i] + s[i + 1]
if let[a] > max_el:
max_el = let[a]
ans = a
prin... |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | def ans(n):
if len(str(n)) == 1:
return str(n)
elif list(set(list(str(n)[1:]))) == ['0']:
return str(n)
else:
if str(n)[0] != '0':
return str(int(str(n)[0])*(10**(len(str(n)) - 1))) + ' ' + ans(str(n)[1:])
elif str(n)[0] == '0':
return ans(str(n)[1:])
... |
<image>
Input
The input contains a single integer a (1 β€ a β€ 18257).
Output
Print a single integer output (1 β€ output β€ 2Β·109).
Examples
Input
2
Output
13 | 3 | n = int(input())
print(1+6*n*(n-1))
# Made By Mostafa_Khaled |
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 | #!/usr/bin/env python3
import sys
input = iter(sys.stdin.read().splitlines()).__next__
sys.setrecursionlimit(10000)
TC = int(input())
ans = []
for tc in range(TC):
x, y, n = map(int, input().split())
m = (n//x)
res = x*m + y
if res > n:
res -= x
ans.append(res)
print('\n'.join(map(str, ans)))
|
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:
βShuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.... | 1 | a = [0] * 10
for k in raw_input():
a[int(k)] += 1
s = ""
for i in xrange(1, 10):
if a[i] != 0:
a[i] -= 1
s += str(i)
break
for i in xrange(10):
s += str(i) * a[i]
if s == raw_input():
print "OK"
else:
print "WRONG_ANSWER" |
Vasya came up with a password to register for EatForces β a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.
But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin l... | 1 | t=input()
for _ in range(0,t):
s=list(raw_input())
if (any(x.isupper() for x in s) and any(x.islower() for x in s)
and any(x.isdigit() for x in s) ):
print "".join(s)
else:
fu=[]
fl=[]
fd=[]
for i in range(0,len(s)):
if s[i].isupper():
... |
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase.
A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD... | 3 | # βͺ H4WK3yEδΉ‘
# Mayank Chaudhary
# ABES EC , Ghaziabad
# ///==========Libraries, Constants and Functions=============///
import sys
from bisect import bisect_left,bisect_right
from collections import deque,Counter
from math import gcd,sqrt,factorial,ceil,log10
from itertools import permutations
inf = float("inf")
mod = ... |
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.
You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i... | 3 | a = input()
b = input()
A = a.upper()
B = b.upper()
d = dict(zip(list(a + A), list(b + B)))
s = list(input())
ans = list(map(lambda x : d[x] if x in d else x, s))
print(''.join(ans)) |
There are N slimes standing on a number line. The i-th slime from the left is at position x_i.
It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.
Niwango will perform N-1 operations. The i-th operation consists of the following procedures:
* Choose an integer k between 1 and N-i (inclusive) with equ... | 3 | import sys
n=int(input())
X=[int(i) for i in input().split()]
mod=10**9+7
n_max=n
F,FI=[0]*(n_max+1),[0]*(n_max+1)
F[0],FI[0]=1,1
for i in range(n_max):
F[i+1]=(F[i]*(i+1))%mod
FI[i+1]=pow(F[i+1],mod-2,mod)
ans=0
DP=[0]*n
DP[0]=1
DP[1]=1
ans=(ans+DP[1]*(X[1]-X[0])*F[n-1]*FI[0])%mod
for i in range(2,n):
DP[i]=(F... |
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | 3 | n,t = map(int, input().split())
out = "1"
for i in range(n-1):
out += "0"
out = int(out)
x = out % t
out += t - x
if len(str(out)) != n:
print(-1)
else:
print(out) |
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c... | 1 | record =[[None for i in range(1001)] for j in range(1001)]
record[0][0],record[0][1],record[1][0],record[1][1] = 0,0,0,0
inp = map(int,raw_input().split())
c1,c2 = inp[0],inp[1]
for i in range(1001):
record[i][0] = 0
for j in range(1001):
record[0][j] = 0
def GameTime(c1,c2):
if c1 >= 0 and c2 >= 0:
if record... |
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for t values of n.
Input
The first line of... | 3 |
n = int(input())
for _ in range(n):
m = int(input())
su = (m * (m + 1)) // 2
i = 0
sa = 0
while 2 ** i <= m:
sa += 2 ** i
i += 1
su -= 2 * sa
print(su) |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n Γ m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | for _ in range(int(input())):
n,m,x,y=map(int,input().split())
if(y>=2*x):
ans=0
for i in range(n):
xx=input()
for j in xx:
if(j=='.'):
ans+=x
print(ans)
else:
ans=0
for i in range(n):
xx=input()
... |
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ... | 3 | n = input()
arr = input()
arr = arr.split()
sum1 = 0
sum2 = 0
for i in range(len(arr)):
if int(arr[0]) > int(arr[len(arr) - 1]):
max = arr[0]
arr.pop(0)
else:
max = arr[len(arr) - 1]
arr.pop()
if i % 2 ==0:
sum1 += int(max)
else:
sum2 += int(max)
print("%... |
A: Alphabet block
Wakana Nakawa loves palindromes. Because my name is also a palindrome.
Wakana got a set with some alphabet blocks. An alphabet block is a block in which one lowercase alphabet is written for each block, and you can create your favorite character string by changing the order of the blocks and combini... | 3 | S = input()
dict = {}
for i in range(len(S)):
if(S[i] in dict):
dict[S[i]] += 1
else:
dict[S[i]] = 1
l = list(dict.values())
cnt = 0
for i in range(len(l)):
if(l[i] % 2 != 0):
cnt += 1
print(cnt // 2)
|
Given an integer x, find 2 integers a and b such that:
* 1 β€ a,b β€ x
* b divides a (a is divisible by b).
* a β
b>x.
* a/b<x.
Input
The only line contains the integer x (1 β€ x β€ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 | x = int(input())
if (x == 1):
print(-1)
else:
print(x, x) |
Look for the Winner!
The citizens of TKB City are famous for their deep love in elections and vote counting. Today they hold an election for the next chairperson of the electoral commission. Now the voting has just been closed and the counting is going to start. The TKB citizens have strong desire to know the winner a... | 3 | while True:
vote_n = int(input())
if vote_n == 0:
break
vote_lst = [v for v in input().split()]
vote_cnt = {}
for i, v in enumerate(vote_lst):
if not v in vote_cnt:
vote_cnt[v] = 1
else:
vote_cnt[v] += 1
first = 0
second =... |
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | 3 | a = int(input())
A = list(map(int,input().split()))
A.sort()
k = 0
for i in range(a):
A[i]+=1
q = 0
A.append(10**6)
for i in range(a):
if A[i] == A[i+1]:
if q+2<A[i]:
A[i]-=2
q = A[i]
k+=1
elif q+1<A[i]:
A[i]-=1
q = A[i]
k+=... |
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(""))
L=[]
for k in range(n):
T=input("")
L.append(T)
for k in range(len(L)):
T=L[k]
if(len(T)>10):
T=T[0]+str(len(T)-2)+T[len(T)-1]
print(T)
|
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | 3 | a=input()
c=int(a)
print (a)
i=1
while i<c:
print (i)
i=i+1 |
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 Γ n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed h... | 3 | ## int(input())
## map(int ,input().split())
## int(i) for i in input().split()
n = int(input())
a = [ int(i) for i in input().split()]
rs = 0
for i in range(n):
t = i
l = i - 1
r = i + 1
cnt = 1
while l >= 0 and a[t] >= a[l] :
l -= 1
t = l + 1
cnt += 1
t = i
whi... |
The squirrel Chokudai has N acorns. One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.
His plan is as follows:
1. Get out of the nest with N acorns in his hands.
2. Go to Exchange A and do some trades.
3. Go to Exchange B and do some trades.
4. Go to Exchange A and do some... | 3 | n = int(input())
g1,s1,b1 = map(int,input().split())
g2,s2,b2 = map(int,input().split())
def trade(n,g1,s1,b1,g2,s2,b2):
tradelist = []
for x,y in (g1,g2),(s1,s2),(b1,b2):
if x < y:
tradelist.append((x,y))
if not tradelist:
return n
dp = [0]*(n+1)
for w,v in tradelist:
for i in range(n+1-w):... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 1 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# pylint: disable=C0111
# GleanStart
#9 9
# GleanEnd
def main():
n, m = map(int, raw_input().split())
a = '.' * (m - 1)
b = '#'
c = '#' * m
for x in xrange(n):
if x % 2 == 0:
print c
else:
print "{}{}".format(a... |
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().split('+')
a.sort(reverse=False)
b = '+'
print(b.join(a)) |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 1 | #!/usr/bin/python
n = input()
if n > 0:
print n
else:
n=-n
a, b = n/10, (n/100)*10+n%10
print max(-a, -b)
|
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).
What is xor?
For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\... | 3 | n = int(input())
a = list(map(int,input().split()))
s = 0
for i in a:
s ^= i
b = [s^i for i in a]
print(*b) |
Andrew has recently moved to Wengaluru. He finds this city amazing as all the buildings of the city are of same shape. There are N buildings in a row with no space in between. Buildings may have different heights while width in other two dimensions is always 1 unit.
Rain occurs very frequently in Wengaluru so Andre... | 1 | T = int(raw_input())
def calculate_water(building_heights, starting_index, largest_ending_index):
height = 0
if building_heights[starting_index] < building_heights[largest_ending_index]:
height = building_heights[starting_index]
else:
height = building_heights[largest_ending_index]
... |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | 3 | tests = int(input())
for t in range(tests):
size = int(input())
A = list(map(int, input().split()))
firstfound = False
summ = 0
tempsumm = 0
for i in A:
if i == 0:
if firstfound:
tempsumm+=1
if i == 1:
if not firstfound:
fir... |
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | 3 | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = [0] * n
s[0] = a[0]
for i in range(1, n):
s[i] = s[i - 1] + a[i]
j = 0
for i in range(m):
if b[i] <= s[j]:
if j == 0:
print(j + 1, b[i])
else:
print(j + 1, b[i] -... |
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such th... | 3 | lst=list(map(int,input().split()))
y=lst[1]
x=lst[0]
res=0
ba,bc,bd=y,y,y
while True:
if ba>=x and bb>=x and bc>=x:
print(res)
break
res+=1
if res%3==0:
ba=bb+bc-1
if res%3==1:
bb=ba+bc-1
if res%3==2:
bc=bb+ba-1
|
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and ... | 1 | x=raw_input()
y=raw_input()
z=""
a=0
for i in range(len(y)):
if(y[i]=="(" and a==0):
z+="0"
a=1
elif(y[i]=="(" and a==1):
z+="1"
a=0
elif(y[i]==")" and a==0):
z+="1"
a=1
elif(y[i]==")" and a==1):
z+="0"
a=0
print z
|
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).
Input
The first line contains integers n and k (1 β€ n β€ 100, 0 β€ k β€ 9). The i-th ... | 3 | lt=list(input().split())
n,k=int(lt[0]),int(lt[1])
r=0
while n!=0:
n-=1
D={}
s=input()
for i in s:
if int(i)<=k:
D[int(i)]=1
if len(D)==k+1:
r+=1
print(r)
|
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).
Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M... | 3 | t=int(input())
a=[2,3,4,5,6,7]
for i in range(t):
x=int(input())
if(1<x<=7):
print(1)
else:
for i in range(len(a)-1,-1,-1):
if(x%a[i]<=7):
m=x//a[i]
if(x%a[i]==0):
print(m)
else:
print(m+1)
break
|
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 | import io
import os
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
sel... |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 1 | m,n = map(int, raw_input().split())
if (m*n)%2==0:
s=(m*n)/2
print s
else:
print (m*n)/(2)
|
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | t=int(input())
for i in range(t):
a,b,c=map(int,input().split())
print(int((a+b+c)//2))
|
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... | 3 | T=int(input())
for i in range(T):
a,b,c=map(int,input().split())
r=""
e=97
for i in range(c):
r=r+chr(e)
e=e+1
mo=a%c
di=a//c
ans=(r*di)+r[:mo]
print(ans)
|
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n Γ m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ... | 3 | n, m = map(int, input().split())
card = []
max_eaten = 0
for i in range(n):
card.append(list(input()))
def getItem(arr, row_index, column_index):
if type(arr) == list and row_index >= 0 and row_index < len(arr):
row = arr[row_index]
if type(row) == list and column_index >= 0 and column_index < len(row):
... |
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the sam... | 1 | n = int(raw_input())
a = raw_input()
ans = 0
for i in range(n):
x = 0
y = 0
for k in range(i,n):
x += {'U':0, 'D':0, 'L':-1, 'R':1}[a[k]]
y += {'U':-1, 'D':1, 'L':0, 'R':0}[a[k]]
if x == 0 and y == 0:
ans += 1
print ans
|
There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 β¦ i β¦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.
There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so th... | 3 | N = int(input())
X = []
for i in range(N):
X.append(list(map(int, input().split())))
cnt = 0
for j in range(N,0,-1):
A = X[j-1][0] + cnt
B = X[j-1][1]
if A%B != 0:
cnt += B - A%B
print(cnt) |
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 sys import stdin, stdout
n, m, a = [int(x) for x in stdin.readline().rstrip().split()]
print (n / a + (1 if (n % a) > 0 else 0))*(m / a + (1 if (m % a) > 0 else 0)) |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | s=input()
l=0
for i in range(len(s)):
if s[i]=='4' or s[i]=='7':
l+=1
else:
l=l
if l==4 or l==7:
print('YES')
else:
print('NO') |
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm... | 3 | s = input()
d = {'>' :'1000',
'<' :'1001',
'+' :'1010',
'-' :'1011',
'.' :'1100',
',' :'1101',
'[' :'1110',
']' :'1111'}
r = ''
for c in s :
r += d[c]
print(int(r,2)%1000003)
|
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, β¦, s_n.
Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).
Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} ... | 3 | T = int(input())
def sort_model(elt):
global models
return models[elt-1] * 1000000000 + elt
def sort_pos(elt):
global pos
return pos[elt-1] * 1000000000 + elt
def get_score_from(x):
global dpos
global N
global memo
if x in memo:
return memo[x]
memo[x] = 1
elts[x] = [mo... |
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... | 1 | n, k = map(int, raw_input().split())
l, r = 1, n
for i in xrange(k):
if i % 2:
print r,
r -= 1
else:
print l,
l += 1
if i % 2:
for i in xrange(r, l - 1, -1):
print i,
else:
for i in xrange(l, r + 1):
print i, |
Ashishgup and FastestFinger play a game.
They start with a number n and play in turns. In each turn, a player can make any one of the following moves:
* Divide n by any of its odd divisors greater than 1.
* Subtract 1 from n if n is greater than 1.
Divisors of a number include the number itself.
The player... | 3 | from sys import stdout, stdin
input = stdin.readline
for t in range(int(input())):
n=int(input())
if n==1:
print("FastestFinger")
elif n==2:
print("Ashishgup")
else:
if n%2==1:
print("Ashishgup")
else:
c=0
while n%2==0:
... |
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... | 1 | print ("+".join(sorted(raw_input()[::2]))) |
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... | 1 | n, a, b, c = map(int,raw_input().split())
ar = [0,0,0,0,0]
ar[1] = min(a, min(c*3, b+c) )
ar[2] = min(a*2, min(b, c*2) )
ar[3] = min(a*3, min(a+b, c))
n = 4-(n%4)
print ar[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 | s=input()
if s.isupper():
s=s.lower()
print(s)
elif s[0].islower() and s[1:].isupper():
s=s.lower()
p=s[0]
q=s[1:]
p=p.upper()
print(p,end="")
print(q)
elif len(s)==1:
print(s.upper())
else:
print(s)
|
Two students of AtCoder Kindergarten are fighting over candy packs.
There are three candy packs, each of which contains a, b, and c candies, respectively.
Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.
Not... | 3 | L=list(map(int,input().split()))
L.sort()
print('Yes' if sum(L[:2])==L[2] else 'No') |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | 3 | n = input()
reverseNum = ''.join(reversed(n))
n = n + reverseNum
print(n) |
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... | 3 | ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DIGIT = {ch:i for i, ch in enumerate(ALPHABET, 1)}
LETTER = {i:ch for i, ch in enumerate(ALPHABET, 1)}
def to_number(s):
return sum(DIGIT[s[-i-1]] * 26 ** i for i in range(len(s)))
def to_string(n):
s = ''
while n:
n, mod_ = divmod(n, 26)
if mod_ =... |
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | k = int(input())
l = list(map(int, input().split()))
m = list(map(int, input().split()))
lev = []
for i in range(1, len(l)):
lev.insert(0, l[i])
for i in range(1, len(m)):
lev.insert(0, m[i])
levlast = set(lev)
if len(levlast) == k:
print('I become the guy.')
else:
print('Oh, my keyboard!') |
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 | input()
dp=[0]*100002
for i in list(map(int,input().split())):dp[i]+=i
a,b=0,0
for i in dp:a,b=max(a,b),a+i
print(a)
|
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integer... | 3 | n , k = map(int , input().split())
dict = {}
for i in range(n):
a = int(input())
if a in dict:
dict[a]+=1
else:
dict[a] = 1
count = 0
l = []
for i in dict:
while dict[i]>=2:
count+=2
dict[i]-=2
if dict[i] == 1:
l.append(i)
count+=len(l)//2
if len(l)%2 != 0:... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 1 | n=int(input())
if n==2 or n%2==1:
print "NO"
else:
print "YES" |
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | for T in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
a.sort(reverse = True)
ans = 0
for i in range(n):
ans = max(ans, min(i + 1, a[i]))
print(ans)
|
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty... | 3 | import sys
input = sys.stdin.buffer.readline
from bisect import bisect_left
def prog():
n = int(input())
array = list(map(int,input().split()))
psum = [0]
for i in range(n):
psum.append(psum[-1] + array[i])
occurences = {}
for i in range(n+1):
if psum[i] in occurences:
... |
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I... | 3 | def partition(A, p, r):
x = A[r-1]
i = p-1
for j in range(p,r-1):
if A[j] <= x:
i = i + 1
A[i],A[j] = A[j],A[i]
A[i+1],A[r-1] = A[r-1],A[i+1]
print("{0} [{1}] {2}".format(" ".join(map(str,A[:i+1])),str(A[i+1])," ".join(map(str,A[i+2:]))))
return
if __name__... |
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square β a prime square.
A square of size n Γ n is called prime if ... | 3 | n=10**3
primes=[True]*(n+1)
p={}
for i in range(2,n+1):
if(primes[i]==True):
p[i]=1
for j in range(2*i,n+1,i):
primes[j]=False
for _ in range(int(input())):
N=int(input())
t=1
while(p.get(N-1+t,None)==None):
t+=1
while(p.get(t,None)!=None):
t+=1
... |
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 β€ n β€ 105) β size of the given array. The second line contains n ... | 3 | n = int(input())
nums = [int(x) for x in input().split()]
minimum = min(*nums)
indices = [i for i in range(n) if nums[i] == minimum]
print(min(r - l for l, r in zip(indices, indices[1:]))) |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | from sys import stdin,stdout
a,b = stdin.readline().split()
c = str(int(int(a)*int(b) / 2))
stdout.write(c) |
Notes
Template in C
Constraints
2 β€ the number of operands in the expression β€ 100
1 β€ the number of operators in the expression β€ 99
-1 Γ 109 β€ values in the stack β€ 109
Input
An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.
You can assume that +... | 1 | class Stack():
def __init__(self):
self.el = []
def add(self, el):
self.el.append(el)
def pop(self):
return self.el.pop()
def isEmpty(self):
if len(self.el) == 0:
return True
else:
return False
a = raw_input().s... |
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | 3 | #!/usr/bin/env python3
def is_sorted(l, f):
return all(f(a, b) for a, b in zip(l[:-1], l[1:]))
def main():
n = int(input())
lst = map(lambda _: input(), range(n))
lst = map(lambda s: tuple(map(int, s.split())), lst)
lst = sorted(lst)
if is_sorted(lst, lambda a, b: a[1] <= b[1]):
pri... |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n = int(input())
l = [int(i) for i in input().split(" ")]
s = [0 for i in range(n)]
for i in range(n):
s[i] = (l[i],i + 1)
s = sorted(s)
for i in range(n):
print((s[i])[1], end = ' ')
|
N Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right.
In the test, there are M rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to ... | 1 | t=int(raw_input())
for i in range(t):
x=raw_input()
n,m=map(int,x.split())
y=raw_input()
mval=map(int,y.split())
mx=max(mval)
mn=min(mval)
for z in range(n):
if abs(z-mx)>abs(z-mn):
print abs(z-mx),
else:
print abs(z-mn),
print '' |
"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 | count=0
n,k=map(int,input().split())
arr=list(map(int,input().strip().split()))
temp=arr[k-1]
for i in arr:
if(i>=temp) and i>0:
count+=1
print(count)
|
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya... | 3 | n,d=map(int,input().split())
c=0
l=[]
for i in range(d):
a=input()
a=list(a)
if '0' in a:
c=c+1
else:
l.append(c)
c=0
l.append(c)
print(max(l)) |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 1 | #!/usr/bin/env python
import sys
def input():
x = sys.stdin.readline().split()
try: x = list (map (int, x))
except: pass
if (len(x) == 1): x = x[0]
return x
a = input()
if a == 1:
print ("NO"); exit()
if a == 2:
print ("NO"); exit()
if a % 2 == 0:
print ("YES")
if a % 2 == 1:
print... |
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | a, b, c = input().split()
a, b, c = int(a), int(b), int(c)
print(max(a, max(b, c)) - min(a, min(b, c))) |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a = int (input ())
b=int(input())
c=int(input())
l=[]
d=(a+b)*c
l.append(d)
e=a*(b+c)
l.append(e)
f=a*b*c
l.append(f)
g=a*b+c
l.append(g)
h=a+b*c
l.append(h)
i=a+b+c
l.append(i)
print(max(l)) |
Stack is a container of elements that are inserted and deleted according to LIFO (Last In First Out).
For $n$ stack $S_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations.
* push($t$, $x$): Insert an integer $x$ to $S_t$.
* top($t$): Report the value which should be deleted next from $S_t$. If $... | 3 | # coding=utf-8
N, Q = map(int, input().split())
S = [[] for i in range(N)]
for j in range(Q):
query = list(map(int, input().split()))
if query[0] == 0:
S[query[1]].append(query[2])
elif query[0] == 1:
if S[query[1]]:
print(S[query[1]][-1])
elif query[0] == 2:
if S[q... |
You are given an array a consisting of n integers numbered from 1 to n.
Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i... | 3 | import sys
read = lambda: sys.stdin.readline().strip()
readi = lambda: map(int, read().split())
from collections import defaultdict
for _ in range(int(read())):
n = int(read())
nums = list(readi())
count = defaultdict(int)
maxDist = defaultdict(int)
lastIndex = defaultdict(int)
for num in nums:... |
You are given a permutation p_1, p_2, β¦, p_n of integers from 1 to n and an integer k, such that 1 β€ k β€ n. A permutation means that every number from 1 to n is contained in p exactly once.
Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_... | 3 | n, k = map(int, input().split())
a = [int(i) for i in input().split()]
b = []
for i in range(n):
b.append((a[i], i))
b.sort()
b.reverse()
b = b[:k]
c = []
s = 0
for i in range(len(b)):
s += b[i][0]
c.append(b[i][1])
f = 1
c.sort()
for i in range(1, len(c)):
f = f * (c[i] - c[i - 1])
print(s, f % 9982443... |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | 3 | query=int(input())
for _ in range(query):
num=int(input())
a=list(map(str, range(1, num+1)))
print(" ".join(a)) |
We have a grid with H rows and W columns, where all the squares are initially white.
You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions:
* Choose one row, then paint all the squares in that row black.
* Choose one column, then paint all the s... | 3 | h = int(input())
w = int(input())
n = int(input())
print((n+max(w,h) - 1) // max(w,h)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.