problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
AtCoDeer the deer is seeing a quick report of election results on TV. Two candidates are standing for the election: Takahashi and Aoki. The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes. AtCoDeer has checked the report N times, and when he c...
3
from fractions import gcd n=int(input()) T,A=1,1 for i in range(n): t,a=map(int,input().split()) m=max(-(-T//t),-(-A//a)) T=t*m A=a*m print(T+A)
— Hey folks, how do you like this problem? — That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: 1. He chooses two piles (i, j) such that 1 ≤ i, j ≤ n and i ≠ j. 2. All candies from pile i are...
3
t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() ct = 0 for i in range(1, n): ct += (k-a[i])//a[0] print(ct)
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: <image> By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n ...
3
import sys def get_single_int (): return int (sys.stdin.readline ().strip ()) def get_string (): return sys.stdin.readline ().strip () def get_ints (): return map (int, sys.stdin.readline ().strip ().split ()) def get_list (): return list (map (int, sys.stdin.readline ().strip ().split ())) #code star...
Let's play Amidakuji. In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines. <image> In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first...
3
w = int(input()) n = int(input()) l = [list(map(int, input().split(','))) for x in range(n)] res = [0] * (w + 1) for i in range(1, w + 1): c = i for a in l: if a[0] == c: c = a[1] elif a[1] == c: c = a[0] res[c] = i for r in res[1:]: print(r)
The year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us...
3
from itertools import product, permutations, combinations n = int(input()) names = {} nex = 0 mama = 128 liking = [0]*mama likes = [[0]*7 for _ in range(7)] def getName(name): global nex if name in names: return names[name] names[name] = nex nex += 1 return names[name] for _ in range(n):...
There are N mountains ranging from east to west, and an ocean to the west. At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns. The height of the i-th mountain from the west is H_i. You can certainly see the ocean from the inn at the top of the westmost mountain. F...
3
n = int(input()) h = list(map(int,input().split())) s = 1 for i in range(1,n): if(h[i] >= max(h[:i])):s += 1 print(s)
For some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated. You are given three numbers: * n_0 — th...
3
t = int(input()) for i in range(t): a, b, c = map(int, input().split()) zeros = 0 zero_ones = 0 ones = 0 addend = False if(a > 0): if(b == 0 and c == 0): zeros = a + 1 elif(c == 0): zeros = a zero_ones = b + 1 else: zer...
Let's denote as <image> the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and <image> is maximum possible. If there are multiple such numbers find the sma...
1
def solve(l, r): bc = bin(l).count('1') best = l x = l for i in xrange(64): x |= (1 << i) if l <= x <= r: nbc = bin(x).count('1') if bc < nbc: bc = nbc best = x else: break return best n = input() for _ in xrange(n): l, r = map(int, raw_input().split()) print solve(l, r)
One quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in ...
1
#!/usr/bin/python import sys import math primes = [] MAXN = 50000 hash = [] dp = dict() def prime_test(v): for i in xrange(2,int(math.sqrt(v))+1): if v % i == 0: return False return True def calc(v, k): if k >= MAXN: if (k <= v): return 1 else: ...
The only difference between easy and hard versions is the maximum value of n. You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n. The positive integer is called good if it can be represented as a sum of distinct powers of 3 (...
3
from math import * def test(nb,indice): global mini if nb - (3**(indice+1) - 1)/2 > 0: return if nb <= 0 or indice <= -1: if nb <= 0: mini = min(mini, -nb) return test(nb - 3**indice, indice - 1) test(nb, indice-1) q = int(input()) for i in rang...
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
3
# cook your dish here s,v1,v2,t1,t2=input().split() time_1=int(t1)+int(s)*int(v1)+int(t1) time_2=int(t2)++int(s)*int(v2)+int(t2) if(time_1<time_2): print("First") elif(time_2<time_1): print("Second") else: print("Friendship")
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes. You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca...
3
I=input for _ in[0]*int(I()): n=int(I());a=[I()for _ in[0]*n] print(n-(all(len(s)%2==0for s in a)&sum(sum(map(int,s))for s in a)%2))
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. Input The first line cont...
3
integers = int(input()) array = input().split(" ") subarray = [] array = [int(i) for i in array] count = 1 index = 0 while index < integers-1: if array[index+1] > array[index]: count += 1 else: subarray.append(count) count = 1 index += 1 subarray.append(count) print(max(subarray))
There is a grid with H rows and W columns, where each square is painted black or white. You are given H strings S_1, S_2, ..., S_H, each of length W. If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is `#`; if that square is painted whi...
3
#深さ優先探索(DFS) import sys sys.setrecursionlimit(1000000) h,w = map(int,input().split()) s = [input() for _ in range(h)] t = [[None]*w for _ in range(h)] def dfs(i,j,color): if not (0<=i<h and 0<=j<w):return 0,0 if s[i][j]==color: return 0,0 if t[i][j]:return 0,0 t[i][j]=True wh,bl=0,0 if s[i][j]=="#...
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 os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.wr...
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n = int(input()) x = input() a = 0 d = 0 for i in x: if i == "A": a += 1 if i == "D": d += 1 if a > d: print("Anton") elif d > a: print("Danik") else: print("Friendship")
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: * a12 + a22 + ... + an2 ≥ x * a1 + a2 + ... + an ≤ y Input The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please d...
1
import sys s = raw_input().split(" ") n = int(s[0]) x = int(s[1]) y = int(s[2]) ns = [ 1 for i in xrange(n)] ns[0] = y+1-n if ns[0]**2>=x-n+1 and ns[0]>0: for i in ns: print i else: print -1
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...
1
# your code goes here z = int(raw_input()) while (z>0): x = raw_input() #print (x) w = len(x) #print w if (w>10): k = w-2 y = x[0]+str(k)+x[w-1] print (y) else: print (x) z=z-1
Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater ...
1
y,k,n = map(int, raw_input().split()) a = 1 L = [] while a * k <= n : if(a * k > y) : L.append(a * k - y) a += 1 if len(L) == 0 : print -1 else : for i in L : print i,
You are given a string S of length N consisting of `A`, `B` and `C`, and an integer K which is between 1 and N (inclusive). Print the string S after lowercasing the K-th character in it. Constraints * 1 ≤ N ≤ 50 * 1 ≤ K ≤ N * S is a string of length N consisting of `A`, `B` and `C`. Input Input is given from Standa...
3
n,k = map(int,input().split()) s = input() S = s[k-1].lower() print(s[:k-1]+S+s[k:])
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided ...
3
n = int(input()) min = 0 res = input().split() for i in range(n): min += i*int(res[i]) print(4*min)
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
3
n=input() n=int(n[-2:]) print(n%2)
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,...
3
d = lambda i, j, k: sum((a - c) * (b - c) for a, b, c in zip(p[i], p[j], p[k])) * (i != j) n = int(input()) r = range(n) p = [list(map(int, input().split())) for i in r] t = [k + 1 for k in r if all(d(i, j, k) <= 0 for i in r for j in r)] if n < 12 else [] for q in [len(t)] + t: print(q) # Made By Mostafa_Khale...
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019. Constraints * All values in input are integers. * 0 \leq L < R \leq 2 \times 10^9 Input Input is given from Standard Input in the fol...
3
l,r=map(int,input().split()) ans=2019 for i in range(l,min(l+2019-1,r)): for j in range(l+1,min(l+2019,r+1)): ans=min(ans,((i%2019)*(j%2019))%2019) print(ans)
There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to onl...
3
import sys input = sys.stdin.buffer.readline sys.setrecursionlimit(10 ** 7) mod = 10 ** 9 + 7 N = int(input()) AB = [] for _ in range(N): AB.append((int(input()), 0)) for _ in range(N): AB.append((int(input()), 1)) AB.sort(reverse=True) ans = 1 Aset = 0 Bset = 0 while AB: _, x = AB.pop() if x: ...
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w...
3
t = int(input()) for _ in range(t): n, k = map(int, input().split()) bitstring = input() zero = 0 one = 0 answer = True for j in range(k): balanced = "?" for i in range(j, n, k): if bitstring[i] != "?": if balanced != "?": if bala...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a= input() b = input() a = a.lower() b = b.lower() if a<b: print(-1) elif a>b: print(+1) else: print(0)
When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC. You, the smartwatch, has found N routes to his home. If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i. Find the smallest cost of a route that takes not l...
3
n,T=map(int,input().split()) C=1001 for i in range(n): c,t=map(int,input().split()) if t<=T: C=min(C,c) if C==1001: print("TLE") exit() print(C)
Transformation Write a program which performs a sequence of commands to a given string $str$. The command is one of: * print a b: print from the a-th character to the b-th character of $str$ * reverse a b: reverse from the a-th character to the b-th character of $str$ * replace a b p: replace from the a-th charact...
3
x = list(input()) n = int(input()) for i in range(n): com = input().split() a = int(com[1]) b = int(com[2]) if com[0] == "print": print("".join(x[a:b+1])) elif com[0] == "reverse": x[a:b+1] = x[a:b+1][::-1] elif com[0] == "replace": x[a:b+1] = list(com[3])
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi...
3
from math import * from copy import * # ll = deepcopy(l) from heapq import * # heappush(hp,x) from string import * # alpha = ascii_lowercase from random import * # l.sort(key=lambda l1:l1[0]-l1[1]) => ex: sort on the basis difference from bisect import * # bisect_left(arr,x,start,end) => start and end...
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked....
3
n = int(input()) myset = set() for _ in range(n): myset.add(input()) print(len(myset))
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return (int(input())) def instr(): return (str(input())) def inlt(): return (list(map(int, input().split()))) def insr(): s = input() return(list(map(int, list(s[:len(s) - 1])))) # def insr(): # ...
You are given an integer n (n ≥ 0) represented with k digits in base (radix) b. So, $$$n = a_1 ⋅ b^{k-1} + a_2 ⋅ b^{k-2} + … a_{k-1} ⋅ b + a_k.$$$ For example, if b=17, k=3 and a=[11, 15, 7] then n=11⋅17^2+15⋅17+7=3179+255+7=3441. Determine whether n is even or odd. Input The first line contains two integers b and...
3
import sys import math from collections import deque def scan(): return list(map(int, sys.stdin.readline().strip().split())) def print_primes_till_n(n): i, j, flag = 0, 0, 0 a = [] c = 0 for i in range(1, n + 1, 1): if i == 1 or i == 0: continue flag = 1 for j...
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras. Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now ...
3
s = input() ans = 1 m = [1] * len(s) for i in range(1, len(s)): if s[i] != s[i-1]: m[i] = m[i-1] + 1 if m[i] > ans: ans = m[i] else: m[i] = 1 if s[0] != s[-1]: if m[-1] == len(s): print(m[-1]) exit() else: for i in range(len(s)): ...
Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. GCD(a, b) is the greatest common divisor of numbers a and b. You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, s...
3
from math import gcd def lcm(a, b): if min(a, b) == 0: return max(a, b) return a // gcd(a, b) * b class equation(): def __init__(self, r, mod): self.r = r self.mod = mod def goodBye(): print("NO") exit(0) def exgcd(a,b): if b == 0: return (1,0) xp,yp = exgc...
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears: 1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; 2. Let ...
3
from heapq import * t = int(input()) for u in range(t): n = int(input()) h = [] a = [0] * n heappush(h, (n, 0, n-1)) ln = 1 i = 1 while ln > 0: now0, now1, now2 = heappop(h) ln -= 1 if now1 == now2: a[now1] = i else: a[now1 + (now2 ...
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
n=int(input()) m=[int(i) for i in input().split()] amazing=0 mx=m[0] mn=m[0] for i in range(1,n): if m[i]>mx: mx=m[i] amazing+=1 if m[i]<mn: mn=m[i] amazing+=1 print(amazing)
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. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with...
1
n = input() x= n while x % 7 != 0: x -= 4 if x < 0: if n % 4 == 0: print '4'*(n/4) else: print -1 else: print '4'*((n-x)/4)+'7'*(x/7)
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the...
3
for t in range(int(input())): k = int(input()) ntc = list(map(int, input().split())) max_inp = max(ntc) if len(set(ntc)) == 1: print(-1) elif max(ntc) == ntc[0]: if ntc[0] != ntc[1]: print(1) else: for i in range(k): if ntc[i] != ntc[0]...
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c. Unfortunately, an adversa...
3
import sys,math,bisect,random input=sys.stdin.readline T=int(input()) for _ in range(T): l,r,m=map(int,input().split()) a,b,c=m,m,m if (m>=l and m<=r): a,b,c=m,l,l elif (m<l): a,b,c=l,l,(2*l)-m else: a,b,c=0,0,0 diff=r-l for i in range(l,r+1): v...
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
1
s=input() num=raw_input() num=list(num) n=[int(i) for i in num] n=sorted(n) k=sum(n) count=0 l=len(n) for i in range(l): if k>=s: break else: k=k-n[i]+9 n[i]=9 count+=1 print count
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
3
moneys = [int(x) for x in input().split()] m = 0 for money in moneys: m += money if m == 0 or m % 5 != 0: print('-1') else: print(int(m / 5))
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) x = 0 for i in range(n): bit = input() if (bit == '++X' or bit == 'X++'): x += 1 else: x -= 1 print(x)
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible. String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too. Input First line of input con...
1
s = list(raw_input()) m = set(s) k = int(raw_input()) if(len(s)<k): print "impossible" else: if(k< len(m)): print 0 else: print (k - len(m))
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative; 2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a...
3
import math a=int(input()) b=list(map(int,input().strip().split())) positive=[0] negative=[0] nans=0 pans=0 for i in range(1,a+1,1): if b[i-1]>0: positive.append(positive[i-1]+1) negative.append(negative[i-1]) else: positive.append(negative[i-1]) negative.append(positive[i-1]+1) ...
You are given a string s consisting of n lowercase Latin letters. Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from po...
3
n=int(input()) s=input() cur=s[0] idx=0 pos=0 for i in range(1,n): if ord(s[i])<ord(cur): pos=1 l=idx+1 r=i+1 break else: idx=i cur=s[i] if pos==0: print("NO") else: print("YES") print("{} {}".format(l,r))
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the wa...
3
import copy n=int(input()) ocu=[0]+list(map(int,input().split())) V=dict() for i in range(1,n+1): V[i]=ocu[i] ocu=[0]*(n+1) stream=[0]*(n+1) l=0 ans=[] for i in range(1,n): stream[i]=i+1 stream[n]=0 m=int(input()) for i in range(m): s=list(map(int,input().split())) if s[0]==1: x0,p=s[1],s[2] ...
The only difference between easy and hard versions is the maximum value of n. You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n. The positive integer is called good if it can be represented as a sum of distinct powers of 3 (...
3
import sys q = int(input()) for _ in range(q): n = int(input()) b = [] while n > 0: b.append(n % 3) n = int(n / 3) c = 0 for p in range(len(b)): b[p] += c c = 0 if b[p] <= 1: continue for u in range(p + 1): b[u] = 0 c ...
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
def previous(l,index): if(index==0): return 0 count=0 while(l[index-1]<=l[index]): index-=1 count+=1 if(index<1): break return count def after(l,index): if(index==len(l)-1): return 0 count=0 while(l[index+1]<=l[index]): index+=1 ...
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
1
n = int(input()) print (-1)**n * ((n+1)//2)
You are given the array a consisting of n elements and the integer k ≤ n. You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: * Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ...
3
from collections import defaultdict as dd n , k = map(int,input().split()) arr = list(map(int,input().split())) arr.sort() d = dd(list) check = [] for i in range(n): cnt = 0 d[arr[i]].append(cnt) while arr[i]>1: arr[i] = arr[i]//2 cnt += 1 d[arr[i]].append(cnt) m = 10e15 for x in d: ...
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second —...
1
book, first_day, max_can_read, a, re_read = map(int,raw_input().split()) days_required = 0 if book<first_day: days_required+=1 else: days_required+=1 pages_read = first_day temp = 0 while pages_read<book: temp+=a days_required+=1 if (first_day + temp)<max_can_read: pages_read += (first_day + temp) - (re_r...
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
for _ in range(int(input())): n,k1,k2=list(map(int,input().split())) a=list(map(int,input().split())) b=list(map(int,input().split())) if max(a)>max(b): print("YES") else: print("NO")
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
R=lambda:map(int,input().split()) n,k=R() a=[] d={} i=1 for x in R(): if d.get(x,0)<i:d[x]=i+k;a+=x,;i+=1 a=a[::-1][:k] print(len(a),*a)
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. Input The first line contai...
3
n = int(input()) m = int(input()) a_list = list() for i in range(0,n): a_list.append(int(input())) if max(a_list) >= m: print(1) else: a_list = sorted(a_list, reverse = True) sum_a = 0 for k in range(0,n): sum_a = sum_a + a_list[k] if sum_a >= m: print(k+1) br...
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex...
3
from itertools import permutations n, m = map(int, input().split()) maze = [list(input()) for _ in range(n)] s = list(map(int, list(input()))) dxy = [(1, 0), (0, 1), (-1, 0), (0, -1)] sx = sy = ex = ey = 0 for y in range(n): for x in range(m): if maze[y][x] == 'S': sx = x sy = y ...
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of ...
3
n=int(input()) a=list(map(int,input().split())) for i in range(n): while a[i]%2==0: a[i]//=2 while a[i]%3==0: a[i]//=3 print("YES" if max(a)==min(a) else "NO")
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: * if the character w_{i-x} exists and is equal to 1, then s_i is 1 (forma...
3
t = int(input()) for _ in range(t): s = input() n = len(s) x = int(input()) w = [0]*n for i in range(n): if 0 <= i + x < n and 0 <= i - x < n: if s[i+x] == "1" and s[i-x] == "1": w[i] = 1 elif 0 <= i + x < n: if s[i+x] == "1": w...
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by 猫屋 https://twitter.com/nekoy...
3
s=input() n=len(s) a=0 for i in range(n-2): for j in range(i+1,n-1): for k in range(j+1,n): if s[i]=='Q' and s[j]=='A' and s[k]=='Q': a+=1 print(a)
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=list(map(int,input().split())) m=[0]*n for i in range(n): m[l[i]-1]=i+1 for i in m: print(i,end=" ")
Given an array a of length n, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square. A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Input The first line contains an integer t (1 ≤ t ≤ 100) — the...
3
import math def is_square(integer): root = math.sqrt(integer) return integer == int(root) ** 2 for T in range(int(input())): n=int(input()) arr=list(map(int,input().split())) for i in arr: if (not is_square(i)): print("YES") break else: print("NO")
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank. One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible. Vasya ha...
3
x=int(input()) d=list(map(int,input().split())) a,b=map(int,input().split()) print(sum(d[a-1:b-1]))
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
input() a,d=map(input().count,['A','D']) print(['Anton',['Danik','Friendship'][a==d]][a<d or a==d])
As a New Year's gift, Dolphin received a string s of length 19. The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`. Dolphin wants to convert the comma-separated string s into a space-separated string. Write a program to perform th...
3
S = input() print(S.replace(',',' '))
E869120 found a chest which is likely to contain treasure. However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters. He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with `?`. One more t...
3
S=input() T=input() for i in reversed(range(len(S)-len(T)+1)): st=S[i:i+len(T)] t=1 for j in range(len(T)): if(st[j]!='?' and st[j]!=T[j]): t=0 break if(t==1): S=S.replace('?','a') print(S[:i]+T+S[i+len(T):]) exit() print("UNRESTORABLE")
You have three piles of candies: red, green and blue candies: * the first pile contains only red candies and there are r candies in it, * the second pile contains only green candies and there are g candies in it, * the third pile contains only blue candies and there are b candies in it. Each day Tanya eats...
3
t = int(input()) for _ in range(t): arr = list(map(int, input().split())) arr.sort() if arr[2]-arr[0] >= arr[1]: print(arr[1]+arr[0]) else: print(int(arr[1]+(arr[0]-(arr[1]-(arr[2]-arr[0]))/2)))
A game is played on a strip consisting of N cells consecutively numbered from 1 to N. Alice has her token on cell A. Borys has his token on a different cell B. Players take turns, Alice moves first. The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or...
3
n,a,b=map(int,input().split());print('ABloircyes'[(b-a)%2==1::2])
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
from sys import stdin from collections import Counter stdin.readline() nums = list(map(int, stdin.readline().rstrip().split(' '))) l = Counter() for i, e in enumerate(nums): l[e] = i print(len(l)) for element, index in reversed(l.most_common()): print('{} '.format(element), end='')
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
I = input for _ in range(int(I())): n,k=map(int,I().split()) a=list(map(int,I().split(' '))) b=list(map(int,I().split(' '))) b.sort(reverse=True) a.sort() for i in range(n): if a[i]<b[i] and k>0: a[i]=b[i] k-=1 print(sum(a))
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list. For ex...
3
n=int(input()) a=list(map(int,input().split())) temp=max(a) first=[];second=[] for i in a: if temp%i==0 and i not in first: first.append(i) else: second.append(i) print(max(first),max(second))
Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit...
3
# Description of the problem can be found at http://codeforces.com/problemset/problem/275/A l_l = list() d_x = [ 0, -1, 1, 0, 0] d_y = [-1, 0, 0, 1, 0] for i in range(3): l_l.append(list(map(int, input().split()))) l_c = list(list(1 for _ in range(3)) for _ in range(3)) for i in range(3): for j in r...
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of n⋅ m different seals, denoted by distinct numbers. All of them were written in an n× m table. The table is lost now. Naruto managed to remember elements of each row from left to right, and eleme...
3
from sys import stdin input = stdin.readline for _ in range(int(input())): n, m = map(int, input().split()) rows = [] rowThatStartsWithNum = {} for i in range(n): rows.append(list(map(int, input().split()))) rowThatStartsWithNum[rows[i][0]] = i firstRowIndex = None for i in r...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
s = input() finalS = "" for i in s: if i not in "AOYEUIaoyeui": finalS = finalS + i for i in finalS: print("." + i.lower(), end="")
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 109) of the equation: x = b·s(x)a + c, where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in...
3
a,b,c=map(int,input().split()) l=[] for i in range(1,82): x=b*(i**a)+c y=abs(x) n=list(map(int,str(y))) if x>0 and x<10**9 and sum(n)==i: l.append(x) print(len(l)) print(*l)
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i. Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ...
3
import collections, heapq, bisect, math def gcd(a, b): if b == 0: return a return gcd(b, a%b) def solve(A): curr_low = float('Inf') out = 0 for i in range(len(A)-1,-1,-1): if A[i] < curr_low: curr_low = A[i] if A[i] > curr_low: out+= 1 return out q = input() tests = [] for te...
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that als...
3
n = int(input()) a = (list(map(int, input().split()))) a.sort() if a[-1] == 1: print(*(a[:-1] + [2])) else: print(1, *a[:-1])
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc. <image> Barney woke up in the morning and wants to eat the ...
3
a,b,c=map(int,input().split()) if a>c: print("NO") elif (c-a)%b==0: print("YES") elif (c-a)%b==1 and (c-a)//b: print("YES") else: print("NO")
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scisso...
3
Q=lambda x,y:Q(y%x,x)if x else y I=input R=range n=int(I()) s=I() p=I() G=len(p)//Q(len(s),len(p))*len(s) s*=G//len(s) p*=G//len(p) a=b=0 for i in R(G): t=s[i]+p[i] if t=='RS'or t=='SP'or t=='PR':a+=1 elif t=='SR'or t=='PS' or t=='RP':b+=1 a*=(n//G) b*=(n//G) for i in R(n%G): t=s[i]+p[i] if t=='RS'or t=='SP'or t==...
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is...
3
n, L, a = list(map(int, input().split())) result = 0 start = 0 if n == 0: result = L // a else: for i in range(n): ti, li = list(map(int, input().split())) result += (ti - start) // a start = ti + li result += (L - start) // a print(result)
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
watermelon_weight = int(input("")) can_be_divided = False for i in range(0, watermelon_weight, ): A = (watermelon_weight - i) // 2 B = watermelon_weight - A if A % 2 == 0 and B % 2 == 0 and B > 0 and A > 0: can_be_divided = True break if can_be_divided: print("YES") else: print("NO")...
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
1
'''148a''' k = int(raw_input()) l = int(raw_input()) m = int(raw_input()) n = int(raw_input()) d = int(raw_input()) s = set() for i in xrange(d/k): s.add(k*(i+1)) for i in xrange(d/l): s.add(l*(i+1)) for i in xrange(d/m): s.add(m*(i+1)) for i in xrange(d/n): s.add(n*(i+1)) print len(s)
You are given a chess board with n rows and n columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board. A knight is a chess piece that can attack a piece in cell (x_2, y_2) from the cell (x_1, y_1) if one of the following conditions is met: * |x_...
3
n=int(input()) oe=1; ans="" for i in range(n): for j in range(n): ans=ans+"W" if oe%2 else ans+"B" oe+=1 ans+='\n' oe=1 if i%2 else 0 print(ans)
In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc. The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0). Aoki, an explorer, conducted a survey to identify the center ...
3
#Nへの代入 N=int(input()) #データのリストdata [x座標,y座標,高さ] k=0 data=list() for i in range(N): l=list(map(int,input().split())) data.append(l) if(l[2]>0): k=i #中心点の探索 for x in range(101): for y in range(101): H=data[k][2]+abs(x-data[k][0])+abs(y-data[k][1]) if all([max(H-abs(x-l[0])-abs(y-...
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of...
3
x = eval(input()) z=0 i =0 while (z<x): l = list(map(int,input().split())) print(l[0],(2*l[0])) z+=1
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is calle...
1
n = input() a = map(int,raw_input().split()) d = {i:0 for i in range(1, 5001)} for i in a: d[i] += 1 c = 0 for i in range(1, n+1): if d[i] == 0: c += 1 print c
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right. AquaMoon can make some operations on friends. On each operation, AquaM...
3
import math # region fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = s...
The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on o...
3
x1, x2, a, b = map(int, input().split()) if a <= 0 <= b: if x1 < x2: if x2 - x1 <= b: print("FIRST") print(x2) else: print("DRAW") else: if x1 - x2 <= -a: print("FIRST") print(x2) else: print("DRAW") else: ...
Maxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i. Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j. Games in the shop are ordered from left to right, Maxim tries to buy every game i...
3
m,n=map(int,input().split()) l=list(map(int,input().split())) a=list(map(int,input().split())) c=0 j=0 for i in l: if(a[j]>=i): c+=1 j+=1 if(j==n): break print(c)
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=list(map(int,input().split())) t=max(a) u=min(a) b=[] for i in range(u,t+1): o=abs(a[0]-i)+abs(a[1]-i)+abs(a[2]-i) b.append(o) print(min(b))
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale. Maxim often visits h...
3
def list_input(): return list(map(int,input().split())) def map_input(): return map(int,input().split()) def map_string(): return input().split() n,k = map_input() a = -1 b = -1 if k == 0 or k == n: a = 0 b = 0 else: a = 1 b = n-k b = min(b,k*2) print(a,b)
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≤ d_i ≤ 9 for all i and d_1 + d_2 + … + d_k = n. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d...
3
TN = 1 def solution(): n = int(input()) print(n) print("1 "*n) while TN != 0: solution() TN -= 1
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co...
3
"""/* Akash Mandal Jalpaiguri Government Engineering College keep trying::don't quit Akash9380 && codeA10 */""" def sii(): return input() def lmii(): return list(map(int, input().split())) n=sii();r=int(n,2) for i in range(10...
Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya. Filya works a lot and he plans to visit ...
3
import sys, math l1, r1, l2, r2, k = map(int,input().split()) a = max(l1, l2) b = min(r1, r2) ans = b - a + 1 if a <= k <= b: ans -= 1 print(max(0, ans))
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
n,k=map(int,input().split()) l=[int(x) for x in input().split()] w=0 for i in l: if i>k: w+=2 else: w+=1 print(w)
The only difference between easy and hard versions is the maximum value of n. You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n. The positive integer is called good if it can be represented as a sum of distinct powers of 3 (...
3
import math from sys import stdin input=stdin.readline for _ in range(int(input())): n=int(input()) p=n while True: p=n ok=True while p>0 and ok: if ok and p%3==2: ok=False ...
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning: a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twi...
3
n = int(input()) a = input().split(' ') pre = int(a[0]) pos = n for i in range(1,n): x = int(a[i]) if x<pre: pre = x pos = i break pre = x if pos==n: print(0) else: ans = 0 for j in range(pos,n): x = int(a[j]) if x<pre: ans = -1 bre...
There is a box containing N balls. The i-th ball has the integer A_i written on it. Snuke can perform the following operation any number of times: * Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written....
3
import math def gcd(a, b): while b: a, b = b, a % b return a n,k = map(int,input().split()) a = list(map(int,input().split())) b = a[0] for i in a: b = gcd(b,i) if k > max(a) or k%b != 0: print('IMPOSSIBLE') else: print('POSSIBLE')
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
N = int(input()) l = [] for i in range(N): a, b, c = map(int, input().split()) sum = a + b + c d = sum // 2 l.append(d) for i in range(N): print(l[i])
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it...
1
n = input() a = raw_input() for i in xrange(2): a = "1 1 1".join(a.split("1 0 1")) print a.count("1")
You have written N problems to hold programming contests. The i-th problem will have a score of P_i points if used in a contest. With these problems, you would like to hold as many contests as possible under the following condition: * A contest has three problems. The first problem has a score not greater than A poin...
3
n= int(input()) a,b = map(int,input().split()) p = input().split() p =[int(p) for p in p] q1 = sum(x <= a for x in p) q2= sum((b >= x > a) for x in p) q3= sum(x > b for x in p) q =[q1,q2,q3] print(min(q))