problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x. For example, if x = 4, then the group with levels [1, 10, ...
3
from collections import defaultdict,Counter from math import sqrt, log10, log2, log, gcd, floor,factorial from bisect import bisect_left, bisect_right from itertools import combinations,combinations_with_replacement import sys,io,os input=sys.stdin.readline input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline #...
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() x = [] for i in range(len(a)): if a[i] != b[i]: x.append('1') else: x.append('0') x = ''.join(x) print(x)
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
3
def same_sign(a, b): if a * b < 0: return False else: return True def main(): t = int(input()) while t: t -= 1 n = int(input()) a = list(map(int, input().split())) max_sum = 0 if n == 1: print(a[0]) else: i, j = 0,...
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
import sys len, d = map(int, sys.stdin.readline().split()) s = 1 while (len > 1): s *= 10 len -= 1 printed = False for _i in range(9): if s % d == 0: print(s) printed = True break s += 1 if printed is False: print(-1)
Absent-minded Masha got set of n cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x. To make a number Masha can rotate her cubes and put them in a row. Aft...
3
from itertools import permutations n = int( input() ) a = [] for i in range( n ): x = list( map( int, input().split() ) ) a.append( x ) p = list( permutations( a ) ) L = [] def build( i, z, val ): if val != 0: L.append(val) if i == n: return for j in range( 6 ): build(i+1, z, val*10 + z[i][j] ) f...
You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order: * Wield one of the katana you have. When you wield Katana i (1 ≀ i ≀ N), the monster receives a_i points of dam...
3
n, h = map(int, input().split()) amax = 0 bs = [] for i in range(n): a, b = map(int, input().split()) amax = max(amax, a) bs.append(b) bs = sorted([i for i in bs if i >= amax], reverse=True) ans = 0 for i in bs: h -= i ans += 1 if h <= 0: break else: ans += (h + amax - 1) // amax print(ans)
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
m,n=input().split() m=int(m) n=int(n) maxn=max(m,n) minn=min(m,n) if (maxn==1): print("0") elif (maxn==2*minn): print(maxn*minn//2) else: num=(maxn//2)*minn if (maxn%2==0): print(num) else: num+=minn//2 print(num)
Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder). He is dividing the problems into two categories by choosing an integer K, as follows: * A problem with difficulty K or higher will be for ...
3
N = int(input()) D = sorted(list(map(int, input().split()))) print(D[N//2]-D[(N//2-1)])
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner. Output the probability th...
3
a,b,c,d = map(int,input().split()) z = a/b x = 1 - (a/b) y = 1 - (c/d) m = 1/(1-(x*y)) print(z*m)
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not. The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ...
3
p = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47] n,m = map(int,input().split()) if n in p and m in p: if p.index(n)+1 == p.index(m): print("YES") else: print("NO") else: print("NO")
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are n displays placed along a road, and the i-th of them can display a text with font size s_i only. Maria Stepanovna wants to rent such t...
1
n=int(raw_input()) ls=map(int,raw_input().split()) lc=map(int,raw_input().split()) costs=[lc,[10000000000 for i in range(n)], [10000000000 for i in range(n)]] for i in range(n): for j in range(i+1,n): if ls[i]<ls[j]: costs[1][j]=min(costs[1][j], costs[0][j]+costs[0][i]) costs[2][j]=...
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
q=int(input()) l=[1,2,4,8,16,32,64,128,256,512,1024] for i in range(q): a=input() s=[int(x) for x in input().split()] if 2048 in s: print("YES") else: for i in range(11): while s.count(l[i])>1: s.remove(l[i]) s.remove(l[i]) s.ap...
Input The input contains a single integer a (0 ≀ a ≀ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
3
a = str(bin(int(input())))[2:] a = '0'*(6 - len(a)) + a v1 = [0, 5, 3, 2, 4, 1] v2 = [4, 3, 5, 2, 0, 1] v3 = [5, 2, 0, 3, 1, 4] v4 = [1, 2, 0, 3, 5, 4] ans = "" for i in v1: ans += a[i] print(int(ans, 2))
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that: * If we consider any color, all elements of this color must be divisible by the minimal element of this color. * The number of used colors must be minimized. For example, it's fine to paint elements [40, 1...
3
a=int(input()) n=list(map(int,input().split())) n.sort() i=0 j=0 while i<len(n): j=i+1 while j<len(n): if n[j]%n[i]==0: n.remove(n[j]) else: j+=1 i+=1 print(i)
When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him. Constra...
3
a = input() a = a[0:3] print (a)
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
for k in [*open(0)][1:]: n,s=map(int,k.split());v=n;d=0 while sum(map(int,str(n)))>s:dig=n//(10**(d))%10;n=n+(10-dig)*(10**d);d=d+1; print(n-v)
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 2. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones (0 means...
3
import re n=int(input()) s=input() a=re.search('000',s) #print(a) b=re.search('11',s) #print(a,b) if s=='0': print("NO") elif s=='00': print("NO") elif s[-2:]=='00': print("NO") elif s[:2]=='00': print("NO") else: if a or b: print("NO") else: print("YES")
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
3
account=int(input()) if account>=0: print(account) else: account_1=str(account)[0:-1] account_2=str(account)[0:-2]+str(account)[-1] print(max(int(account_1),int(account_2)))
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β€” when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything ...
3
def main(): from math import pi d, h, v, e = map(float, input().split()) x = v / (d * d * pi * .25) if x > e: print("YES") print(h / (x - e)) else: print("NO") if __name__ == "__main__": main()
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n=int(input()) x,y,z=0,0,0 for i in range(0,n): a2=list(map(int,input().split())) x+=a2[0] y+=a2[1] z+=a2[2] print("YES" if(x==0 and y==0 and z==0) else "NO")
You are given an array a consisting of n integers. You can remove at most one element from this array. Thus, the final length of the array is n-1 or n. Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array. Recall that the contiguous subarray a wi...
3
n = int(input()) a = list(map(int, input().split())) subarray = [] cur_length = 1 for i in range(n - 1): if a[i] < a[i + 1]: cur_length += 1 else: subarray.append(cur_length) cur_length = 1 subarray.append(cur_length) result = max(subarray) index_acc = 0 for i in range(len(subarray) - 1)...
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()) cnt = 0 prev = '' for _ in range(n): x = input() cnt += x != prev prev = x print(cnt)
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
3
t = int(input()) for _ in range(t): a = input() n = int(a[0]) x = len(a) res = ((n - 1) * 10) + (x * (x + 1)) // 2 print(res)
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i. Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob β€” from right to left. The game ends if all the candies are eaten. The process consists o...
3
t=int(input()) for i1 in range(t): n=int(input()) l=list(map(int,input().split())) i=-1 i_help=0 j=n j_help=n-1 a=0 sum_a=0 b=0 sum_b=0 chance=0 move=0 prev=0 traversed=0 while i<j: #print('i at ',l[i]) #print('j at ',l[...
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team. At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix...
3
def process(): for i in t: cnt[ord(i) - ord('a')] -= 1 if cnt[ord(i) - ord('a')] < 0: return 'need tree' if len(s) == len(t): return 'array' i, j = 0, 0 while i < len(s) and j < len(t): if s[i] == t[j]: i += 1 j += 1 else: ...
Today is the ticket release date for Aizu Entertainment's recommended idol group "Akabeko & Koboushi". There are four types of tickets: S seat 6000 yen A seat 4000 yen B seat 3000 yen C seat 2000 yen You, the sales manager, are excitedly waiting for the launch. Finally on sale. It's selling very well! Shortly after ...
3
for _ in range(4): t,n = map(int,input().split()) if t == 1: print(6000*n) elif t == 2: print(4000*n) elif t == 3: print(3000*n) elif t == 4: print(2000*n)
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
1
n = int(raw_input()) l = raw_input() l = l.split() l = [int(i) for i in l] m = range(1001) m = [0 for i in m] for i in l: m[i] += 1 maxm = max(m) k = len(set(l)) print '%d %d' % (maxm, k)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
#!/usr/bin/env python # coding: utf-8 # In[13]: x = input() x = list(x.lower()) # In[14]: s="" for i in range(len(x)): if x[i] not in "aeioyu": s = s+"."+x[i] # In[15]: print(s)
The girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Tayl...
3
from sys import stdin, stderr, stdout, exit def check(x:int): return 2 if (x % 400 == 0 or (x % 4 == 0 and x % 100 != 0)) else 1 def main(): x = int(stdin.readline().strip()) s = 0 for y in range(x+1, 1000000): s += check(y) if(s % 7 == 0 and check(x) == check(y)): stdout.w...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
_ = input() print('HARD' if any(map(int, input().split())) else 'EASY')
Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose...
3
t=int(input()) for i in range(t): n=int(input()) a=list(map(int, input().split(" "))) dp=[0 for i in range(n)] for k in range(n): maxs=[[a[k], k]] mins=[[a[k], k]] cnt=1 if(k>=n-2): cnt=n-k else: for pro in range(k+1, min(n, k+5)): if(a[pro]>=a[k]): maxs.append([a...
Hansa is throwing a birthday party. Seeing the extravagant parties thrown by her friends in the past, Hansa too decided to do something unique. Being a Computer Engineer herself, she knew just how to do it. She sent password-protected e-invites to T of her friends. Along with each of those e-invites there would be a nu...
1
t=input() while t: a=map(str, raw_input("").split()) base=int(a[0]) stri=a[1] q=1 ans=0 while len(stri)>0: l=stri[-1] if ord(l)<59: l=ord(l)-48 else: l=ord(l)-87 ans+=q*l q*=base stri=stri[:-1] x=str(ans) print sum(i...
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
3
v='aouie' s=input()+'b' #print(list(zip(s, s[1:]))) print(('NO','YES')[all(x in v+'n' or y in v for x,y in zip(s,s[1:]))])
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways ...
3
'''input 2 4 ''' a, b = map(int, input().split()) first, draw, second = 0,0,0 for i in range(1,7): if(abs(i-a) < abs(i-b)): first += 1 elif(abs(i-a) > abs(i-b)): second += 1 else: draw += 1 print(first, draw, second)
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
1
s1=raw_input() s2=raw_input() s3=raw_input() if len(s1)+len(s2)!=len(s3): print 'NO' else: list1=list(s1)+list(s2) list1.sort() list2=list(s3) list2.sort() if list1==list2: print 'YES' else: print 'NO'
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key. To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this stri...
1
s = [] for l in raw_input(): if l == 'B': if s:s.pop() else: s.append(l) print ''.join(s)
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game. Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, ...
3
n=int(input()) if n<=3: print("NO") elif n%2==0: print("YES") print("1 * 2 = 2") print("2 * 3 = 6") print("4 * 6 = 24") for x in range(5,n,2): print(x+1,"-",x,"=","1") print("24 * 1 = 24") else: print("YES") print("2 - 1 = 1") print("1 + 3 = 4") print("4 * 5 = 20"...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
import sys,os if (os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") input = lambda:sys.stdin.readline().strip() li = lambda:list(map(int,input().split())) I = lambda:int(input()) for _ in range(I()): n= I() l = [i for i in range(n,0,-1)] print(*l)
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str...
3
n = int(input()) for i in range(n): a,b = list(map(int,input().split())) if a<(b+1)/2 : print('NO') else : print('YES')
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa...
1
# theMonkeyKing # CodeForces 740-A # Main Function def main( ): from sys import stdin, stdout n, m = stdin.readline().split() n = int(n) m = int(m) lines = stdin.readline() mood = list( lines.split(' ') ) mood = map( int, mood ) F = [0] * (n+1) for i in range(0, m) : l, r ...
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: * start the race from some point of a field, * go around the flag, * close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the poin...
3
a,b = map(int,input().split()) x,y = map(int,input().split()) p = abs(a-x)+1 q = abs(y-b)+1 p = max(p,2) q = max(q,2) print(2*(p+q))
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced β€” their sum is equal to 0. Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means...
3
n = int(input()) flag = False for i in range(n): x = int(input()) if x % 2 == 0: print(x // 2) else: if flag is False: print(x // 2) flag = True else: print(x // 2 + 1) flag = False
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,...
3
n=int(input()) for _ in range(n): p=int(input()) A=list(map(int,input().split())) B=set() work=False for t in range(p): lm=(A[t]+t)%p if lm in B: work=True print("NO") break B.add(lm) if not work: print("YES") ...
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≀ a < b ≀ n. The greatest common divisor, gcd(a, b), of two positive integ...
3
for _ in range(int(input())): n=int(input()) if n % 2 == 0: print(n//2) else: n=n-1 print((n//2))
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
T = int(input()) for _ in range(T): a, b = map(int, input().split(" ")) c = 0 if a < b: if a % 2 != 0 and b % 2 == 0: c = 1 if a % 2 != 0 and b % 2 != 0: c = 2 if a % 2 == 0 and b % 2 == 0: c = 2 if a % 2 == 0 and b % 2 != 0: c ...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
1
n = int(raw_input()) count = 0 for i in xrange(n): p, v, t = map(int, raw_input().split()) if p + v + t >= 2: count += 1 print count
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
x = 0 for n in range(int(input())): if "+" in input(): x += 1 else: x -= 1 print(x)
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β€” their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
a = [int(x) for x in input().split()] v = 0 for i in a: v += i v //= 3 for i in sorted(a[::])[:-1]: print(v - i, end = " ")
Find the minimum area of a square land on which you can place two identical rectangular a Γ— b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≀ a, b ≀ 100) β€” positive integers (you are given ...
3
t= int(input()) ans=[] for i in range(t): a,b=[int(i) for i in input().split()] s=min(max(2*a,b),max(2*b,a)) m=s**2 ans.append(m) for i in ans: print(i)
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct points and m segme...
3
from sys import stdin,stdout nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) for _ in range(1):#nmbr()): n,k=lst() mp={} a=lst() for i in range(n): mp[a[i]]=i b=sorted(a) turn=0 ans=[0]*n for v in b: ans[mp[v]]=turn&1 tur...
Step up and down Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and...
3
while True : n = int(input()) if n == 0 : break posi = 0 right = 0 left = 0 cnt = 0 task = list(input().split()) for i in range(n) : if task[i] == 'lu' : left = 1 elif task[i] == 'ru' : right = 1 elif task[i] == 'ld' : ...
Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue. After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence ...
3
# @author import sys class BRedAndBlue: def solve(self, tc=0): for _ in range(int(input())): n = int(input()) r = [int(_) for _ in input().split()] m = int(input()) b = [int(_) for _ in input().split()] ri = bi = 0 answers = [0] ...
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure. Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed...
3
N=input().split() x=0 abdo="" for oba7 in range(3): N[oba7]=int(N[oba7]) while N[2]**x<N[0]: x+=1 if N[2]**x<=N[1]: while N[2]**x<=N[1] : abdo=abdo+str(N[2]**x)+" " x+=1 print(abdo) else: print(-1)
Given a permutation p of length n, find its subsequence s_1, s_2, …, s_k of length at least 2 such that: * |s_1-s_2|+|s_2-s_3|+…+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2. * Among all such subsequences, choose the one whose length, k, is as small as possible. If mul...
3
t = int(input()) for loop in range(t): n = int(input()) arr = list(map(int,input().split())) ans = [arr[0]] for i in range(1,n-1): if(arr[i]>arr[i-1] and arr[i]>arr[i+1]): ans.append(arr[i]) elif(arr[i]<arr[i-1] and arr[i]<arr[i+1]): ans.append(arr[i]) ans.app...
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β€” a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec...
1
n = input() a = map(int, raw_input().split()) if n == 2: print a[1] - a[0], a[1] - a[0] print a[1] - a[0], a[1] - a[0] exit(0) print a[1] - a[0], a[-1] - a[0] for i in range(1, n-1): print min(a[i] - a[i-1], a[i+1] - a[i]), max(a[i] - a[0], a[-1] - a[i]) print a[-1] - a[-2], a[-1] - a[0]
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
num_stones = int(input()) stones = list(input()) num_stones_to_remove = 0 idx_i = 0 idx_j = 1 while idx_j < num_stones: if stones[idx_i] == stones[idx_j]: num_stones_to_remove += 1 idx_i += 1 idx_j += 1 print(num_stones_to_remove)
The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
1
n = input() t = [[], [], []] a = map(int, raw_input().split()) for i in xrange(n): t[a[i] - 1].append(i + 1) ans = min(len(t[0]), len(t[1]), len(t[2])) print ans for i in xrange(ans): print t[0][i], t[1][i], t[2][i]
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n β‰₯ 2). In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider t...
3
from sys import stdin, stdout # a0,a1,a2,a3,a4,a5.... # gcd(a0, a1), gcd(a1, a2).... # gcd(gcd(a0, a1), gcd(a1, a2)), gcd(gcd(a2, a3), gcd(a3, a4)).... # gcd(gcd(a1, a2), gcd(a2, a3)), gcd(gcd(a3, a4), gcd(a4, a5)).... # gcd(gcd(gcd(a0, a1), gcd(a1, a2)), gcd(gcd(a2, a3), gcd(a3, a4))).... # segment tree + binary s...
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts. There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses. Find the minimum distance to be traveled when AtCoDeer can start and ...
3
N=int(input()) a=sorted(map(int,input().split())) print(abs(a[-1]-a[0]))
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
for _ in range(int(input())): z1,o1,t1 = list(map(int,input().split())) z2,o2,t2 = list(map(int,input().split())) ans = 0 # 2 vs 1 ans += 2 * min(t1,o2) t1 -= min(t1,o2) o2 -= min(t1,o2) # 0 vs 2 t2 -= min(t2,z1) # 2 vs 2 t2 -= min(t2,t1) ans -= 2 * min(t2,o1) ...
A class of students wrote a multiple-choice test. There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points....
3
import sys import math import bisect def main(): n, m = map(int, input().split()) A = [] for i in range(m): A.append([]) #print(A) for i in range(n): s = input() for j in range(m): A[j].append(s[j]) B = list(map(int, input().split())) ''' print(A) ...
Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates. Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions: * The largest among the values in the i-th row (1 \leq i \leq N) is A_i. * The largest among the value...
3
from bisect import bisect_left N, M = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) MOD = 10**9 + 7 if len(A) != len(set(A)) or len(B) != len(set(B)): print(0) exit() A.sort() B.sort() setA = set(A) setB = set(B) ans = 1 for i, x in enumerate(range(1, N * ...
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each ot...
1
import math def haha(): A = raw_input() A = A.split(" ") a = int(A[0]) b = int(A[1]) i = math.floor(math.sqrt(a)) k = math.floor(math.sqrt(b)) while k*(k+1) > b: k -= 1 if i > k: print "Valera" else: print "Vladik" haha()
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. <image> The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 ≀ a ≀ r_1, l_2 ≀ b ≀ r_2 an...
3
n=int(input()) for i in range(n): l=list(map(int,input().split())) if l[0]!=l[2]: print(l[0],l[2]) elif l[0]==l[2] and l[0]!=l[3]: print(l[0],l[3]) elif l[0]==l[2] and l[0]==l[3]: print(l[1],l[2])
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y? Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime...
3
for _ in range(int(input())): x,y = map(int, input().split()) if x-y == 1 or x-y == 0: print('NO') else: print('YES')
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ...
1
n=input() arr=map(int,raw_input().split()) mi=min(arr) ma=max(arr) diff=ma-mi+1 print diff-n
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
a = [int(s) for s in input().split()] c=1 r=0 k=a[0] n=a[1] w=a[2] for i in range(w): r=r+k*c c=c+1 x=r-n if x>0: print(x) else: print(0)
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute β€” health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
a = int(input()) if a%4 == 1: print(0 ,'A') elif a%4 == 3: print(2, 'A') elif a%4 == 2: print(1, 'B') elif a%4 == 0: print(1, 'A')
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
1
def main(): n, m = map(int, raw_input().split()) a = map(int, raw_input().split()) time = 0 curr_pos = 1 for entry in a: if entry > curr_pos: time += entry - curr_pos curr_pos = entry elif entry < curr_pos: time += n - curr_pos + entry ...
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know l...
3
__author__ = 'Utena' s=input() n=len(s) ans=set() if n<=6: print(0) exit(0) dp=[[False,False]for i in range(n+1)] if n>7: dp[3][1]=True ans.add(s[-3:]) dp[2][0]=True ans.add(s[-2:]) for i in range(4,n-4): if s[(-i):(-i+2)]!=s[(-i+2):(-i+3)]+s[-i+3]and dp[i-2][0] or dp[i-2][1]: dp[i][0]=True...
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that: * If we consider any color, all elements of this color must be divisible by the minimal element of this color. * The number of used colors must be minimized. For example, it's fine to paint elements [40, 1...
3
n=int(input()) a=list(map(int,input().split())) a=sorted(a) vis=[False for i in range(n)] cnt=0 for i in range(n): if vis[i]==False: vis[i]=True cnt += 1 for j in range(i+1,n): if vis[j]==False: if a[j]%a[i] == 0: vis[j]=True print(cnt)
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
import sys n=[ ] a=int(input()) n=list(map(int,input().split())) n1=n2=0 for i in range (len(n)): if n[i] %2==0: n1=n1+1 c=i+1 else : n2=n2+1 b=i+1 if n1>n2 : print(b) else : print(c)
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn. The variance Ξ±2 is defined by Ξ±2 = (βˆ‘ni=1(si - m)2)/n where m is an average of si. The standard deviation of the scores is the square root of their variance. Constraints * n ≀ 1000 * 0 ≀ si ≀ 100 Inpu...
1
import math member = [] score = [] while True: num = int(raw_input()) if num == 0: break member.append(num) score.append(map(int, raw_input().split())) alpha = [] for m, s in zip(member, score): average = sum(s)/float(m) sigma = 0 for t in s: sigma += (t - average)**2 else: ...
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N). Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all th...
3
from sys import setrecursionlimit setrecursionlimit(2 * (10 ** 5)) n = int(input()) ab = [tuple(map(lambda x:int(x)-1, input().split())) for _ in range(n-1)] e = [[] for _ in range(n)] for a, b in ab: e[a].append(b) e[b].append(a) MOD = 10 ** 9 + 7 d = [] def modinv(x): a = x b = MOD u = 1 ...
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of th...
3
n,m=list(map(int,input().split())) arr=list(map(int,input().split())) marr=list(map(int,input().split())) f=[0]*(m+1) cnt,i=0,0 valid=sum(marr) #m while(i<n): f[arr[i]]+=1 if f[arr[i]]<=marr[arr[i]-1]: cnt+=1 if cnt==valid: break i+=1 if i==n: print(-1) else: ans=(i+1)-...
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size nΓ— n and he wants to traverse his grid f...
3
import math,sys from sys import stdin,stdout from collections import Counter, defaultdict, deque input = stdin.readline I = lambda:int(input()) li = lambda:list(map(int,input().split())) def solve(): n=I() a=[] for i in range(n): a.append(input().strip()) p=a[0][1] q=a[1][0] r=a[n-1][n-...
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially S...
3
s=str(input()) t=str(input()) i=0 for j in t : if j==s[i]: i=i+1 print (i+1)
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()) k = 0 for i in range(1, n+1): zhivut, mogut= map(int, input().split()) if mogut - zhivut >=2: k = k + 1 print(k)
On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≀ i ≀ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should...
1
n = int(raw_input()) t = [int(s) for s in raw_input().split()] u = {} for i in xrange(len(t)): y = 2*t[i]+abs(2*i-n+1) u[y] = u.get(y,0)+1 print n - max(u[i] for i in u if i > n)
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (...
3
# -*- coding:utf-8 -*- """ created by shuangquan.huang at 1/8/20 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(N, A): MOD = 10**9 + 7 dp = [0 for _ in range(N+1)] for i in range(N): dp[i+1] = 2 * dp[i] + 2 - dp[A[i]] ...
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
import math n=list(map(int,input().split())) print(math.ceil(n[0]/n[2])*math.ceil(n[1]/n[2]))
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
import collections#deque refers to double ended queue a,b=map(int,input().split()) ar=list(map(int,input().split())) s=set() ar1=collections.deque([]) for i in ar: if i not in s: s.add(i) ar1.appendleft(i) if len(s)>b: s.remove(ar1[-1]) ar1.pop() print(len(s)) print(*...
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
from sys import stdin,stdout def INPUT():return list(int(i) for i in stdin.readline().split()) import math def inp():return stdin.readline() def out(x):return stdout.write(x) import math as M MOD=10**9+7 from random import randint as R ################################### p=10000 D=[True]*(p+1) i=2 while(i**2<=p+1): ...
Extended Euclid Algorithm Given positive integers a and b, find the integer solution (x, y) to ax + by = gcd(a, b), where gcd(a, b) is the greatest common divisor of a and b. Constraints * 1 ≀ a, b ≀ 109 Input a b Two positive integers a and b are given separated by a space in a line. Output Print two inte...
1
def egcd(a, b): (x, lastx) = (0, 1) (y, lasty) = (1, 0) while b != 0: q = a // b (a, b) = (b, a % b) (x, lastx) = (lastx - q * x, x) (y, lasty) = (lasty - q * y, y) return (lastx, lasty) a, b = map(int, raw_input().split()) ans = egcd(a, b) for i in ans: print i,
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho...
3
import sys b,d,s = map(int, sys.stdin.readline().split()) array = [b,d,s] maxx = max(b,d,s) result = 0 for x in array: result += max(0,maxx-1-x) print(result)
Given a permutation p of length n, find its subsequence s_1, s_2, …, s_k of length at least 2 such that: * |s_1-s_2|+|s_2-s_3|+…+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2. * Among all such subsequences, choose the one whose length, k, is as small as possible. If mul...
3
MOD = 1000000007 si = lambda : input() dgl = lambda : list(map(int, input())) ii = lambda : int(input()) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) for _ in range(ii()): n=ii() a=il() l=0 L=0 maxa=-100000000 k=[] k.append(a[0]) D=0 for i...
Vivek has encountered a problem. He has a maze that can be represented as an n Γ— m grid. Each of the grid cells may represent the following: * Empty β€” '.' * Wall β€” '#' * Good person β€” 'G' * Bad person β€” 'B' The only escape from the maze is at cell (n, m). A person can move to a cell only if it shares a...
3
def bfs(c, l, n, m): queue = [(n - 1, m - 1)] while queue: i = queue.pop() if l[i[0]][i[1]] == '#': continue if l[i[0]][i[1]] == 'G': c -= 1 l[i[0]][i[1]] = '#' if i[1] != m - 1: queue.append((i[0], i[1] + 1)) if i[1] != 0: ...
Write a program which reads an integer n and prints the factorial of n. You can assume that n ≀ 20. Input An integer n (1 ≀ n ≀ 20) in a line. Output Print the factorial of n in a line. Example Input 5 Output 120
3
import sys from functools import reduce n = int(sys.stdin.readline().rstrip()) print(reduce(lambda a,b:a*b,range(1,n+1)))
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≀ a, b, c and a β‹… b β‹… c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 100)...
3
ans="" for _ in range(int(input())): n=nn=int(input()) l1=[]; i=2 while len(l1)<2 and i*i<=nn: if n%i==0: l1.append(i); n//=i i+=1 if len(l1)<2 or l1[1]==n or l1[0]==n: ans+="NO\n" else: ans+="YES\n"; ans+=f"{l1[0]} {l1[1]} {n}\n" print(ans)
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk...
1
n = int(raw_input()) def f(i, j): x = n - abs(n - i) - abs(n - j) if x < 0: return ' ' else: return x for i in xrange(2*n+1): s = '' for j in xrange(2*n+1): s += ' ' + str(f(i, j)) print s[1:].rstrip(' ')
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,...
1
n,m,k=map(int,raw_input().split()) M=10**9+9 x=max(0,m-(n/k*(k-1)+n%k)) print ((m-x+(pow(2,x+1,M)-2)*k-x*(k-1))%M+M)%M
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
from __future__ import division from collections import Counter as ctr from math import ceil, log, factorial, sqrt # reads a line of input and converts into a list of ints # 1 1 3 => [1, 1, 3] def rl(): return [int(i) for i in raw_input().split()] # reads n lines of input (if n defined) and returns a list of strin...
Joisino is working as a receptionist at a theater. The theater has 100000 seats, numbered from 1 to 100000. According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive). How many people are sitting at the theater now? Constrai...
3
n = int(input()) s = 0 for i in range(n): a,b = map(int, input().split()) s +=b-(a-1) print(s)
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c...
3
#!/usr/bin/env python3 import sys def rint(): return map(int, sys.stdin.readline().split()) #lines = stdin.readlines() s = list(input()) q = s.count('?') o = s.count('1') z = s.count('0') ans =[] #00 if z+q >= o+1: ans.append("00") #01 tmp = o+q-z - (z+o+q)%2 if tmp%2 == 0: x = tmp//2 if x >= 0 and ...
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c...
3
for i in range(int(input())): x,y = map(int,input().split()) if x % y !=0: c = x%y print(y-c) else: print(0)
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles. The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that...
3
for _ in range(int(input())): n, price = map(int, input().split()) pocket = [int(i) for i in input().split()] pocket.sort(reverse=True) cnt = 0 s = 0 for i in pocket: s += i if s >= (cnt + 1) * price: cnt += 1 else: break print(cnt) ...
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≀ a < b ≀ n. The greatest common divisor, gcd(a, b), of two positive integ...
3
#: Author - Soumya Saurav import sys,io,os,time from collections import defaultdict from collections import OrderedDict from collections import deque from itertools import combinations from itertools import permutations import bisect,math,heapq alphabet = "abcdefghijklmnopqrstuvwxyz" input = sys.stdin.readline ######...
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i. For each square, you will perform either of the following operations once: * Decrease the height of the square by 1. * Do nothing. Determine if it is possible to perform the operations so that the heights ...
3
n = int(input()) h = list(map(int, input().split())) f, mx = 0, 0 for hi in h: if hi > mx: mx = hi if hi <= (mx-2): f = 1; break print('YNeos'[f::2])
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
n = int(input()) array = [list(map(int, input().split())) for _ in range(n)] for [x, y, a, b] in array: if (y - x) % (a + b) == 0: print((y - x) // (a + b)) else: print(-1)
Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one. GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x...
3
from collections import Counter from copy import deepcopy def getMax(c1, c2): ret = 1 << 32 for k in c2.keys(): ret = min(ret, c1[k]//c2[k]) return ret a, b, c = input(), input(), input() counterA, counterB, counterC = Counter(a), Counter(b), Counter(c) cntB, cntC = 0, getMax(counterA, counterC) ...