problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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
import math n=input() if(n=='0'): print("0") else: n1=int(n,2) ans=(math.log(n1,4)) if int(ans)==ans: if 4**int(ans)<n1: print(int(ans)+1) else: print(int(ans)) else: print(math.ceil(ans))
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
z = [int(s) for s in input().split()] s = list(input()) k = 0 for j in range(z[1]): for i in range(z[0] - 1, 0, -1): if k == 1: k = 0 continue if s[i] == 'G' and s[i - 1] == 'B': s[i], s[i-1] = s[i-1], s[i] k += 1 print(''.join(s))
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains. Mountains are described by a sequence of heights...
3
t = int(input()) for i in range(t): n, k = map(int,input().split()) a = list(map(int,input().split())) cn = 0 for i in range(1, k - 1): cn += int(a[i]> a[i - 1] and a[i] > a[i + 1]) maxcn = cn maxl = 1 cn -= int(a[1]> a[0] and a[1] > a[2]) for i in range(k - 1, n - 1): cn...
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs). <image> Fig. 1 A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertic...
3
def set_pdt(i, p, d): u = tree[i] u[0], u[1] = p, d for c in u[3]: set_pdt(c, i, d+1) else: if u[0] == -1: u[2] = "root" elif u[3]: u[2] = "internal node" else: u[2] = "leaf" n = int(input()) tree = [[-1,0,0,0] for _ in range(n)] root ...
John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points. John Doe wondered, how many distinct ways to fill the table with points are there, provided that...
3
n,m,k=map(int,input().split()) M=int(1e9+7) N=n*n iv=[0]*(N+1) iv[1]=1 for i in range(2, N+1): iv[i]=M-M//i*iv[M%i]%M f1=[1]*(N+1) for i in range(1, N+1): f1[i]=f1[i-1]*i%M f2=[1]*(N+1) for i in range(1, N+1): f2[i]=f2[i-1]*iv[i]%M left=m%n #m/n+1, m/n def powM(b, p): r=1 while p>0: if p%2>...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- def main(): n,k = input().rstrip().split() n, k = int(n), int(k) A = [int(i) for i in input().rstrip().split()] min_score = 0 num_passed = 0 for i in range(n): if i+1 == k: min_score = A[i] for x in A: if x >= min_score and x > 0...
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones. Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a. You can apply the following operations any number of times: * Choose some substring of string a (for example, you can choose entire strin...
3
n, x, y = map(int, input().split()) s = input() nGroups = int(s[0] == '0') for i in range(1, n): if s[i - 1] != s[i] == '0': nGroups += 1 if nGroups == 0: print(0) else: print((nGroups - 1) * min(x, y) + y)
4 different points on the plane Read the coordinates of $ A (x_a, y_a) $, $ B (x_b, y_b) $, $ C (x_c, y_c) $, $ D (x_d, y_d) $ and read those 4 points Create a program that outputs YES if there is no dent in the quadrangle $ ABCD $ with the coordinates as the vertices, and NO if there is a dent. A quadrangle with a de...
3
import math while True: try: xa, ya, xb, yb, xc, yc, xd, yd = map(float, input().split(',')) except: break vecs = [(xb - xa, yb - ya), (xc - xb, yc - yb), (xd - xc, yd - yc), (xa - xd, ya - yd)] angles = [(math.atan2(*vecs[(i + 1) % 4][::-1]) - math.atan2(*vecs[i][::-1])) % (2 * math.pi)...
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him;...
3
from collections import Counter a=input() b=input() c=Counter(a) d=Counter(b) # print(c,d) for i in d.keys(): if i==" ": continue if i not in c.keys(): print("NO") exit() else: if d[i]>c[i]: print("NO") exit() print("YES")
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
3
n = int(input()) ar = list(map(int,input().split())) ar.sort() ans = 0 for i in ar: ans += abs(i - 1) if n == 1: print(ans) exit(0) if n == 2: print(abs(i - ar[0])) exit(0) if n >= 50: print(ans) exit(0) for i in range(2 , 100000): s = 0 ok = 1 for j in range(0 , n): ...
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be deri...
3
t=int(input()) for i in range(t): s=input() k=input() b=[] a=[] for j in s: b.append(j) for j in k: a.append(j) b1=[[] for j in range(26)] for j in range(len(b)): b1[ord(b[j])-97].append(j) dp=[[-1]*(26) for j in range(len(b)+1)] for j in range(26): ...
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th...
3
b=[0]*101 for k in range(3,101): i=0 while (k-3*i)>=0: if (k-3*i)%7==0: b[k]+=1 break else: i+=1 t=int(input()) for i in range(t): if b[int(input())]==1: print('YES') else: print('NO')
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ...
3
n, m = [int(v) for v in input().split()] ip2name = {} for _ in range(n): name, ip = input().split() ip2name[ip] = name for _ in range(m): cmd, ip = input().split() assert ip[-1] == ';' ip = ip[:-1] print('%s %s; #%s' % (cmd, ip, ip2name[ip]))
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
t = int(input()) res = [] for i in range(t): b = input() j = 1 a = b[0] while True: if j + 1 < len(b): a = a + b[j] j += 2 else: a = a + b[j] break res.append(a) print("\n".join(res))
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
stra = input(); try: indexa = stra.index('h'); stra = stra[indexa + 1:len(stra)]; indexa = stra.index('e'); stra = stra[indexa + 1:len(stra)]; indexa = stra.index('l'); stra = stra[indexa + 1:len(stra)]; indexa = stra.index('l'); stra = stra[indexa + 1:len(stra)]; indexa = stra.index...
Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j. Constraints * 1 \leq N \leq 2 \times 10^5 * P_1, \ldots, P_N is a permutation of 1, \ldots, N. * All values in input are ...
3
n = int(input()) p = list(map(int, input().split())) x = 2*(10**5)+1 c = 0 for i in p: if i < x: x = i c += 1 print (c)
How many ways are there to choose two distinct positive integers totaling N, disregarding the order? Constraints * 1 \leq N \leq 10^6 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 4 Output 1 Input 999999 Output 499999
3
N=int(input()) cnt=0 X=N/2 while X>1: X=X-1 cnt=cnt+1 print(cnt)
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing n...
3
n = int(input()) a = sorted(map(int, input().split())) print(' '.join(map(str, a[1::2] + a[::2][::-1])))
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints. Consider...
3
number_of_segment_and_upper=input().split() number_of_segment=int(number_of_segment_and_upper[0]) upper=int(number_of_segment_and_upper[1]) segments=list() i=0 while i<number_of_segment: l_and_r=input().split() l=int(l_and_r[0]) r=int(l_and_r[1]) segments.append(l) segments.append(r) i+=1 d=list...
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
1
def main(): n=map(long,raw_input().strip().split())[0] flowers=map(int,raw_input().strip().split()) flowers.sort() maxdif=flowers[n-1]-flowers[0] num_min=0 num_max=0 if maxdif==0: print 0,(n*(n-1)/2) return for item in flowers: if flowers[0]==item: num_min+=1 elif flowers[n-1]==item: num_max...
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
1
'''input AAA ''' vowels = 'AEIOUY' last = 0 res = 0 s = 'X' + raw_input() + 'A' for i in xrange(len(s)): ch = s[i] if ch in vowels: res = max(res, i - last) last = i print res
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
def check(n, coin): count = 0 if n>=coin: count = n // coin n = n - coin*count return(n,count) n = int(input()) n, ans1 = check(n,100) ans = 0 ans += ans1 n, ans1 = check(n,20) ans += ans1 n, ans1 = check(n,10) ans += ans1 n, ans1 = check(n,5) ans += ans1 n, ans1 = check(n,1) ans += a...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input()) for i in range(n): p = input() if len(p) > 10: print(p[0] + str(len(p) - 2) + p[-1]) else: print(p)
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
for t in range(int(input())): n = int(input()) if n%3 != 0 and n!= 1: print(-1) else: a = 0 b = 0 while n%3 == 0: a += 1 n = n//3 while n%2 == 0: b+=1 n=n//2 if b > a or n!=1: print(...
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as foll...
3
t=int(input()) def solve(d,m): ans=1 for i in range(30): if d < (1 << i): break ans = ans *( min((1<<(i+1)) - 1,d) - (1 << i) + 2) % m; ans-=1; if ans < 0: ans+=m; return ans while t: t-=1 d,m=[int(c) for c in input().split()] print(solv...
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties... Most of the young explorer...
3
############ ---- Input Functions ---- ############ import sys t = int(input()) for i in range(t): n = int(input()) arr = sorted(list(map(int, sys.stdin.readline().strip().split(' ')))) ans = 0 last_grp_count = 0 for e in arr: if last_grp_count + 1 == e: ans += 1 las...
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times: * Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y. Your task is to fi...
3
from math import * t=int(input()) for _ in range(t): a,b,x,y,n=map(int,input().split()) r=n k=max(y,(b-r)) r=r-b+k m=max(x,(a-r)) ans=k*m c=max(x,(a-n)) n=n-a+c d=max(y,(b-n)) s=c*d ans=min(ans,s) print(ans)
Niwango created a playlist of N songs. The title and the duration of the i-th song are s_i and t_i seconds, respectively. It is guaranteed that s_1,\ldots,s_N are all distinct. Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, w...
3
n=int(input()) a=[list(input().split()) for _ in range(n)] x=input() s=0 for i in range(n): if a[i][0]==x: p=i break for i in range(p+1,n): s+=int(a[i][1]) print(s)
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
def howabido(l): a=l[0] for i in l: if i!=a: return False return True def lekbir(l,n): m=max(l) if l[0]>l[1] and l[0]==m: return 1 for i in range(1,n-1): if l[i]==m and (l[i]>l[i-1] or l[i]>l[i+1]): return i+1 if l[n-1]>l[n-2] and l[n-1]==m: ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input()) for i in range (n): s=input() if len(s)<11: print(s) else: m=len(s)-1 print("{}{}{}".format(s[0],len(s)-2,s[m]))
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: * Include a perso...
3
import re from collections import Counter class Task: commands = [] answer = 0 def getData(self): while True: try: str = input() except EOFError: break self.commands += [str] def solve(self): peopleCount = 0 for current in self.commands: if current[0] == '+': peopleCount += 1 e...
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ...
3
#!/bin/python3 import sys n = int(input()) a = list(map(int, input().split())) a = sorted(a) for i in range(0,n-2): if a[i] + a[i + 1] > a[i+2]: print("YES") sys.exit() print("NO")
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
from sys import stdin def main(): l = stdin.read().splitlines()[2::2] for i, s in enumerate(l): *aa, a = map(int, s.split()) while aa and aa[-1] >= a: a = aa.pop() while aa and aa[-1] <= a: a = aa.pop() l[i] = str(len(aa)) print('\n'.join(l)) if __...
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
3
def codeforces(text): string = 'Bulbasaur' needed = {} for letter in string: if letter in needed: needed[letter] += 1 else: needed[letter] = 1 counts = [] for char in set(string): counts.append(text.count(char) // needed[char]) return min(counts) ...
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty. For example: * by applying a move to the string "where", the result is the s...
3
s=input() n=input() a=len(s) b=len(n) x=0 for i in range (min(a,b)): if s[a-1-i]!=n[b-1-i] : break x+=1 print (a-x+b-x)
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
3
''' a = numpy.zeros(2,dtype=bool) ~[F,F] = [T,T] ''' for _ in range(int(input())): a,b,n,m = map(int,input().split()) if m<=min(a,b) and n+m <= a+b: print('Yes') else: print('No')
There are n Christmas trees on an infinite number line. The i-th tree grows at the position x_i. All x_i are guaranteed to be distinct. Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything. There are m people who want t...
1
def cal_len(seg): result = 0 for s in seg: result = result + (s[1] - s[0] + 1 - s[2]) return result def solve(max_dis): d = max_dis - 1 seg = [[g_x[0] - d, g_x[0] + d, 0]] tot = 0 for x in g_x: if seg[-1][1] >= x - d: seg[-1][1] = x + d seg[-1][2] = ...
You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a w...
3
import sys input=sys.stdin.readline def read_list(): return map(int,input().split()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs from collections import deque as dq from collections import defaultdict as dc # import math # f = open('test.py') # def input(): # return f....
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine th...
3
#!/usr/bin/python3 import math import sys DEBUG = False def inp(): return sys.stdin.readline().rstrip() def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) INF = 70 def solve(N, A): B = [set() for _ in range(63)] for i, a in enumerate(A): if a == 0...
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
3
################### <---------------------- QuickSilver_ ---------------------> #################### n,m=[int(i) for i in input().split()] if n<m: print(-1) else: tot=(n+1)//2 if tot%m==0: print(tot) else: print(tot+m-tot%m)
You are given an array a consisting of n integers. Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ...
3
import math # function to count the divisors def countDivisors(n) : cnt = 0 for i in range(1, (int)(math.sqrt(n)) + 1) : if (n % i == 0) : # If divisors are equal, # count only one if (n / i == i) : cnt = cnt + 1 e...
Digory Kirke and Polly Plummer are two kids living next door to each other. The attics of the two houses are connected to each other through a passage. Digory's Uncle Andrew has been secretly doing strange things in the attic of his house, and he always ensures that the room is locked. Being curious, Digory suspects th...
1
cases = int(raw_input()) for i in xrange(cases): jump = 1 days = 0 inp = raw_input().split("#") for j in inp: if len(j)+1>jump: days+=1 jump = len(j)+1 print days
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
3
n,k=map(int,input().split()) a=[int(i) for i in input().split()] mx=100000 for i in a: if k%i==0: mx=min(mx,k//i) print(mx)
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
X = input() x = [] for i in X: x.append(i) l1 = x[0] x[0] = l1.upper() ans = ''.join(x) print(ans)
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative. Yasser, ...
3
import math num_tests = int(input()) out = [] for _ in range(num_tests): cup_cnt = int(input()) cups = list(map(int, input().split(' '))) cups_sum = sum(cups) min_sum, curr_sum = math.inf, 0 is_happy = 'YES' for idx in range(len(cups)): curr_sum += cups[idx] if ((idx < len(cups...
You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root v...
3
#import sys #input = lambda: sys.stdin.readline().rstrip() from collections import deque T = int(input()) for _ in range(T): N = int(input()) X = [[] for i in range(N)] pp = [int(a)-1 for a in input().split()] for i, p in enumerate(pp, 1): X[i].append(p) X[p].append(i) P = [-1] * N...
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
1
p=int(raw_input('')) d=[] count=0 ct=0 d=[int(x) for x in raw_input().split()] for i in range(p): count+=d[i] d.sort() d.reverse() for i in range(p): ct+=d[i] if ct>count/2 : print i+1 break
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
from sys import stdin def main(): #入力 readline=stdin.readline t=int(readline()) res=[] for i in range(t): n=int(readline()) a=list(map(int,readline().split())) for j in range(n): if j==0: m=a[j]%2 else: if a[j]%2!=m: ...
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
t=int(input()) for _ in range(t): x1,y1,z1=map(int,input().split()) x2,y2,z2=map(int, input().split()) ans=min(z1,y2) y2-=ans;z1-=ans ans*=2 if z2<=x1+z1: print(ans) else: print(ans-(z2-x1-z1)*2)
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
3
n = list(map(int, input().split())) if n[2] < n[1] : print (n[2]) elif n[2] >= n[1] and n[2] <= n[0]: print(n[1]) else: print((n[0] + n[1]) - n[2])
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
3
n = int(input()) A = list(map(int, input().split())) odd = [] eve = [] for i in A : if i % 2 : odd.append(i) else : eve.append(i) odd.sort() eve.sort() while len(odd) and len(eve) : odd.pop() eve.pop() if len(odd) : odd.pop() if len(eve) : eve.pop() print(sum(odd)+sum(eve));
We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it. Print all strings that are written on the most number of votes, in lexicographical order. Constraints * 1 \leq N \leq 2 \times 10^5 * S_i (1 \leq i \leq N) are strings consisting of lowercase English letters. * The length of S...
3
from collections import Counter n = int(input()) s = Counter([input() for _ in range(n)]) mx = max(s.values()) for k in sorted(x for x,y in s.items() if y == mx) : print(k)
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I...
3
def partition(A, p, r): x = A[r] i = p - 1 for j in range(p, r): if A[j] <= x: i += 1 A[i], A[j] = A[j], A[i] A[i+1], A[r] = A[r], A[i+1] return i+1 n = int(input()) A = list(map(int, input().split())) p = partition(A, 0, n-1) first = ' '.join(str(a) for a in A[0...
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are n doors, the i-th door initially has durability equal to a_i. During your move you can try to br...
3
import math n, x, y = map(int, input().split()) a = list(map(int, input().split())) ans = 0 if x > y: ans = n else: k = 0 for i in range(n): if a[i] <= x: k += 1 ans = math.ceil(k / 2) print(ans)
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes. A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe...
3
import math k,n,s,p=map(int,input().split()) print(math.ceil(((math.ceil(n/s))*k)/p))
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
1
# -*- coding: utf-8 -*- k = input() l = input() ok = 0 for i in xrange(1, 32): if k ** i == l: ok = 1 print 'YES' print i-1 if not ok: print 'NO'
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c...
3
t = int(input()) ans = [] for i in range(t): a = input() a = [i for i in a] ans.append(0) w = ['a','b','c'] for j in range(len(a) - 1): if a[j] == a[j + 1] and a[j] != '?': ans[i] = -1 break if a[j] == '?' and ((j == 0) or (j == len(a) - 1)): if j ...
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go. Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of ...
3
n,x=[int(i) for i in input().split()] l=[int(i) for i in input().split()] l.sort() def f(x): i=0 while i in x: i+=1 return i c=0 while f(l)!=x: if f(l)>x: c+=1 break for i in range(f(l),x): if i not in l: c+=1 l.append(i) l.sort() ...
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
n = int(input()) flag= 0 res = [] for _ in range(n): s = list(input()) hallway = s.index('|') if len(set(s[0:hallway])) == 1 and flag == 0 and s[0] == 'O': s[0] = '+' s[1] = '+' flag= 1 elif len(set(s[hallway+1::])) == 1 and flag == 0 and s[3] == 'O': s[3] = '+' s...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
n=int(input()) faces=0 for i in range(n): s=input() if s=="Tetrahedron": faces=faces+4 if s=="Cube": faces=faces+6 if s=="Octahedron": faces=faces+8 if s=="Dodecahedron": faces=faces+12 if s=="Icosahedron": faces=faces+20 print(faces)
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
s = map(int, input().split()) s = list(s) x = 0 for i in s: if s.count(i) > 1: x = x + (s.count(i) - 1) while i in s: s.remove(i) print(x)
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();game=input();a=game.count('A');d=game.count('D') if(a>d):print("Anton") elif(a<d):print("Danik") else:print("Friendship")
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
3
n,k = map(int,input().split()) contor = 0 for i in range(1,n+1): if (k%i==0)and(k//i<=n): contor+=1 print(contor)
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
t=int(input()) for _ in range(t): n=int(input()) d=dict() l=list(map(int,input().split())) for i in l: if i in d: d[i]+=1 else: d[i]=1 dis=0 sam=0 c=0 for i in d.keys(): if d[i]>sam: sam=d[i] dis+=1 else: ...
You are given an array a consisting of n positive integers. Initially, you have an integer x = 0. During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1). ...
3
from sys import stdin, stdout from sys import maxsize #input = stdin.readline().strip def solve(): pass test = 1 test = int(input()) for t in range(0, test): # brr = [list(map(int,input().split())) for i in range(rows)] # 2D array row-wise input # n = int(input()) # s = list(input()) ...
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of...
3
#------------------------------what is this I don't know....just makes my mess faster-------------------------------------- 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....
You are given a sequence with N integers: A = \\{ A_1, A_2, \cdots, A_N \\}. For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied: * If A_i and A_j (i < j) are painted with the same color, A_i < A_j. Find the minimum number of col...
3
from bisect import bisect_left, bisect_right n = int(input()) INF = 1010101010 dp = [INF] * n a = [int(input()) for _ in range(n)] a.reverse() for i in a: dp[bisect_right(dp, i)] = i print(bisect_left(dp, INF))
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including t...
3
h,w = map(int,input().split()) cnt = 0 for i in range(h): A = list(input()) cnt += A.count('#') if cnt == h+w-1: print("Possible") else: print("Impossible")
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1...
3
from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,input().spl...
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
3
if __name__ == "__main__": T = int(input()) for i in range(T): n, m = map(int, input().split()) if (n == 1 or m == 1) or (n == 2 and m == 2): print("YES") else: print("NO")
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future. On ...
1
data = raw_input().split() n = int(data[0]) w = int(data[1]) b = int(data[2]) min_cost = min(w,b) data = raw_input().split() dancers = [int(x) for x in data] cost = 0 while(dancers): if len(dancers) == 1: if dancers[0] == 2: cost += min_cost else: break else: ...
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so. Input The first line of the input contains a single integer t (1≤ t ≤...
3
t = int(input()) results = [] for case in range(t): n, x = map(int, input().split()) a = list(map(int, input().split())) odd = 0 even = 0 for i in a: odd += int(i % 2 == 1) even += int(i % 2 == 0) ans = 'No' if (odd == n): if (x % 2): ans = 'Yes' ...
Given is a string S. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different. Cons...
3
S = list(input()) K = int(input()) if len(set(S)) == 1: print((len(S)*K)//2) exit() def n_change(sss): s = sss.copy() x = 0 for i in range(1,len(s)): if s[i] == s[i-1]: s[i] = "X" x += 1 return x print(n_change(S) + (K-1) * (n_change(2*S) - n_change(S)))
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
liste = [] for i in range(5): temp = input() liste.append(temp) for i in range(len(liste)): if '1' in liste[i]: row = i+1 break columns = liste[row-1].split(" ") for i in range(len(columns)): if '1' == columns[i]: column = i+1 break value = abs(row-3) + abs(column-3...
Snuke has N hats. The i-th hat has an integer a_i written on it. There are N camels standing in a circle. Snuke will put one of his hats on each of these camels. If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No...
3
N = int(input()) A = list(map(int, input().split())) b = 0 for i in range(N): b ^= A[i] print("Yes" if b == 0 else "No")
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
a=int(input()) if a<=5: print(1) else: if a%5>0: print(a//5+1) else: print(a//5)
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
3
n , a, b = map(int,input().split()) cnt = 0 for i in range(1, n+1) : if (i-1) >= a and (n-i) <= b: cnt += 1 print(cnt)
There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 ...
3
from heapq import heappush, heappop import sys input = sys.stdin.buffer.readline N, Q = map(int, input().split()) E = [] for i in range(N): s, t, x = map(int, input().split()) E.append((0, t - x, x, i)) E.append((1, s - x, x, i)) D = [int(input()) for _ in range(Q)] E.sort(key=lambda a: a[1], reverse=Tr...
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2). You want to construct the array a of length n such that: * The first n/2 elements of a are even (divisible by 2); * the second n/2 elements of a are odd (not divisible by 2); * all elements of a are distinct and positi...
3
t = int(input()) for _ in range(t): n = int(input()) if n % 4 != 0: print('NO') else: ans = [] for i in range(1, n // 2 + 1): ans.append(2 * i) for i in range(n // 2 - 1): ans.append(1 + 2 * i) ans.append(3 * n // 2 - 1) print('YES') ...
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
3
n=int(input()) for i in range(n): l=int(input()) s=input() if len(s) == l: rs=s.find("8") try: if rs != -1: if s[rs+10] != "": print("YES") else: print("NO") except: print("NO")
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers: In the decimal representation of s: * s > 0, * s consists of n digits, * no digit in s equals 0, * s is not divisible by any of it's digits. Input The input consists of mult...
3
ts = int(input()) for t in range(ts): n = int(input()) if n == 1: print(-1) else: print('2', end = '') for i in range(n-1): print('3', end = '') print()
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
3
n,m = map(int,input().split()) ikn = list(map(int,input().split())) stp = list(map(int,input().split())) code = [] for i in range(n): if ikn[i] in stp: code.append(ikn[i]) for i in range(len(code)): print(code[i],end=' ')
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'...
3
from math import gcd, ceil from collections import defaultdict, deque from sys import stdin,stdout from bisect import bisect_left, bisect_right from copy import deepcopy inp=lambda : int(stdin.readline()) sip=lambda : stdin.readline() mulip =lambda : map(int, stdin.readline().split()) lst=lambda : list(map(int,stdin...
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times: * Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y. Your task is to fi...
3
import math for _ in range(int(input())): a, b, x, y, n = map(int, input().split()) a1 = a b1 = b n1 = n # temp = 0 # if a > b: # temp = a # a = b # b = temp # temp = x # x = y # y = temp if a-x >= n: a = a-n # print(a * b) ...
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode o...
3
def factorial(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result p=10**9+7 n,m,pos=map(int,input().split()) lesser=m-1 greater=n-m l=0 h=n ans=1 while(l<h): m=(l+h)//2 if pos<m: ans=(ans*greater) ans...
Not so long ago as a result of combat operations the main Berland place of interest — the magic clock — was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin correspond...
3
from math import sqrt,ceil x,y=map(int,input().split()) if x==0 or y==0: print("black") else: if ( x>0 and y>0 ) or ( x<0 and y<0 ) : d = sqrt( (x**2) + (y**2) ) if int(d)==ceil(d): print('black') else: if int(d)%2==0: print("black") else: print("white") elif ( x<0 and y>0 ) or ( x>0 and y<0 ...
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it. They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card. Let th...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- N = int(raw_input()) a = map(int, raw_input().split()) '''math total=x+y y=total-x x-y=x-(total-x) =2x-total |x-y|=|2x-total| ''' total = sum(a) x = a[0] answer = abs(x*2-total) for i in range(1,N-1): x += a[i] answer = min(answer, abs(x*2-total)) print answe...
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...
3
n,m = map(int,input().split()) a=[int(i) for i in input().split()] c=a[0]-1 for i in range(1,len(a)): if a[i-1]>a[i]: c+=a[i]+n-a[i-1] else: c+=a[i]-a[i-1] print(c)
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the...
3
n = int(input()) a = list(map(int, input().split())) for i in a: print(sorted(a)[::-1].index(i)+1, end = ' ')
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar...
3
t=int(input()) for _ in range(t): n=int(input()) s=int(input()) r=0 l=[] f=0 while (s%2==0) and s>0: s=s-s%10 s=s//10 while s>0: k=s%10 l.append(k) r=r+k if r%2==0: f=1 break s=s//10 p=len(l) if f==1: ...
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times: * Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y. Your task is to fi...
3
g = int(input()) for t in range(g): a,b,x,y,n = map(int,input().split()) isALower = False if max(a-n,x) < max(b-n, y): isALower = True if isALower: remainder = 0 if x > a - n: remainder = n - (a -x) a = x b = b - remainder if b <...
You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string. In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet f...
3
n=int(input()) s=(str(input())) s=list("$"+s+"$") char=[] for i in s: char.append(ord(i)) removable=[] z=len(char) for i in range(1,n+1): # print(i) if char[i]==char[i-1]+1 or char[i]==char[i+1]+1: removable.append((char[i],i)) while len(removable)>0: removable.sort() char.pop(removable[-1][...
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it. They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card. Let th...
3
N = int(input()) a = list(map(int,input().split())) total = sum(a) ans = float('inf') x = 0 for i in range(N-1): x += a[i] ans = min(abs(total-2*x),ans) print (ans)
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
3
cases = int(input()) while cases > 0: l = int(input()) num = input() if l == 1: if int(num) % 2 == 0: print(2) else: print(1) elif l % 2 == 1: for d in range(0, len(num), 2): if int(num[d]) % 2 == 1: print(1) ...
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the...
3
n = int(input()) c = 0 for i in range(n): c += 1 s, d = map(int, input().split()) c = c + (s-c) % d c = max(s, c) print(c)
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ...
1
#!usr/bin/env python2.7 def bin_pow(a, n): res = 1.0 while(n > 0): if((n & 1) == 1): res *= a a *= a n >>= 1 return res m, n = map(int, raw_input().split()) ans = 0 for i in range(1, m + 1): ans += i * (bin_pow(1.0 * i / m, n) - bin_pow((i - 1.0) / m, n)) print ans
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
3
n = input() n, m, k = map(int, n.split(' ')) if m >= n and k >= n: print("YES") else: print("NO")
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
3
test=int(input()) for i in range(test): [s,k]=list(map(int,input().split())) arr=list(map(int,input().split())) brr=list(map(int,input().split())) has=[0]*(s+1) ans=[] for j in range(k): has[brr[j]]=1 for j in range(1,s+1): if has[j]==0: ans.append(j) res=[] ...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
import math for i in range(int(input())): z = int(input()) print(math.ceil(z/2))
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland. There are n candidates, including Limak. We know how many citizens are going to vote for each candidate. Now i-th candidate would get ai votes. Limak is candidate number 1. To win in elections, he...
3
n = int(input()) c = [] values = list(map(int,(input().split()))) t = values[0] for i in range(n - 1): c.append(values[i+1]) c.sort(reverse=True) ans = 0 while True: if t > c[0] : break; t += 1 c[0] -= 1 ans += 1 c.sort(reverse=True) print(ans)