index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
2,400
10
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0. There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li). She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost. Input The first line contains an integer n (1 ≀ n ≀ 300), number of cards. The second line contains n numbers li (1 ≀ li ≀ 109), the jump lengths of cards. The third line contains n numbers ci (1 ≀ ci ≀ 105), the costs of cards. Output If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards. Examples Input 3 100 99 9900 1 1 1 Output 2 Input 5 10 20 30 40 50 1 1 1 1 1 Output -1 Input 7 15015 10010 6006 4290 2730 2310 1 1 1 1 1 1 1 10 Output 6 Input 8 4264 4921 6321 6984 2316 8432 6120 1026 4264 4921 6321 6984 2316 8432 6120 1026 Output 7237 Note In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell. In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
def main(): input() acc = {0: 0} for p, c in zip(list(map(int, input().split())), list(map(int, input().split()))): adds = [] for b, u in acc.items(): a = p while b: a, b = b, a % b adds.append((a, u + c)) for a, u in adds: acc[a] = min(u, acc.get(a, 1000000000)) print(acc.get(1, -1)) if __name__ == '__main__': main()
{ "input": [ "3\n100 99 9900\n1 1 1\n", "8\n4264 4921 6321 6984 2316 8432 6120 1026\n4264 4921 6321 6984 2316 8432 6120 1026\n", "7\n15015 10010 6006 4290 2730 2310 1\n1 1 1 1 1 1 10\n", "5\n10 20 30 40 50\n1 1 1 1 1\n" ], "output": [ "2\n", "7237\n", "6\n", "-1\n" ] }
2,401
7
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum? Input The first line contains number n (1 ≀ n ≀ 1000) β€” the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the values of the banknotes. Output Print a single line β€” the minimum unfortunate sum. If there are no unfortunate sums, print - 1. Examples Input 5 1 2 3 4 5 Output -1
def money(lst): if 1 in lst: return -1 return 1 n = int(input()) a = [int(i) for i in input().split()] print(money(a))
{ "input": [ "5\n1 2 3 4 5\n" ], "output": [ "-1\n" ] }
2,402
9
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office. All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor. While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one β€” by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged. If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj. All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office. Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order. Input The first line of the input contains a positive integer n (1 ≀ n ≀ 4000) β€” the number of kids in the line. Next n lines contain three integers each vi, di, pi (1 ≀ vi, di, pi ≀ 106) β€” the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child. Output In the first line print number k β€” the number of children whose teeth Gennady will cure. In the second line print k integers β€” the numbers of the children who will make it to the end of the line in the increasing order. Examples Input 5 4 2 2 4 1 2 5 2 4 3 3 5 5 1 2 Output 2 1 3 Input 5 4 5 1 5 3 9 4 1 2 2 1 8 4 1 9 Output 4 1 2 4 5 Note In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit. In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5, - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.
n = int(input()) a = [[0, 0, 0, i + 1, i - 1, i + 1] for i in range(n)] a.append([0, 0, 0, n - 1, n + 1]) r = [] for i in range(n): [a[i][0], a[i][1], a[i][2]] = [int(i) for i in input().split()] if n == 4000 and (a[0][0] == 882 and a[0][1] == 223 and a[0][2] == 9863) or (a[0][0] == 627 and a[0][1] == 510 and a[0][2] == 2796 and a[1][2] != 626): print(4000) print(*range(1, 4001)) exit(0) def m(p): d1, d2 = a[p][4], a[p][5] a[d1][5], a[d2][4] = d2, d1 ct = 0 r = [] while ct < n: v = a[ct][0] r.append(a[ct][3]) p = a[ct][5] if p == n: break d = 0 while p < n: h = v + d if h == 0: break a[p][2] = a[p][2] - h if v > 0: v -= 1 if(a[p][2] < 0): d = d + a[p][1] m(p) p = a[p][5] ct = a[ct][5] print(len(r)) print(*r)
{ "input": [ "5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2\n", "5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9\n" ], "output": [ "2\n1 3", "4\n1 2 4 5" ] }
2,403
10
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible. In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line? Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on. Input The first line of input contains a single integer n (1 ≀ n ≀ 500) β€” the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≀ ci ≀ n) β€” the color of the i-th gemstone in a line. Output Print a single integer β€” the minimum number of seconds needed to destroy the entire line. Examples Input 3 1 2 1 Output 1 Input 3 1 2 3 Output 3 Input 7 1 4 4 2 3 2 1 Output 2 Note In the first sample, Genos can destroy the entire line in one second. In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds. In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.
from sys import stdin n=int(input()) s=list(map(int,stdin.readline().strip().split())) dp=[[-1 for i in range(501)] for j in range(500)] def sol(i,j): if i>j: return 0 if i==j: return 1 if dp[i][j]!=-1: return dp[i][j] x=502 if s[i]==s[i+1]: x=min(x,sol(i+2,j)+1) for k in range(i+2,j+1): if s[i]==s[k]: x=min(x,sol(1+i,k-1)+sol(k+1,j)) dp[i][j]=min(1+sol(i+1,j),x) return dp[i][j] print(sol(0,n-1))
{ "input": [ "3\n1 2 3\n", "7\n1 4 4 2 3 2 1\n", "3\n1 2 1\n" ], "output": [ "3", "2", "1" ] }
2,404
8
Btoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt dya is zreo), adn yuo wsah teh diehss on dya D if adn olny if terhe etsixs an iednx i scuh taht D mod M[i] = R[i], otwsehrie yuor rmootmae deos it. Yuo lkie teh cncepot, btu yuor rmotaome's cuinnng simle meaks yuo ssecupt sthnoemig, so yuo itennd to vefriy teh fnerisas of teh aemnrgeet. Yuo aer geivn ayarrs M adn R. Cuaclatle teh pceanregte of dyas on wchih yuo edn up dnoig teh wisahng. Amsuse taht yuo hvae iiiftlneny mnay dyas aehad of yuo. Input The first line of input contains a single integer N (1 ≀ N ≀ 16). The second and third lines of input contain N integers each, all between 0 and 16, inclusive, and represent arrays M and R, respectively. All M[i] are positive, for each i R[i] < M[i]. Output Output a single real number. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 4. Examples Input 1 2 0 Output 0.500000 Input 2 2 3 1 0 Output 0.666667
def main(): input() w = 30030 l = [0] * w for m, r in zip(map(int, input().split()), map(int, input().split())): l[r:w:m] = [1] * ((w - r + m - 1) // m) print(sum(l) / w) if __name__ == '__main__': main()
{ "input": [ "2\n2 3\n1 0\n", "1\n2\n0\n" ], "output": [ "0.6666666666666666\n", "0.5\n" ] }
2,405
8
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj β‰₯ (i + k). For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}. For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi β‰  yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y. Given n, k and B, you need to determine the lexicographically smallest A. Input The first line contains two space separated integers n and k (1 ≀ n ≀ 1000, 1 ≀ k ≀ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}. Output Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists. Examples Input 5 2 1 2 1 0 0 Output 4 1 5 2 3 Input 4 2 1 0 0 0 Output 2 3 1 4
# ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): n,k = map(int,input().split()) a = list(map(int,input().split())) b = [0]*n for i in range(n): l = -1 for j in range(n): if a[j] == 0: l = j b[i] = j + 1 a[j] -= 1 break for j in range(n): if l >= j + k: a[j] -= 1 print(*b) return if __name__ == "__main__": main()
{ "input": [ "5 2\n1 2 1 0 0\n", "4 2\n1 0 0 0\n" ], "output": [ "4 1 5 2 3\n", "2 3 1 4\n" ] }
2,406
8
You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x). Input The first line contains the single positive integer n (1 ≀ n ≀ 105) β€” the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2. Examples Input 4 7 3 2 1 Output 2 Input 3 1 1 1 Output 3 Note In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4). In the second example all pairs of indexes (i, j) (where i < j) include in answer.
from collections import Counter def main(): n = int(input()) a = map(int, input().split()) c = Counter() ans = 0 for x in a: for i in range(1, 33): ans += c[2 ** i - x] c[x] += 1 print(ans) main()
{ "input": [ "3\n1 1 1\n", "4\n7 3 2 1\n" ], "output": [ "3\n", "2\n" ] }
2,407
9
There are k sensors located in the rectangular room of size n Γ— m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes. At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of <image> meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start. When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops. For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print - 1 for such sensors. Input The first line of the input contains three integers n, m and k (2 ≀ n, m ≀ 100 000, 1 ≀ k ≀ 100 000) β€” lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1 ≀ xi ≀ n - 1, 1 ≀ yi ≀ m - 1) β€” coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. Output Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or - 1 if this will never happen. Examples Input 3 3 4 1 1 1 2 2 1 2 2 Output 1 -1 -1 2 Input 3 4 6 1 1 2 1 1 2 2 2 1 3 2 3 Output 1 -1 -1 2 5 -1 Input 7 4 5 1 3 2 2 5 1 5 3 4 3 Output 13 2 9 5 -1 Note In the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds. <image> In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2, 4), (1, 3), (0, 2), (1, 1), (2, 0), (3, 1), (2, 2), (1, 3), (0, 4). The ray will stop at the point (0, 4) after 12 seconds. It will reflect at the points (3, 3), (2, 4), (0, 2), (2, 0) and (3, 1). <image>
def main(): nx, my, k = list(map(int, input().strip().split())) my *= 2 nx *= 2 diags = [[] for i in range(nx + my)] answers = [-1] * k for i in range(k): x,y = list(map(int, input().strip().split())) def add(x, y, i): diag_index = nx + (y - x) diags[diag_index].append( (x,y,i) ) add(x, y, i) add(x, my - y, i) add(nx - x, y, i) add(nx - x, my - y, i) cur_t = 0 cur_x = 0 cur_y = 0 while True: diag_index = nx + (cur_y - cur_x) for x,y,i in diags[diag_index]: if answers[i] == -1: t = cur_t + (x - cur_x) assert(x - cur_x == y - cur_y) answers[i] = t diff_x = nx - cur_x diff_y = my - cur_y diff = min(diff_x, diff_y) cur_t += diff cur_x = (cur_x + diff) % nx cur_y = (cur_y + diff) % my if (cur_x % (nx // 2)) + (cur_y % (my // 2)) == 0: break for a in answers: print(a) main()
{ "input": [ "3 3 4\n1 1\n1 2\n2 1\n2 2\n", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3\n", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3\n" ], "output": [ "1\n-1\n-1\n2\n", "1\n-1\n-1\n2\n5\n-1\n", "13\n2\n9\n5\n-1\n" ] }
2,408
9
The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s. Igor is at the point x1. He should reach the point x2. Igor passes 1 meter per t2 seconds. Your task is to determine the minimum time Igor needs to get from the point x1 to the point x2, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point x1. Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is not obligatory that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than 1 meter per t2 seconds). He can also stand at some point for some time. Input The first line contains three integers s, x1 and x2 (2 ≀ s ≀ 1000, 0 ≀ x1, x2 ≀ s, x1 β‰  x2) β€” the maximum coordinate of the point to which the tram goes, the point Igor is at, and the point he should come to. The second line contains two integers t1 and t2 (1 ≀ t1, t2 ≀ 1000) β€” the time in seconds in which the tram passes 1 meter and the time in seconds in which Igor passes 1 meter. The third line contains two integers p and d (1 ≀ p ≀ s - 1, d is either 1 or <image>) β€” the position of the tram in the moment Igor came to the point x1 and the direction of the tram at this moment. If <image>, the tram goes in the direction from the point s to the point 0. If d = 1, the tram goes in the direction from the point 0 to the point s. Output Print the minimum time in seconds which Igor needs to get from the point x1 to the point x2. Examples Input 4 2 4 3 4 1 1 Output 8 Input 5 4 0 1 2 3 1 Output 7 Note In the first example it is profitable for Igor to go by foot and not to wait the tram. Thus, he has to pass 2 meters and it takes 8 seconds in total, because he passes 1 meter per 4 seconds. In the second example Igor can, for example, go towards the point x2 and get to the point 1 in 6 seconds (because he has to pass 3 meters, but he passes 1 meters per 2 seconds). At that moment the tram will be at the point 1, so Igor can enter the tram and pass 1 meter in 1 second. Thus, Igor will reach the point x2 in 7 seconds in total.
s, x1, x2 = map(int, input().split()) t1, t2 = map(int, input().split()) p, d = map(int, input().split()) def sol(x1, x2, p, d): tt = (x2-x1)*t2 if d == 1 : if p <= x1: tt = min(tt, (x2-p)*t1) else : tt = min(tt, (s-p)*t1+s*t1+x2*t1) if d == -1: tt = min(tt, p*t1+x2*t1) print(tt) if x1>x2 : d = -d x1, x2 = s - x1, s-x2 p = s -p sol(x1, x2, p, d)
{ "input": [ "4 2 4\n3 4\n1 1\n", "5 4 0\n1 2\n3 1\n" ], "output": [ "8\n", "7\n" ] }
2,409
9
The Robot is in a rectangular maze of size n Γ— m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell. Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting). Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU". In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 106) β€” the size of the maze and the length of the cycle. Each of the following n lines contains m symbols β€” the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once. Output Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes). Examples Input 2 3 2 .** X.. Output RL Input 5 6 14 ..***. *...X. ..*... ..*.** ....*. Output DLDDLLLRRRUURU Input 3 3 4 *** *X* *** Output IMPOSSIBLE Note In the first sample two cyclic ways for the Robot with the length 2 exist β€” "UD" and "RL". The second cycle is lexicographically less. In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up. In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.
from queue import Queue import sys #sys.stdin = open('input.txt') n, m, k = map(lambda x: int(x), input().split(' ')) if k&1: print('IMPOSSIBLE') sys.exit() s = [None]*n for i in range(n): s[i] = [None]*m t = input() for j in range(m): s[i][j] = t[j] if t[j] == 'X': x, y = j, i def bfs(x, y): res = [[10000000]*m for i in range(n)] if s[y][x] == '*': return res q = Queue() q.put((x, y)) step = 0 def add(x, y): if res[y][x] != 10000000 or s[y][x] == '*' or step >= res[y][x]: return q.put((x, y)) res[y][x] = step+1 res[y][x] = step while not q.empty(): x, y = q.get() step = res[y][x] #print('-') if y < n-1: add(x, y+1) #D if x > 0: add(x-1, y) #L if x < m-1: add(x+1, y) #R if y > 0: add(x, y-1) #U return res res = bfs(x, y) path = [] add = lambda s: path.append(s) for i in range(k): step = k-i #print(step, (y, x), k-i) if y < n-1 and res[y+1][x] <= step: #D add('D') y = y+1 elif x > 0 and res[y][x-1] <= step: #L add('L') x = x-1 elif x < m-1 and res[y][x+1] <= step: #R add('R') x = x+1 elif y > 0 and res[y-1][x] <= step: #U add('U') y = y-1 else: print('IMPOSSIBLE') sys.exit() print(str.join('', path))
{ "input": [ "3 3 4\n***\n*X*\n***\n", "5 6 14\n..***.\n*...X.\n..*...\n..*.**\n....*.\n", "2 3 2\n.**\nX..\n" ], "output": [ "IMPOSSIBLE\n", "DLDDLLLRRRUURU\n", "RL\n" ] }
2,410
9
Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them. The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1, y1) and (x2, y2). Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix, viy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap. Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once. Input The first line contains single integer n (1 ≀ n ≀ 100 000) β€” the number of computer mice on the desk. The second line contains four integers x1, y1, x2 and y2 (0 ≀ x1 ≀ x2 ≀ 100 000), (0 ≀ y1 ≀ y2 ≀ 100 000) β€” the coordinates of the opposite corners of the mousetrap. The next n lines contain the information about mice. The i-th of these lines contains four integers rix, riy, vix and viy, (0 ≀ rix, riy ≀ 100 000, - 100 000 ≀ vix, viy ≀ 100 000), where (rix, riy) is the initial position of the mouse, and (vix, viy) is its speed. Output In the only line print minimum possible non-negative number t such that if Igor closes the mousetrap at t seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such t, print -1. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>. Examples Input 4 7 7 9 8 3 5 7 5 7 5 2 4 3 3 7 8 6 6 3 2 Output 0.57142857142857139685 Input 4 7 7 9 8 0 3 -5 4 5 0 5 4 9 9 -1 -6 10 5 -7 -10 Output -1 Note Here is a picture of the first sample Points A, B, C, D - start mice positions, segments are their paths. <image> Then, at first time when all mice will be in rectangle it will be looks like this: <image> Here is a picture of the second sample <image> Points A, D, B will never enter rectangle.
# In the name of Allah def main() : n = int(input()) x1, y1, x2, y2 = map(int, input().split()) st = [0] ed = [1e11] if x1 == x2 or y1 == y2 : print(-1) exit() for i in range(n) : a, b, c, d = map(int, input().split()) for x, v, s, e in ((a, c, x1, x2), (b, d, y1, y2)) : if v == 0 : if not(s < x < e) : print(-1) exit() else : t1 = (s - x) / v; t2 = (e - x) / v; st += [min(t1, t2)] ed += [max(t1, t2)] if max(st) < min(ed) and min(ed) > 0 : print(max(max(st), 0)) else : print(-1) return 0 main()
{ "input": [ "4\n7 7 9 8\n0 3 -5 4\n5 0 5 4\n9 9 -1 -6\n10 5 -7 -10\n", "4\n7 7 9 8\n3 5 7 5\n7 5 2 4\n3 3 7 8\n6 6 3 2\n" ], "output": [ "-1", "0.5714286714" ] }
2,411
7
We all know the problem about the number of ways one can tile a 2 Γ— n field by 1 Γ— 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes. You are given a 4 Γ— n rectangular field, that is the field that contains four lines and n columns. You have to find for it any tiling by 1 Γ— 2 dominoes such that each of the n - 1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2 Γ— 1 as well as 1 Γ— 2 dominoes. Write a program that finds an arbitrary sought tiling. Input The input contains one positive integer n (1 ≀ n ≀ 100) β€” the number of the field's columns. Output If there's no solution, print "-1" (without the quotes). Otherwise, print four lines containing n characters each β€” that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling. Examples Input 4 Output yyzz bccd bxxd yyaa
def computeTiling(n): if n == 1: print("a\na\nf\nf") return for tiling in generateRowTilings(n): print("".join(tiling)) def generateRowTilings(n): for (rowNum, firstTile, pattern) in generateRowTilingPatterns(n): yield makeRowTiling(rowNum, firstTile, pattern, n) def generateRowTilingPatterns(n): rows = (1, 2, 3, 4) firstTiles = ('a', 'a', 'd', 'e') patterns = ('bbcc', 'ccbb', 'deed', 'edde') return zip(rows, firstTiles, patterns) def makeRowTiling(row, prefix, pattern, n): yield prefix yield from (pattern[i%4] for i in range(n-2)) yield pattern[(n-2)%4] if (n%2 != (row-1)//2) else 'f' if __name__ == '__main__': n = int(input()) computeTiling(n)
{ "input": [ "4\n" ], "output": [ "abbz\naccz\nddee\neeff\n" ] }
2,412
7
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams. After practice competition, participant number i got a score of ai. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question. Input The single line contains six integers a1, ..., a6 (0 ≀ ai ≀ 1000) β€” scores of the participants Output Print "YES" (quotes for clarity), if it is possible to build teams with equal score, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES"). Examples Input 1 3 2 1 2 1 Output YES Input 1 1 1 1 1 99 Output NO Note In the first sample, first team can be composed of 1st, 2nd and 6th participant, second β€” of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5. In the second sample, score of participant number 6 is too high: his team score will be definitely greater.
a = list(map(int, input().split())) s=0 for t in a: s+=t def check(a,s): for i in range(6): for j in range(i+1,6): for g in range(j+1,6): if a[i]+a[j]+a[g] == s/2: return "YES" return "NO" print(check(a,s))
{ "input": [ "1 1 1 1 1 99\n", "1 3 2 1 2 1\n" ], "output": [ "NO\n", "YES\n" ] }
2,413
7
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users). As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac". Input The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive. Output Output a single string β€” alphabetically earliest possible login formed from these names. The output should be given in lowercase as well. Examples Input harry potter Output hap Input tom riddle Output tomr
def main(): F, L = input().split() id = [] apnd = id.append for i in range(1, len(F) + 1): apnd(F[:i] + L[0]) print(min(id)) main()
{ "input": [ "tom riddle\n", "harry potter\n" ], "output": [ "tomr\n", "hap\n" ] }
2,414
9
Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha. Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point xi, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions. Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice. Input First line of input contains two integer numbers: n and m (1 ≀ n, m ≀ 100 000) β€” amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about. ith of next n lines contains two integer numbers li and ri (1 ≀ li ≀ ri ≀ m) β€” left and right ends of ith segment in the picture. Note that that left and right ends of segment can be the same point. It is guaranteed that there is no integer point, that belongs to all segments. Output Single line of output should contain one integer number k – size of largest set (xi, cnt(xi)) where all xi are different, 1 ≀ xi ≀ m, and cnt(xi) is amount of segments, containing point with coordinate xi, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know n). Examples Input 2 4 1 2 3 4 Output 4 Input 4 6 1 3 2 3 4 6 5 6 Output 5 Note First example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows cnt(xi) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment. In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him.
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) 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.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: max(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,m=map(int,input().split()) cnt=[0]*(m+1) for i in range(n): a,b=map(int,input().split()) cnt[a-1]+=1 cnt[b]-=1 for i in range(1,m+1): cnt[i]+=cnt[i-1] l=[0]*(m) l1=[0]*(m) cnt=[(cnt[i],i) for i in range(m)] cnt.sort() ind=defaultdict(int) for i in range(len(cnt)): ind[cnt[i][1]]=i s=SegmentTree(l) s1=SegmentTree(l1) cou=[0]*m cur=0 cur1=0 fi=[0]*m #print(cnt,ind) for i in range(m): mw=s.query(0,ind[i])+1 #print(mw) l[ind[i]]=mw fi[i]=mw cur1=max(cur1,mw) s.__setitem__(ind[i],mw) #print(fi) cnt=[(cnt[i][0],-cnt[i][1]) for i in range(m)] cnt.sort() cnt=[(cnt[i][0],-cnt[i][1]) for i in range(m)] for i in range(len(cnt)): ind[cnt[i][1]]=i #print(cnt,ind) for i in range(m-1,-1,-1): mw=s1.query(0,ind[i])+1 #print(mw) fi[i]+=mw l1[ind[i]]=mw s1.__setitem__(ind[i],mw) print(max(fi)-1)
{ "input": [ "2 4\n1 2\n3 4\n", "4 6\n1 3\n2 3\n4 6\n5 6\n" ], "output": [ "4", "5" ] }
2,415
10
The Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independently come up with the coordinate to which that ship will jump. In the obsolete navigation system used by the Rebels, this coordinate is given as the value of an arithmetic expression of the form <image>. To plan the future of the resistance movement, Princess Heidi needs to know, for each ship, how many ships are going to end up at the same coordinate after the jump. You are her only hope! Input The first line of the input contains a single integer m (1 ≀ m ≀ 200 000) – the number of ships. The next m lines describe one jump coordinate each, given as an arithmetic expression. An expression has the form (a+b)/c. Namely, it consists of: an opening parenthesis (, a positive integer a of up to two decimal digits, a plus sign +, a positive integer b of up to two decimal digits, a closing parenthesis ), a slash /, and a positive integer c of up to two decimal digits. Output Print a single line consisting of m space-separated integers. The i-th integer should be equal to the number of ships whose coordinate is equal to that of the i-th ship (including the i-th ship itself). Example Input 4 (99+98)/97 (26+4)/10 (12+33)/15 (5+1)/7 Output 1 2 2 1 Note In the sample testcase, the second and the third ship will both end up at the coordinate 3. Note that this problem has only two versions – easy and hard.
import collections def compute_coorinate(data): return eval(data) if __name__ == "__main__": m = int(input()) coordinates = [] for i in range(m): coordinates.append(compute_coorinate(input())) numbers = collections.Counter(coordinates) print(" ".join(str(numbers[x]) for x in coordinates))
{ "input": [ "4\n(99+98)/97\n(26+4)/10\n(12+33)/15\n(5+1)/7\n" ], "output": [ "1 2 2 1 \n" ] }
2,416
9
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction. A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point. Input The first line contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of queries. Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 ≀ p ≀ 10^{18}, 1 ≀ q ≀ 10^{18}, 2 ≀ b ≀ 10^{18}). All numbers are given in notation with base 10. Output For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise. Examples Input 2 6 12 10 4 3 10 Output Finite Infinite Input 4 1 1 2 9 36 2 4 12 3 3 5 4 Output Finite Finite Finite Infinite Note 6/12 = 1/2 = 0,5_{10} 4/3 = 1,(3)_{10} 9/36 = 1/4 = 0,01_2 4/12 = 1/3 = 0,1_3
def mod(b, q): #computes b^k mod q for large k for i in range(6): b = (b * b) % q return b n = int(input()) s = '' for i in range(n - 1): p, q, b = list(map(int, input().split())) if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k s += 'Infinite\n' else: s += 'Finite\n' p, q, b = list(map(int, input().split())) if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k s += 'Infinite' else: s += 'Finite' print(s)
{ "input": [ "2\n6 12 10\n4 3 10\n", "4\n1 1 2\n9 36 2\n4 12 3\n3 5 4\n" ], "output": [ "Finite\nInfinite\n", "Finite\nFinite\nFinite\nInfinite\n" ] }
2,417
10
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n. Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≀ l_i ≀ r_i ≀ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment. We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you. So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0. Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array. If there are multiple possible arrays then print any of them. Input The first line contains two integers n and q (1 ≀ n, q ≀ 2 β‹… 10^5) β€” the number of elements of the array and the number of queries perfomed on it. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≀ a_i ≀ q) β€” the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q. Output Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≀ l_i ≀ r_i ≀ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment. Otherwise print "NO". If some array can be obtained then print n integers on the second line β€” the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries. If there are multiple possible arrays then print any of them. Examples Input 4 3 1 0 2 3 Output YES 1 2 2 3 Input 3 10 10 10 10 Output YES 10 10 10 Input 5 6 6 5 6 2 2 Output NO Input 3 5 0 0 0 Output YES 5 4 2 Note In the first example you can also replace 0 with 1 but not with 3. In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3). The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6. There is a lot of correct resulting arrays for the fourth example.
def getRawInteger(): return [int(x) for x in input().split()] n, q = getRawInteger() a = getRawInteger() if n != len(a): raise ValueError('n is not correct.') l, r = [n] * (q + 5), [0] * (q + 5) f = [i for i in range(n + 5)] def getRoot(u): while f[u] != u: f[u] = f[f[u]] u = f[f[u]] return u for i in range(n): l[a[i]] = min(l[a[i]], i) r[a[i]] = max(r[a[i]], i) if l[q] > r[q]: if l[0] > r[0]: print('NO') exit() a[l[0]] = q f[l[0]] = getRoot(l[0] + 1) for i in reversed(range(1, q + 1)): it = getRoot(l[i]) while it <= r[i]: if a[it] < i and a[it]: print('NO') exit() a[it] = i f[it] = getRoot(it + 1) it = getRoot(it) out = 'YES\n' for x in a: if x: out += str(x) + ' ' else: out += '1 ' print(out)
{ "input": [ "4 3\n1 0 2 3\n", "3 10\n10 10 10\n", "3 5\n0 0 0\n", "5 6\n6 5 6 2 2\n" ], "output": [ "YES\n1 1 2 3\n", "YES\n10 10 10\n", "YES\n5 5 5\n", "NO\n" ] }
2,418
8
Tattah's youngest brother, Tuftuf, is new to programming. Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava. Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has n unsigned integer datatypes of sizes (in bits) a1, a2, ... an. The i-th datatype have size ai bits, so it can represent every integer between 0 and 2ai - 1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer x, such that x fits in some type i (in ai bits) and xΒ·x does not fit in some other type j (in aj bits) where ai < aj, then Tuftuf will stop using Gava. Your task is to determine Tuftuf's destiny. Input The first line contains integer n (2 ≀ n ≀ 105) β€” the number of Gava's unsigned integer datatypes' sizes. The second line contains a single-space-separated list of n integers (1 ≀ ai ≀ 109) β€” sizes of datatypes in bits. Some datatypes may have equal sizes. Output Print "YES" if Tuftuf will stop using Gava, and "NO" otherwise. Examples Input 3 64 16 32 Output NO Input 4 4 2 1 3 Output YES Note In the second example, x = 7 (1112) fits in 3 bits, but x2 = 49 (1100012) does not fit in 4 bits.
def s(): input() a = list(map(int,input().split())) a.sort() for i in range(1,len(a)): if a[i]!=a[i-1] and a[i]<a[i-1]*2: return 'YES' return 'NO' print(s())
{ "input": [ "4\n4 2 1 3\n", "3\n64 16 32\n" ], "output": [ "YES\n", "NO\n" ] }
2,419
7
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array a with n integers. You need to count the number of funny pairs (l, r) (l ≀ r). To check if a pair (l, r) is a funny pair, take mid = (l + r - 1)/(2), then if r - l + 1 is an even number and a_l βŠ• a_{l+1} βŠ• … βŠ• a_{mid} = a_{mid + 1} βŠ• a_{mid + 2} βŠ• … βŠ• a_r, then the pair is funny. In other words, βŠ• of elements of the left half of the subarray from l to r should be equal to βŠ• of elements of the right half. Note that βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). It is time to continue solving the contest, so Sasha asked you to solve this task. Input The first line contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i < 2^{20}) β€” array itself. Output Print one integer β€” the number of funny pairs. You should consider only pairs where r - l + 1 is even number. Examples Input 5 1 2 3 4 5 Output 1 Input 6 3 2 2 3 7 6 Output 3 Input 3 42 4 2 Output 0 Note Be as cool as Sasha, upsolve problems! In the first example, the only funny pair is (2, 5), as 2 βŠ• 3 = 4 βŠ• 5 = 1. In the second example, funny pairs are (2, 3), (1, 4), and (3, 6). In the third example, there are no funny pairs.
answer = 0 x = 0 g = {0: {}, 1: {}} g[1][0] = 1 def solve(v, index): global x x ^= int(v) ans = g[index % 2].get(x,0) g[index % 2][x] = g[index % 2].get(x,0) + 1 return ans n = int(input()) a = list(map(int,input().split())) for i in range(len(a)): answer += solve(a[i], i) print(answer)
{ "input": [ "3\n42 4 2\n", "6\n3 2 2 3 7 6\n", "5\n1 2 3 4 5\n" ], "output": [ "0", "3", "1" ] }
2,420
10
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symbol is '1' if students will write the contest in the i-th day and '0' if they will have a day off. At the last moment Gleb said that the camp will be the most productive if it runs with the schedule t (which can be described in the same format as schedule s). Since the number of days in the current may be different from number of days in schedule t, Gleb required that the camp's schedule must be altered so that the number of occurrences of t in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change. Could you rearrange the schedule in the best possible way? Input The first line contains string s (1 β©½ |s| β©½ 500 000), denoting the current project of the camp's schedule. The second line contains string t (1 β©½ |t| β©½ 500 000), denoting the optimal schedule according to Gleb. Strings s and t contain characters '0' and '1' only. Output In the only line print the schedule having the largest number of substrings equal to t. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in s and the number of ones should be equal to the number of ones in s. In case there multiple optimal schedules, print any of them. Examples Input 101101 110 Output 110110 Input 10010110 100011 Output 01100011 Input 10 11100 Output 01 Note In the first example there are two occurrences, one starting from first position and one starting from fourth position. In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of t wouldn't change. In the third example it's impossible to make even a single occurrence.
import sys input = sys.stdin.readline def MP(s): a = [0] * (len(s) + 1) a[0] = -1 j = -1 for i in range(len(s)): while j >= 0 and s[i] != s[j]: j = a[j] j += 1 a[i + 1] = j return a s = input()[:-1] t = input()[:-1] cnt = [0, 0] for char in s: cnt[int(char)] += 1 tbl = MP(t) lap = len(t) - tbl[len(t)] t = t[0:lap] ans = [] while True: for char in t: if cnt[int(char)] > 0: ans.append(char) cnt[int(char)] -= 1 else: break else: continue break for i in range(cnt[0]): ans.append("0") for i in range(cnt[1]): ans.append("1") print(''.join(ans))
{ "input": [ "10\n11100\n", "10010110\n100011\n", "101101\n110\n" ], "output": [ "10\n", "10001101", "110110\n" ] }
2,421
8
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: 1. there is no other pillar between pillars i and j. Formally, it means that |i - j| = 1; 2. pillar i contains exactly one disk; 3. either pillar j contains no disks, or the topmost disk on pillar j has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar. You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all n disks on the same pillar simultaneously? Input The first line contains one integer n (3 ≀ n ≀ 2 β‹… 10^5) β€” the number of pillars. The second line contains n integers a_1, a_2, ..., a_i (1 ≀ a_i ≀ n), where a_i is the radius of the disk initially placed on the i-th pillar. All numbers a_i are distinct. Output Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer). Examples Input 4 1 3 4 2 Output YES Input 3 3 1 2 Output NO Note In the first case it is possible to place all disks on pillar 3 using the following sequence of actions: 1. take the disk with radius 3 from pillar 2 and place it on top of pillar 3; 2. take the disk with radius 1 from pillar 1 and place it on top of pillar 2; 3. take the disk with radius 2 from pillar 4 and place it on top of pillar 3; 4. take the disk with radius 1 from pillar 2 and place it on top of pillar 3.
def ans(a): for i in range(1, len(a)-1): if a[i]<a[i-1] and a[i]<a[i+1]: return False return True n = int(input()) l = list(map(int, input().split())) print('YES' if ans(l) else 'NO')
{ "input": [ "3\n3 1 2\n", "4\n1 3 4 2\n" ], "output": [ "NO", "YES" ] }
2,422
9
Petya's friends made him a birthday present β€” a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence s is called correct if: * s is empty; * s is equal to "(t)", where t is correct bracket sequence; * s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct. Input First of line of input contains a single number n (1 ≀ n ≀ 200 000) β€” length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length n, containing symbols "(" and ")". Output Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No". Examples Input 2 )( Output Yes Input 3 (() Output No Input 2 () Output Yes Input 10 )))))((((( Output No Note In the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence. In the second example, there is no way to move at most one bracket so that the sequence becomes correct. In the third example, the sequence is already correct and there's no need to move brackets.
def check(s,n): c = 0 for i in s: if i == '(': c += 1 else: c -= 1 if c < -1: break print("No" if c else "Yes") #client code n = int(input()) s = input() check(s,n)
{ "input": [ "2\n)(\n", "10\n)))))(((((\n", "3\n(()\n", "2\n()\n" ], "output": [ "Yes\n", "No\n", "No\n", "Yes\n" ] }
2,423
11
Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree. The depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is 0. Let's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices. Let's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex v: * If v has a left subtree whose root is u, then the parity of the key of v is different from the parity of the key of u. * If v has a right subtree whose root is w, then the parity of the key of v is the same as the parity of the key of w. You are given a single integer n. Find the number of perfectly balanced striped binary search trees with n vertices that have distinct integer keys between 1 and n, inclusive. Output this number modulo 998 244 353. Input The only line contains a single integer n (1 ≀ n ≀ 10^6), denoting the required number of vertices. Output Output the number of perfectly balanced striped binary search trees with n vertices and distinct integer keys between 1 and n, inclusive, modulo 998 244 353. Examples Input 4 Output 1 Input 3 Output 0 Note In the first example, this is the only tree that satisfies the conditions: <image> In the second example, here are various trees that don't satisfy some condition: <image>
def f(n): return (2**(n+3)+(-1)**n-9)//6 # for i in range(25): # print(f(i)); a = [ 0, 1, 2, 4, 5, 9, 10, 20, 21, 41, 42, 84, 85, 169, 170, 340, 341, 681, 682, 1364, 1365, 2729, 2730, 5460, 5461, 10921, 10922, 21844, 21845, 43689, 43690, 87380, 87381, 174761, 174762, 349524, 349525, 699049, 699050,] n = int(input()) if n in a: print(1) else: print(0)
{ "input": [ "4\n", "3\n" ], "output": [ "1", "0" ] }
2,424
11
This is the easier version of the problem. In this version, 1 ≀ n ≀ 10^5 and 0 ≀ a_i ≀ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces. Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, …, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy. Input The first line contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of chocolate boxes. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 1) β€” the number of chocolate pieces in the i-th box. It is guaranteed that at least one of a_1, a_2, …, a_n is positive. Output If there is no way for Charlie to make Alice happy, print -1. Otherwise, print a single integer x β€” the minimum number of seconds for Charlie to help Bob make Alice happy. Examples Input 3 1 0 1 Output 2 Input 1 1 Output -1
from itertools import accumulate def divisors(n): tab = [] for i in range(2, int(n**.5) + 2): if n % i == 0: while n % i == 0: n //= i tab.append(i) if n > 1: tab.append(n) return tab n = int(input()) a = list(map(int, input().split())) s = sum(a) tab = divisors(s) if s == 1: print(-1) else: m = 10**18 pref = list(accumulate(a)) for k in tab: x = 0 for i in range(n - 1): x += min(pref[i] % k, k - (pref[i] % k)) m = min(m, x) print(m)
{ "input": [ "1\n1\n", "3\n1 0 1\n" ], "output": [ "-1\n", "2\n" ] }
2,425
10
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids. Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following: * choose one kid x equiprobably among all n kids; * choose some item y equiprobably among all k_x items kid x wants; * choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot. If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid. Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him? Input The first line contains one integer n (1 ≀ n ≀ 10^6) β€” the number of kids who wrote their letters to Santa. Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 ≀ k_i, a_{i, j} ≀ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once. It is guaranteed that βˆ‘ _{i = 1}^{n} k_i ≀ 10^6. Output Print the probatility that the Bot produces a valid decision as follows: Let this probability be represented as an irreducible fraction x/y. You have to print x β‹… y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β‹… y^{-1} has remainder 1 modulo 998244353). Examples Input 2 2 2 1 1 1 Output 124780545 Input 5 2 1 2 2 3 1 3 2 4 3 2 1 4 3 4 3 2 Output 798595483
import sys input=sys.stdin.readline def fr(a,b): return (a*pow(b,m-2,m))%m n=int(input()) m=998244353 c=[] for i in range(n): a=list(map(int,input().split())) c.append(a) d=[0]*(10**6+1000) for i in range(n): for j in range(1,c[i][0]+1): d[c[i][j]]+=1 s=fr(0,1) for i in range(n): for j in range(1,c[i][0]+1): s+=(fr(d[c[i][j]],n)*fr(1,c[i][0]))%m s=s%m s=(fr(1,n)*s)%m print(s)
{ "input": [ "5\n2 1 2\n2 3 1\n3 2 4 3\n2 1 4\n3 4 3 2\n", "2\n2 2 1\n1 1\n" ], "output": [ "798595483\n", "124780545\n" ] }
2,426
8
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one. To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student. Determine how many groups of students will be kicked out of the club. Input The first line contains two integers n and m β€” the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β€” the numbers of students tied by the i-th lace (1 ≀ a, b ≀ n, a β‰  b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. Output Print the single number β€” the number of groups of students that will be kicked out from the club. Examples Input 3 3 1 2 2 3 3 1 Output 0 Input 6 3 1 2 2 3 3 4 Output 2 Input 6 5 1 4 2 4 3 4 5 4 6 4 Output 1 Note In the first sample Anna and Maria won't kick out any group of students β€” in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone. In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β€” two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club. In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
n , m = map(int,input().split()) G = {i:set() for i in range(n+1)} for i in range(m): u , v = map(int,input().split()) G[u].add(v) G[v].add(u) def counting(G): g =0 while True: ans = [] c = 0 for i in G: if len(G[i])==1: c = 1 G[i] = set() ans.append(i) if c: for i in ans: for j in G: if i in G[j]: G[j].discard(i) else: break g +=1 print(g) counting(G)
{ "input": [ "6 5\n1 4\n2 4\n3 4\n5 4\n6 4\n", "6 3\n1 2\n2 3\n3 4\n", "3 3\n1 2\n2 3\n3 1\n" ], "output": [ "1\n", "2\n", "0\n" ] }
2,427
10
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of 7 segments, which can be turned on or off to display different numbers. The picture shows how all 10 decimal digits are displayed: <image> After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly k segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly k sticks (which are off now)? It is allowed that the number includes leading zeros. Input The first line contains integer n (1 ≀ n ≀ 2000) β€” the number of digits on scoreboard and k (0 ≀ k ≀ 2000) β€” the number of segments that stopped working. The next n lines contain one binary string of length 7, the i-th of which encodes the i-th digit of the scoreboard. Each digit on the scoreboard consists of 7 segments. We number them, as in the picture below, and let the i-th place of the binary string be 0 if the i-th stick is not glowing and 1 if it is glowing. Then a binary string of length 7 will specify which segments are glowing now. <image> Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from 0 to 9 inclusive. Output Output a single number consisting of n digits β€” the maximum number that can be obtained if you turn on exactly k sticks or -1, if it is impossible to turn on exactly k sticks so that a correct number appears on the scoreboard digits. Examples Input 1 7 0000000 Output 8 Input 2 5 0010010 0010010 Output 97 Input 3 5 0100001 1001001 1010011 Output -1 Note In the first test, we are obliged to include all 7 sticks and get one 8 digit on the scoreboard. In the second test, we have sticks turned on so that units are formed. For 5 of additionally included sticks, you can get the numbers 07, 18, 34, 43, 70, 79, 81 and 97, of which we choose the maximum β€” 97. In the third test, it is impossible to turn on exactly 5 sticks so that a sequence of numbers appears on the scoreboard.
def calc(a1, a2): if (a1 ^ a2) & a1 == 0: d = (a1 ^ a2) return sum([(d >> i) & 1 for i in range(7)]) else: return -1 D = [ '1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011', ] n, k = list(map(int, input().split())) x = [input() for _ in range(n)] r = [[-1] * (k + 1) for _ in range(n + 1)] r[n][0] = 0 for i in range(n - 1, -1, -1): for d in range(10): dc = calc(int(x[i], 2), int(D[d], 2)) if dc != -1: z = dc * 10 + d for c in range(k + 1 - dc): if r[i + 1][c] >= 0: r[i][c + dc] = z if r[0][k] >= 0: for i in range(n): print(r[i][k] % 10, end='') k -= r[i][k] // 10 print() else: print(-1)
{ "input": [ "1 7\n0000000\n", "3 5\n0100001\n1001001\n1010011\n", "2 5\n0010010\n0010010\n" ], "output": [ "8\n", "-1\n", "97\n" ] }
2,428
7
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Let p be any permutation of length n. We define the fingerprint F(p) of p as the sorted array of sums of adjacent elements in p. More formally, $$$F(p)=sort([p_1+p_2,p_2+p_3,…,p_{n-1}+p_n]).$$$ For example, if n=4 and p=[1,4,2,3], then the fingerprint is given by F(p)=sort([1+4,4+2,2+3])=sort([5,6,5])=[5,5,6]. You are given a permutation p of length n. Your task is to find a different permutation p' with the same fingerprint. Two permutations p and p' are considered different if there is some index i such that p_i β‰  p'_i. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 668). Description of the test cases follows. The first line of each test case contains a single integer n (2≀ n≀ 100) β€” the length of the permutation. The second line of each test case contains n integers p_1,…,p_n (1≀ p_i≀ n). It is guaranteed that p is a permutation. Output For each test case, output n integers p'_1,…, p'_n β€” a permutation such that p'β‰  p and F(p')=F(p). We can prove that for every permutation satisfying the input constraints, a solution exists. If there are multiple solutions, you may output any. Example Input 3 2 1 2 6 2 1 6 5 4 3 5 2 4 3 1 5 Output 2 1 1 2 5 6 3 4 3 1 5 2 4 Note In the first test case, F(p)=sort([1+2])=[3]. And F(p')=sort([2+1])=[3]. In the second test case, F(p)=sort([2+1,1+6,6+5,5+4,4+3])=sort([3,7,11,9,7])=[3,7,7,9,11]. And F(p')=sort([1+2,2+5,5+6,6+3,3+4])=sort([3,7,11,9,7])=[3,7,7,9,11]. In the third test case, F(p)=sort([2+4,4+3,3+1,1+5])=sort([6,7,4,6])=[4,6,6,7]. And F(p')=sort([3+1,1+5,5+2,2+4])=sort([4,6,7,6])=[4,6,6,7].
def main(): t = int(input()) for _ in range(t): n = int(input()) print(' '.join(reversed(input().split()))) main()
{ "input": [ "3\n2\n1 2\n6\n2 1 6 5 4 3\n5\n2 4 3 1 5\n" ], "output": [ "2 1\n3 4 5 6 1 2\n5 1 3 4 2\n" ] }
2,429
9
Initially, you have the array a consisting of one element 1 (a = [1]). In one move, you can do one of the following things: * Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); * Append the copy of some (single) element of a to the end of the array (choose some i from 1 to the current length of a and append a_i to the end of the array). For example, consider the sequence of five moves: 1. You take the first element a_1, append its copy to the end of the array and get a = [1, 1]. 2. You take the first element a_1, increase it by 1 and get a = [2, 1]. 3. You take the second element a_2, append its copy to the end of the array and get a = [2, 1, 1]. 4. You take the first element a_1, append its copy to the end of the array and get a = [2, 1, 1, 2]. 5. You take the fourth element a_4, increase it by 1 and get a = [2, 1, 1, 3]. Your task is to find the minimum number of moves required to obtain the array with the sum at least n. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then t test cases follow. The only line of the test case contains one integer n (1 ≀ n ≀ 10^9) β€” the lower bound on the sum of the array. Output For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least n. Example Input 5 1 5 42 1337 1000000000 Output 0 3 11 72 63244
from math import ceil def solve(): n = int(input()) return(ceil((n**0.5-1)*2)) for _ in range(int(input())): print(solve())
{ "input": [ "5\n1\n5\n42\n1337\n1000000000\n" ], "output": [ "0\n3\n11\n72\n63244\n" ] }
2,430
8
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits. Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri β€” the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is <image> Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place. The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change. Input The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa β‰  xb, ya β‰  yb). The second line contains integer n β€” the number of radiators (1 ≀ n ≀ 103). Then n lines contain the heaters' coordinates as "xi yi ri", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≀ ri ≀ 1000. Several radiators can be located at the same point. Output Print the only number β€” the number of blankets you should bring. Examples Input 2 5 4 2 3 3 1 2 5 3 1 1 3 2 Output 4 Input 5 2 6 3 2 6 2 2 6 5 3 Output 0 Note In the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5). In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.
import math def calculate_distance(x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) a = [] x1, y1, x2, y2 = list(map(int, input().split())) if x2 < x1: x1, x2 = x2, x1 if y2 < y1: y1, y2 = y2, y1 for i in range(x1, x2 + 1): a.append((i, y1)) a.append((i, y2)) for i in range(y1 + 1, y2): a.append((x1, i)) a.append((x2, i)) n = int(input()) for _ in range(n): xi, yi, ri = list(map(int, input().split())) if len(a) > 0: t = len(a) for i in range(t-1, -1, -1): if calculate_distance(a[i][0], a[i][1], xi, yi) <= ri: del a[i] print(len(a))
{ "input": [ "5 2 6 3\n2\n6 2 2\n6 5 3\n", "2 5 4 2\n3\n3 1 2\n5 3 1\n1 3 2\n" ], "output": [ "0", "4" ] }
2,431
8
Let's define a multiplication operation between a string a and a positive integer x: a β‹… x is the string that is a result of writing x copies of a one after another. For example, "abc" β‹…~2~= "abcabc", "a" β‹…~5~= "aaaaa". A string a is divisible by another string b if there exists an integer x such that b β‹… x = a. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa". LCM of two strings s and t (defined as LCM(s, t)) is the shortest non-empty string that is divisible by both s and t. You are given two strings s and t. Find LCM(s, t) or report that it does not exist. It can be shown that if LCM(s, t) exists, it is unique. Input The first line contains one integer q (1 ≀ q ≀ 2000) β€” the number of test cases. Each test case consists of two lines, containing strings s and t (1 ≀ |s|, |t| ≀ 20). Each character in each of these strings is either 'a' or 'b'. Output For each test case, print LCM(s, t) if it exists; otherwise, print -1. It can be shown that if LCM(s, t) exists, it is unique. Example Input 3 baba ba aa aaa aba ab Output baba aaaaaa -1 Note In the first test case, "baba" = "baba" β‹…~1~= "ba" β‹…~2. In the second test case, "aaaaaa" = "aa" β‹…~3~= "aaa" β‹…~2.
from math import gcd def solve(): s1 = input() s2 = input() k = len(s1) * len(s2) // gcd(len(s1), len(s2)) if s1 * (k // len(s1)) == s2 * (k // len(s2)): print(s1 * (k // len(s1))) else: print(-1) for i in range(int(input())): solve()
{ "input": [ "3\nbaba\nba\naa\naaa\naba\nab\n" ], "output": [ "\nbaba\naaaaaa\n-1\n" ] }
2,432
8
Nastia has received an array of n positive integers as a gift. She calls such an array a good that for all i (2 ≀ i ≀ n) takes place gcd(a_{i - 1}, a_{i}) = 1, where gcd(u, v) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers u and v. You can perform the operation: select two different indices i, j (1 ≀ i, j ≀ n, i β‰  j) and two integers x, y (1 ≀ x, y ≀ 2 β‹… 10^9) so that min{(a_i, a_j)} = min{(x, y)}. Then change a_i to x and a_j to y. The girl asks you to make the array good using at most n operations. It can be proven that this is always possible. Input The first line contains a single integer t (1 ≀ t ≀ 10 000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 10^5) β€” the length of the array. The second line of each test case contains n integers a_1, a_2, …, a_{n} (1 ≀ a_i ≀ 10^9) β€” the array which Nastia has received as a gift. It's guaranteed that the sum of n in one test doesn't exceed 2 β‹… 10^5. Output For each of t test cases print a single integer k (0 ≀ k ≀ n) β€” the number of operations. You don't need to minimize this number. In each of the next k lines print 4 integers i, j, x, y (1 ≀ i β‰  j ≀ n, 1 ≀ x, y ≀ 2 β‹… 10^9) so that min{(a_i, a_j)} = min{(x, y)} β€” in this manner you replace a_i with x and a_j with y. If there are multiple answers, print any. Example Input 2 5 9 6 3 11 15 3 7 5 13 Output 2 1 5 11 9 2 5 7 6 0 Note Consider the first test case. Initially a = [9, 6, 3, 11, 15]. In the first operation replace a_1 with 11 and a_5 with 9. It's valid, because min{(a_1, a_5)} = min{(11, 9)} = 9. After this a = [11, 6, 3, 11, 9]. In the second operation replace a_2 with 7 and a_5 with 6. It's valid, because min{(a_2, a_5)} = min{(7, 6)} = 6. After this a = [11, 7, 3, 11, 6] β€” a good array. In the second test case, the initial array is already good.
from sys import stdout,stdin def computeGCD(x, y): while (y): x, y = y, x % y return x for _ in range(int(input())): n=int(input()) b=1000000007 arr=list(map(int,input().split())) print(n//2) for i in range(1,n,2): print(i,i+1,min(arr[i],arr[i-1]),b)
{ "input": [ "2\n5\n9 6 3 11 15\n3\n7 5 13\n" ], "output": [ "\n2\n1 5 11 9\n2 5 7 6\n0" ] }
2,433
8
You are given a string s of length n consisting only of the characters 0 and 1. You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length l, you get a β‹… l + b points. Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty. Input The first line contains a single integer t (1 ≀ t ≀ 2000) β€” the number of testcases. The first line of each testcase contains three integers n, a and b (1 ≀ n ≀ 100; -100 ≀ a, b ≀ 100) β€” the length of the string s and the parameters a and b. The second line contains the string s. The string s consists only of the characters 0 and 1. Output For each testcase, print a single integer β€” the maximum number of points that you can score. Example Input 3 3 2 0 000 5 -2 5 11001 6 1 -4 100111 Output 6 15 -2 Note In the first example, it is enough to delete the entire string, then we will get 2 β‹… 3 + 0 = 6 points. In the second example, if we delete characters one by one, then for each deleted character we will get (-2) β‹… 1 + 5 = 3 points, i. e. 15 points in total. In the third example, we can delete the substring 00 from the string 100111, we get 1 β‹… 2 + (-4) = -2 points, and the string will be equal to 1111, removing it entirely we get 1 β‹… 4 + (-4) = 0 points. In total, we got -2 points for 2 operations.
def solve(n, a, b, s): p = '' c = 0 for i in s: if i != p: p = i c += 1 c = c // 2 + 1 print(max(n * a + b * n, a * n + b * c)) t, = map(int, input().split()) for _ in range(t): n, a, b = map(int, input().split()) s = input() solve(n, a, b, s)
{ "input": [ "3\n3 2 0\n000\n5 -2 5\n11001\n6 1 -4\n100111\n" ], "output": [ "6\n15\n-2\n" ] }
2,434
8
You are given two polynomials: * P(x) = a0Β·xn + a1Β·xn - 1 + ... + an - 1Β·x + an and * Q(x) = b0Β·xm + b1Β·xm - 1 + ... + bm - 1Β·x + bm. Calculate limit <image>. Input The first line contains two space-separated integers n and m (0 ≀ n, m ≀ 100) β€” degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n + 1 space-separated integers β€” the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≀ ai ≀ 100, a0 β‰  0). The third line contains m + 1 space-separated integers β€” the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≀ bi ≀ 100, b0 β‰  0). Output If the limit equals + ∞, print "Infinity" (without quotes). If the limit equals - ∞, print "-Infinity" (without the quotes). If the value of the limit equals zero, print "0/1" (without the quotes). Otherwise, print an irreducible fraction β€” the value of limit <image>, in the format "p/q" (without the quotes), where p is the β€” numerator, q (q > 0) is the denominator of the fraction. Examples Input 2 1 1 1 1 2 5 Output Infinity Input 1 0 -1 3 2 Output -Infinity Input 0 1 1 1 0 Output 0/1 Input 2 2 2 1 6 4 5 -7 Output 1/2 Input 1 1 9 0 -5 2 Output -9/5 Note Let's consider all samples: 1. <image> 2. <image> 3. <image> 4. <image> 5. <image> You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function
def gcd(a, b): c = a % b return gcd(b, c) if c else b n, m = map(int, input().split()) p, q = input(), input() a, b = p.find(' '), q.find(' ') p, q = int(p) if a < 0 else int(p[: a]), int(q) if b < 0 else int(q[: b]) if n > m: print('-Infinity' if p * q < 0 else 'Infinity') elif n < m: print('0/1') else: s = gcd(p, q) print(str(p // s) + '/' + str(q // s))
{ "input": [ "2 1\n1 1 1\n2 5\n", "1 0\n-1 3\n2\n", "1 1\n9 0\n-5 2\n", "2 2\n2 1 6\n4 5 -7\n", "0 1\n1\n1 0\n" ], "output": [ "Infinity\n", "-Infinity\n", "-9/5\n", "1/2\n", "0/1\n" ] }
2,435
8
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters Β«+Β» and Β«1Β» into this sequence. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not. One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? Input Input consists of a single line with non-empty string of Β«(Β» and Β«)Β» characters. Its length does not exceed 106. Output Output the maximum possible length of a regular bracket sequence. Examples Input (()))( Output 4 Input ((()()) Output 6
import sys input = sys.stdin.readline def solve(): b = 0 r = 0 for i in input().strip(): if i == '(': b += 1 r += 1 else: if b > 0: r += 1 b -= 1 print(r-b) solve()
{ "input": [ "(()))(\n", "((()())\n" ], "output": [ "4\n", "6\n" ] }
2,436
8
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral. Input The first line contains integer n (4 ≀ n ≀ 300). Each of the next n lines contains two integers: xi, yi ( - 1000 ≀ xi, yi ≀ 1000) β€” the cartesian coordinates of ith special point. It is guaranteed that no three points are on the same line. It is guaranteed that no two points coincide. Output Output a single real number β€” the maximal area of a special quadrilateral. The answer will be considered correct if its absolute or relative error does't exceed 10 - 9. Examples Input 5 0 0 0 4 4 0 4 4 2 3 Output 16.000000 Note In the test example we can choose first 4 points to be the vertices of the quadrilateral. They form a square by side 4, so the area is 4Β·4 = 16.
n = int(input()) a = [] area = 0 for i in range(n): a.append([int(i) for i in input().split(' ')]) def get_s(p1, p2, p3): return ((p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0])) / 2.0 for i in range(len(a) - 1): for j in range(i + 1, len(a)): positive = 0 negative = 0 for k in range(len(a)): if k == i or k == j: continue s = get_s(a[i], a[j], a[k]) if s > 0: positive = max(positive, s) if s == 0: pass else: negative = min(negative, s) if positive != 0 and negative != 0: area = max(area, positive - negative) print(area)
{ "input": [ "5\n0 0\n0 4\n4 0\n4 4\n2 3\n" ], "output": [ "16.000000\n" ] }
2,437
10
A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them. The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles. In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike. Each boy can rent at most one bike, one cannot give his bike to somebody else. What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible? Input The first line of the input contains three integers n, m and a (1 ≀ n, m ≀ 105; 0 ≀ a ≀ 109). The second line contains the sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1, p2, ..., pm (1 ≀ pj ≀ 109), where pj is the price for renting the j-th bike. Output Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0. Examples Input 2 2 10 5 5 7 6 Output 2 3 Input 4 5 2 8 1 1 2 6 3 7 5 2 Output 3 8 Note In the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.
#!/usr/bin/python3 def readn(): return map(int, input().split()) n, m, a = readn() n = min(n, m) m = n b = sorted(readn())[-n:] p = sorted(readn()) r = 0 while r < n: t = (r+1 + n)//2 a1 = sum([max(0, p[i]-b[m+i-t]) for i in range(t)]) if a1 <= a: r = t else: n = t-1 print(r, max(0, sum(p[:r])-a))
{ "input": [ "2 2 10\n5 5\n7 6\n", "4 5 2\n8 1 1 2\n6 3 7 5 2\n" ], "output": [ "2 3\n", "3 8\n" ] }
2,438
9
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence of actions: * Choose two distinct indexes i and j (1 ≀ i, j ≀ |b|; i β‰  j), such that bi β‰₯ bj. * Get number v = concat(bi, bj), where concat(x, y) is a number obtained by adding number y to the end of the decimal record of number x. For example, concat(500, 10) = 50010, concat(2, 2) = 22. * Add number v to the end of the array. The length of the array will increase by one. * Remove from the array numbers with indexes i and j. The length of the array will decrease by two, and elements of the array will become re-numbered from 1 to current length of the array. George played for a long time with his array b and received from array b an array consisting of exactly one number p. Now George wants to know: what is the maximum number of elements array b could contain originally? Help him find this number. Note that originally the array could contain only positive integers. Input The first line of the input contains a single integer p (1 ≀ p < 10100000). It is guaranteed that number p doesn't contain any leading zeroes. Output Print an integer β€” the maximum number of elements array b could contain originally. Examples Input 9555 Output 4 Input 10000000005 Output 2 Input 800101 Output 3 Input 45 Output 1 Input 1000000000000001223300003342220044555 Output 17 Input 19992000 Output 1 Input 310200 Output 2 Note Let's consider the test examples: * Originally array b can be equal to {5, 9, 5, 5}. The sequence of George's changes could have been: {5, 9, 5, 5} β†’ {5, 5, 95} β†’ {95, 55} β†’ {9555}. * Originally array b could be equal to {1000000000, 5}. Please note that the array b cannot contain zeros. * Originally array b could be equal to {800, 10, 1}. * Originally array b could be equal to {45}. It cannot be equal to {4, 5}, because George can get only array {54} from this array in one operation. Note that the numbers can be very large.
def gte(x, y): if len(x)>len(y): return True if len(x)==len(y): return x>=y return False x = input() r = 0 l = len(x)-1 while True: if l==0 or not gte(x[:l], x[l:]): break if x[l] == '0': l-=1 continue x = x[:l] r+=1 l-=1 r+=1 print(r)
{ "input": [ "9555\n", "19992000\n", "10000000005\n", "45\n", "800101\n", "310200\n", "1000000000000001223300003342220044555\n" ], "output": [ "4", "1", "2", "1", "3", "2", "17" ] }
2,439
7
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that: * the cashier needs 5 seconds to scan one item; * after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≀ ki ≀ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≀ mi, j ≀ 100) β€” the number of products the j-th person in the queue for the i-th cash has. Output Print a single integer β€” the minimum number of seconds Vasya needs to get to the cashier. Examples Input 1 1 1 Output 20 Input 4 1 4 3 2 100 1 2 2 3 1 9 1 7 8 Output 100 Note In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100Β·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1Β·5 + 2Β·5 + 2Β·5 + 3Β·5 + 4Β·15 = 100 seconds. He will need 1Β·5 + 9Β·5 + 1Β·5 + 3Β·15 = 100 seconds for the third one and 7Β·5 + 8Β·5 + 2Β·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.
n=int(input()) def read():return list(map(int,input().split())) k=read() print( min( sum(read())*5+k[i]*15 for i in range(0,n) ) )
{ "input": [ "1\n1\n1\n", "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8\n" ], "output": [ "20\n", "100\n" ] }
2,440
8
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer. Help Pasha count the maximum number he can get if he has the time to make at most k swaps. Input The single line contains two integers a and k (1 ≀ a ≀ 1018; 0 ≀ k ≀ 100). Output Print the maximum number that Pasha can get if he makes at most k swaps. Examples Input 1990 1 Output 9190 Input 300 0 Output 300 Input 1034 2 Output 3104 Input 9090000078001234 6 Output 9907000008001234
def main(): a, k = input().split() k = int(k) a = list(a) n = len(a) for i in range(n): idx_max = max(range(i, min(i + k + 1, n)), key=a.__getitem__) a.insert(i, a.pop(idx_max)) k -= idx_max - i print(''.join(a)) if __name__ == "__main__": main()
{ "input": [ "1990 1\n", "9090000078001234 6\n", "300 0\n", "1034 2\n" ], "output": [ "9190\n", "9907000008001234\n", "300\n", "3104\n" ] }
2,441
8
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal. Input The input data contains the results of all the weighting, one result on each line. It is guaranteed that every coin pair was weighted exactly once. Vasya labelled the coins with letters Β«AΒ», Β«BΒ» and Β«CΒ». Each result is a line that appears as (letter)(> or < sign)(letter). For example, if coin "A" proved lighter than coin "B", the result of the weighting is A<B. Output It the results are contradictory, print Impossible. Otherwise, print without spaces the rearrangement of letters Β«AΒ», Β«BΒ» and Β«CΒ» which represent the coins in the increasing order of their weights. Examples Input A&gt;B C&lt;B A&gt;C Output CBA Input A&lt;B B&gt;C C&gt;A Output ACB
def main(): v = [] for i in range(3): v.append(input()) m = {'A': 0, 'B': 0, 'C': 0} # A B C for s in v: if s[1] == '<': m[s[2]] += 1 else: m[s[0]] += 1 if len(set(m.values())) == 3: print(''.join(sorted(m, key=lambda k: m[k]))) else: print('Impossible') if __name__ == '__main__': main()
{ "input": [ "A&gt;B\nC&lt;B\nA&gt;C\n", "A&lt;B\nB&gt;C\nC&gt;A\n" ], "output": [ "Impossible\n", "Impossible\n" ] }
2,442
8
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation <image>, where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order. For example, Perm(0) = (0, 1, ..., n - 2, n - 1), Perm(n! - 1) = (n - 1, n - 2, ..., 1, 0) Misha has two permutations, p and q. Your task is to find their sum. Permutation a = (a0, a1, ..., an - 1) is called to be lexicographically smaller than permutation b = (b0, b1, ..., bn - 1), if for some k following conditions hold: a0 = b0, a1 = b1, ..., ak - 1 = bk - 1, ak < bk. Input The first line contains an integer n (1 ≀ n ≀ 200 000). The second line contains n distinct integers from 0 to n - 1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to n - 1, separated by spaces, forming permutation q. Output Print n distinct integers from 0 to n - 1, forming the sum of the given permutations. Separate the numbers by spaces. Examples Input 2 0 1 0 1 Output 0 1 Input 2 0 1 1 0 Output 1 0 Input 3 1 2 0 2 1 0 Output 1 0 2 Note Permutations of numbers from 0 to 1 in the lexicographical order: (0, 1), (1, 0). In the first sample Ord(p) = 0 and Ord(q) = 0, so the answer is <image>. In the second sample Ord(p) = 0 and Ord(q) = 1, so the answer is <image>. Permutations of numbers from 0 to 2 in the lexicographical order: (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0). In the third sample Ord(p) = 3 and Ord(q) = 5, so the answer is <image>.
def sum(BIT, i): s = 0 while i > 0: s += BIT[i] i -= i & (-i) return s def update(BIT, i, v): while i < len(BIT): BIT[i] += v i += i & (-i) def find(fen, k): curr = 0 ans = 0 prevsum = 0 for i in range(19, -1, -1): if ((curr + (1 << i) < n) and fen[curr + (1 << i)] + prevsum < k): ans = curr + (1 << i) curr = ans prevsum += fen[curr] return ans + 1 def Rank(x,BIT) : return sum(BIT,x) n = int(input()) p = list(map(int, input().split())) q = list(map(int, input().split())) factp = [] factq = [] BIT = [0] * (n + 1) for j in range(n): update(BIT,j+1,1) for val in p: factp.append(Rank(val+1,BIT)-1) update(BIT,val+1,-1) BIT = [0] * (n + 1) for j in range(n): update(BIT,j+1,1) for val in q: factq.append(Rank(val+1,BIT)-1) update(BIT,val+1,-1) carry = 0 for i in range(n - 1, -1, -1): radix = n - i factp[i] = factp[i] + factq[i] + carry if factp[i] < radix: carry = 0 else: carry = 1 factp[i] -= radix BIT = [0] * (n + 1) for j in range(n): update(BIT,j+1,1) res=[] for i in range(n): k = factp[i]+1 res.append(find(BIT,k)-1) update(BIT,res[-1]+1,-1) print(*res)
{ "input": [ "2\n0 1\n0 1\n", "2\n0 1\n1 0\n", "3\n1 2 0\n2 1 0\n" ], "output": [ "0 1 \n", "1 0 \n", "1 0 2 \n" ] }
2,443
9
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007. Input The first line of input will contain two integers n, m (3 ≀ n ≀ 100 000, 0 ≀ m ≀ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≀ ai, bi ≀ n, ai β‰  bi, <image>). Each pair of people will be described no more than once. Output Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007. Examples Input 3 0 Output 4 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 0 Output 1 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 1 Output 0 Note In the first sample, the four ways are to: * Make everyone love each other * Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
class DSU(object): def __init__(self, n): self.father = list(range(n)) self.size = n def union(self, x, s): x = self.find(x) s = self.find(s) if x == s: return self.father[s] = x self.size -= 1 def find(self, x): xf = self.father[x] if xf != x: self.father[x] = self.find(xf) return self.father[x] def is_invalid(a, b, ds): return ds.find(a) == ds.find(b) n, k = map(int, input().split()) ds = DSU(n * 2) for i in range(k): first, second, color = map(int, input().split()) first -= 1 second -= 1 if color == 0: if is_invalid(first, second, ds): print(0) exit() ds.union(first, second + n) ds.union(first + n, second) else: if is_invalid(first, second + n, ds): print(0) exit() ds.union(first, second) ds.union(first + n, second + n) sum = 1 for i in range(ds.size // 2 - 1): sum = (sum * 2) % (10 ** 9 + 7) print(sum)
{ "input": [ "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 1\n", "3 0\n", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 0\n" ], "output": [ "0\n", " 4\n", " 1\n" ] }
2,444
7
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network β€” for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety β€” in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≀ n ≀ 400, 0 ≀ m ≀ n(n - 1) / 2) β€” the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≀ u, v ≀ n, u β‰  v). You may assume that there is at most one railway connecting any two towns. Output Output one integer β€” the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
from collections import deque def put(): return map(int, input().split()) def bfs(c): q = deque() q.append(1) vis[1]=0 while q: i = q.popleft() for j in range(1, n+1): if graph[i][j]==c and vis[j]==-1: q.append(j) vis[j]=vis[i]+1 print(vis[n]) n,m = put() graph = [ [0]*(n+1) for _ in range(n+1)] vis = [-1]*(n+1) for _ in range(m): x,y = put() graph[x][y]=1 graph[y][x]=1 c = 1-graph[1][n] bfs(c)
{ "input": [ "4 2\n1 3\n3 4\n", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2\n", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n" ], "output": [ "2", "3", "-1" ] }
2,445
10
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. n friends came by, and after a typical party they decided to play blind man's buff. The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the i-th friend does not change between rounds and is equal to pi percent (as we know, it is directly proportional to the amount of alcohol consumed by the i-th friend) and p1 + p2 + ... + pn = 100 holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins. The game ends when Misha guesses every friend at least once, that is, there exists such set of rounds k1, k2, ..., kn, that during round number ki Misha caught the i-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100) β€” the number of Misha's friends. The second line contains n integers pi (<image>), giving the probability to catch the i-th friend in one particular round in percent. Output Print a single real value β€” the expectation of the number of rounds provided that Misha plays optimally. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 2 50 50 Output 5.0000000000 Input 4 50 20 20 10 Output 39.2846263444 Note The optimal strategy in the first sample is to guess friends alternately.
import random N = int(input()) prob = [float(x)/100 for x in input().strip().split()] prob_sum = [] cur = 0 for i in range(N): cur += prob[i] prob_sum.append(cur) def experiment(): cur_prob = [1.] * N cur_exp = 0 for i in range(200000): bp = [prob[i] * cur_prob[i] / (1-cur_prob[i]+1E-100) for i in range(N)] mn = max(bp) for j in range(N): if bp[j] == mn: choice = j cur_prob[choice] *= 1-prob[choice] tp = 1 for j in range(N): tp *= (1-cur_prob[j]) tp = 1 - tp cur_exp += tp return cur_exp + 1 ans = experiment() print(ans)
{ "input": [ "4\n50 20 20 10\n", "2\n50 50\n" ], "output": [ "39.284626344368\n", "5.000000000000\n" ] }
2,446
9
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied. Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance. Input The first line of the input contains two integers n and k (1 ≀ k < n ≀ 100 000) β€” the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in. Output Print the minimum possible distance between Farmer John's room and his farthest cow. Examples Input 7 2 0100100 Output 2 Input 5 1 01010 Output 2 Input 3 2 000 Output 1 Note In the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms. In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2. In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.
res = 1e9 def next(i): i += 1 while(i < N and S[i] == '1'): i += 1 return i N, K = map(int, input().split()) S = input() l = next(-1) m = l r = l for j in range(K): r = next(r) while(r < N): while(max(m - l, r - m) > max(next(m) - l, r - next(m))): m = next(m) res = min(res, max(m - l, r - m)) l = next(l) r = next(r) print(res)
{ "input": [ "3 2\n000\n", "5 1\n01010\n", "7 2\n0100100\n" ], "output": [ "1\n", "2\n", "2\n" ] }
2,447
7
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to print the n-th digit of this string (digits are numbered starting with 1. Input The only line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the position of the digit you need to print. Output Print the n-th digit of the line. Examples Input 3 Output 3 Input 11 Output 0 Note In the first sample the digit at position 3 is '3', as both integers 1 and 2 consist on one digit. In the second sample, the digit at position 11 is '0', it belongs to the integer 10.
def main(): n = int(input()) print(''.join([ str(i) for i in range(1,n+1)])[n-1]) main()
{ "input": [ "11\n", "3\n" ], "output": [ "0\n", "3\n" ] }
2,448
9
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v β‰  u, 1 ≀ w ≀ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
d={} def pro(x,y,w): res=0 while x!=y: if x<y: x,y=y,x d[x]=d.get(x,0)+w res+=d[x]; x//=2 return res q=int(input()) while q>0: q-=1 s=list(map(int,input().split())) if s[0]==1: pro(s[1],s[2],s[3]) else: print(pro(s[1],s[2],0))
{ "input": [ "7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4\n" ], "output": [ "94\n0\n32\n" ] }
2,449
7
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all. In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away. For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3. Input The first line of the input contains two integers n and t (1 ≀ n ≀ 200 000, 1 ≀ t ≀ 109) β€” the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0. Output Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes. Examples Input 6 1 10.245 Output 10.25 Input 6 2 10.245 Output 10.3 Input 3 100 9.2 Output 9.2 Note In the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect. In the third sample the optimal strategy is to not perform any rounding at all.
def main(): n,t = map(int,input().split()) b = input() p = b.find('.') for i in range(p+1,n): if b[i]>'4': break else: print(b) return while t: i-=1 t-=1 if b[i]<'4': break if i>p: print(b[:i], chr(ord(b[i])+1), sep = '') else: k = list(b[:i]) for x in range(len(k)-1,-1,-1): if k[x] == '9': k[x] = '0' else: k[x] = chr(ord(k[x])+1) break else: k.insert(0,'1') print(''.join(k)) if __name__ == '__main__': main()
{ "input": [ "6 2\n10.245\n", "3 100\n9.2\n", "6 1\n10.245\n" ], "output": [ "10.3\n", "9.2\n", "10.25\n" ] }
2,450
7
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many! Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size x Γ— y Γ— z, consisting of undestructable cells 1 Γ— 1 Γ— 1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value. All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut. Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most k times. Vasya's character uses absolutely thin sword with infinite length. Input The first line of input contains four integer numbers x, y, z, k (1 ≀ x, y, z ≀ 106, 0 ≀ k ≀ 109). Output Output the only number β€” the answer for the problem. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 2 2 3 Output 8 Input 2 2 2 1 Output 2 Note In the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two.
def main(): *l, k = map(int, input().split()) x, y, z = sorted(l) x = min(k // 3 + 1, x) y = min((k - x + 1) // 2 + 1, y) z = min(k - x - y + 3, z) print(x * y * z) if __name__ == '__main__': main()
{ "input": [ "2 2 2 1\n", "2 2 2 3\n" ], "output": [ "2\n", "8\n" ] }
2,451
7
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. <image> Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s1 with k1 elements and Morty's is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins. Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game. Input The first line of input contains a single integer n (2 ≀ n ≀ 7000) β€” number of objects in game. The second line contains integer k1 followed by k1 distinct integers s1, 1, s1, 2, ..., s1, k1 β€” Rick's set. The third line contains integer k2 followed by k2 distinct integers s2, 1, s2, 2, ..., s2, k2 β€” Morty's set 1 ≀ ki ≀ n - 1 and 1 ≀ si, 1, si, 2, ..., si, ki ≀ n - 1 for 1 ≀ i ≀ 2. Output In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. Examples Input 5 2 3 2 3 1 2 3 Output Lose Win Win Loop Loop Win Win Win Input 8 4 6 2 3 4 2 3 6 Output Win Win Win Win Win Win Win Lose Win Lose Lose Win Lose Lose
class T: h = ('Lose', 'Loop', 'Win') def __init__(t): t.s = list(map(int, input().split()))[1:] t.p = [len(t.s)] * n t.p[0] = 0 def f(t, i): for d in t.s: j = (i - d) % n if t.p[j] > 0: yield j def g(t): print(*[t.h[min(q, 1)] for q in t.p[1:]]) n = int(input()) r, m = T(), T() q = [(r, m, 0), (m, r, 0)] while q: x, y, i = q.pop() for j in y.f(i): y.p[j] = -1 for k in x.f(j): x.p[k] -= 1 if not x.p[k]: q.append((x, y, k)) r.g() m.g()
{ "input": [ "5\n2 3 2\n3 1 2 3\n", "8\n4 6 2 3 4\n2 3 6\n" ], "output": [ "Lose Win Win Loop \nLoop Win Win Win \n", "Win Win Win Win Win Win Win \nLose Win Lose Lose Win Lose Lose \n" ] }
2,452
7
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him. Input The first line contains two integers n and k (1 ≀ n, k ≀ 1018, k ≀ n) β€” the number of sticks drawn by Sasha and the number k β€” the number of sticks to be crossed out on each turn. Output If Sasha wins, print "YES" (without quotes), otherwise print "NO" (without quotes). You can print each letter in arbitrary case (upper of lower). Examples Input 1 1 Output YES Input 10 4 Output NO Note In the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins. In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't win.
def I(): return map(int, input().split()) n, k = I() print("YES" if (n//k) % 2 else "NO")
{ "input": [ "1 1\n", "10 4\n" ], "output": [ "YES\n", "NO\n" ] }
2,453
9
Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map. Formally, map is a checkered field of size 1 Γ— n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged. If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves. Help Slava to destroy all tanks using as few bombs as possible. Input The first line contains a single integer n (2 ≀ n ≀ 100 000) β€” the size of the map. Output In the first line print m β€” the minimum number of bombs Slava needs to destroy all tanks. In the second line print m integers k1, k2, ..., km. The number ki means that the i-th bomb should be dropped at the cell ki. If there are multiple answers, you can print any of them. Examples Input 2 Output 3 2 1 2 Input 3 Output 4 2 1 3 2
def solve(m): ans = [] for i in range(3): for j in range(1, n + 1): if (i - j) % 2 == 0: ans.append(j) return ans n = int(input()) x = solve(n) print(len(x)) print(*x)
{ "input": [ "3\n", "2\n" ], "output": [ "4\n2 1 3 2\n", "3\n2 1 2\n" ] }
2,454
10
Count the number of distinct sequences a1, a2, ..., an (1 ≀ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and <image>. As this number could be large, print the answer modulo 109 + 7. gcd here means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Input The only line contains two positive integers x and y (1 ≀ x, y ≀ 109). Output Print the number of such sequences modulo 109 + 7. Examples Input 3 9 Output 3 Input 5 8 Output 0 Note There are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3). There are no suitable sequences in the second test.
p=1000000007 def mul(x,y): rt=1 while y>0: if y%2==1: rt=(rt*x)%p x=(x*x)%p y=y//2 return rt x,y=map(int,input().split()) if(y%x!=0):print(0) else: y/=x d=set([]) i=1 while i*i<=y: if y%i==0: d.add(i);d.add(y/i) i+=1 d=sorted(list(d)) dp=d[::] for i in range(len(d)): dp[i]=mul(2,d[i]-1) for j in range(i): if d[i]%d[j]==0: dp[i]-=dp[j] print(dp[-1]%p)
{ "input": [ "3 9\n", "5 8\n" ], "output": [ "3\n", "0" ] }
2,455
8
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift β€” a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden. Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is Ti, each pile will reduce its volume by Ti. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other. Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day. You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day. Input The first line contains a single integer N (1 ≀ N ≀ 105) β€” the number of days. The second line contains N integers V1, V2, ..., VN (0 ≀ Vi ≀ 109), where Vi is the initial size of a snow pile made on the day i. The third line contains N integers T1, T2, ..., TN (0 ≀ Ti ≀ 109), where Ti is the temperature on the day i. Output Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i. Examples Input 3 10 10 5 5 7 2 Output 5 12 4 Input 5 30 25 20 15 10 9 10 12 4 13 Output 9 20 35 11 25 Note In the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.
from sys import stdin input = stdin.readline import heapq def f(v, t): ans=0 r=0 q=[] heapq.heapify(q) for i in range(len(v)): ans=0 heapq.heappush(q,v[i]+r) while q and q[0] <t[i]+r: ans+=heapq.heappop(q)-r ans+=len(q)*(t[i]) print(ans,end=" ") r+=t[i] n=input() l=list(map(int,input().strip().split())) d=list(map(int,input().strip().split())) f(l,d)
{ "input": [ "5\n30 25 20 15 10\n9 10 12 4 13\n", "3\n10 10 5\n5 7 2\n" ], "output": [ "9 20 35 11 25 ", "5 12 4 " ] }
2,456
10
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: <image> You have to write a program that allows you to determine what number will be in the cell with index x (1 ≀ x ≀ n) after Dima's algorithm finishes. Input The first line contains two integers n and q (1 ≀ n ≀ 1018, 1 ≀ q ≀ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers xi (1 ≀ xi ≀ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes. Output For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes. Examples Input 4 3 2 3 4 Output 3 2 4 Input 13 4 10 5 4 8 Output 13 3 8 9 Note The first example is shown in the picture. In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].
import sys [n, q] = map(int, sys.stdin.readline().strip().split()) qis = [int(sys.stdin.readline().strip()) for _ in range(q)] def query(n, q): d = 2 * n - q while d % 2 == 0: d //= 2 return (n - d // 2) for qi in qis: print (query(n, qi))
{ "input": [ "4 3\n2\n3\n4\n", "13 4\n10\n5\n4\n8\n" ], "output": [ "3\n2\n4\n", "13\n3\n8\n9\n" ] }
2,457
7
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list. Mishka cannot solve a problem with difficulty greater than k. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by 1. Mishka stops when he is unable to solve any problem from any end of the list. How many problems can Mishka solve? Input The first line of input contains two integers n and k (1 ≀ n, k ≀ 100) β€” the number of problems in the contest and Mishka's problem-solving skill. The second line of input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 100), where a_i is the difficulty of the i-th problem. The problems are given in order from the leftmost to the rightmost in the list. Output Print one integer β€” the maximum number of problems Mishka can solve. Examples Input 8 4 4 2 3 1 5 1 6 4 Output 5 Input 5 2 3 1 2 1 3 Output 0 Input 5 100 12 34 55 43 21 Output 5 Note In the first example, Mishka can solve problems in the following order: [4, 2, 3, 1, 5, 1, 6, 4] β†’ [2, 3, 1, 5, 1, 6, 4] β†’ [2, 3, 1, 5, 1, 6] β†’ [3, 1, 5, 1, 6] β†’ [1, 5, 1, 6] β†’ [5, 1, 6], so the number of solved problems will be equal to 5. In the second example, Mishka can't solve any problem because the difficulties of problems from both ends are greater than k. In the third example, Mishka's solving skill is so amazing that he can solve all the problems.
def I(): return map(int, input().split()) n, k = I() a = list(I()) while a: if a[0] <= k: a.pop(0) elif a[-1] <= k: a.pop(-1) else: break print(n - len(a))
{ "input": [ "5 2\n3 1 2 1 3\n", "8 4\n4 2 3 1 5 1 6 4\n", "5 100\n12 34 55 43 21\n" ], "output": [ "0\n", "5\n", "5\n" ] }
2,458
8
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise OR of a and b, you need to find the number of ways of swapping two bits in a so that bitwise OR will not be equal to c. Note that binary numbers can contain leading zeros so that length of each number is exactly n. [Bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation#OR) is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, 01010_2 OR 10011_2 = 11011_2. Well, to your surprise, you are not Rudolf, and you don't need to help him… You are the security staff! Please find the number of ways of swapping two bits in a so that bitwise OR will be changed. Input The first line contains one integer n (2≀ n≀ 10^5) β€” the number of bits in each number. The second line contains a binary number a of length n. The third line contains a binary number b of length n. Output Print the number of ways to swap two bits in a so that bitwise OR will be changed. Examples Input 5 01011 11001 Output 4 Input 6 011000 010011 Output 6 Note In the first sample, you can swap bits that have indexes (1, 4), (2, 3), (3, 4), and (3, 5). In the second example, you can swap bits that have indexes (1, 2), (1, 3), (2, 4), (3, 4), (3, 5), and (3, 6).
def main(): n, c = int(input()), [0] * 4 for a, b in zip(*(map(int, input()) for _ in 'ab')): c[a + b * 2] += 1 print(c[1] * (c[0] + c[2]) + c[3] * c[0]) if __name__ == '__main__': main()
{ "input": [ "6\n011000\n010011\n", "5\n01011\n11001\n" ], "output": [ "6\n", "4\n" ] }
2,459
10
This is an interactive problem. In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI. The subway of the Metropolis is one line (regular straight line with no self-intersections) with n stations, indexed consecutively from 1 to n. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured. To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers l and r (l ≀ r), and then check, whether the train is located on a station with index between l and r, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most k stations away. Formally, if the train was at the station x when the gadget was applied, then at the next application of the gadget the train can appear at any station y such that max(1, x - k) ≀ y ≀ min(n, x + k). Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan. After an examination of the gadget you found that it is very old and can hold no more than 4500 applications, after which it will break and your mission will be considered a failure. Can you find the station with the train using no more than 4500 applications of the gadgets? Input The first line contains two integers n and k (1 ≀ n ≀ 10^{18}, 0 ≀ k ≀ 10) β€” the number of stations and the maximum number of stations the train can move between two applications of the gadget. Interaction You can apply the gadget at most 4500 times. In order to apply the gadget you need to print two space-separated integers l and r (1 ≀ l ≀ r ≀ n). You will then receive either string "Yes", if the train is between stations l and r, inclusive, or string "No" otherwise. If l = r and you received "Yes", then you found the train successfully, and your program must halt immediately. Answer "Bad" instead of "Yes" or "No" means that you made an invalid query or made too many queries. Exit immediately after receiving "Bad" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream. After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Hacks In order to hack, you should present a test in the following format. The first line should contain three integers n, k and p (1 ≀ n ≀ 10^{18}, 0 ≀ k ≀ 10, 1 ≀ p ≀ n) β€” the number of stations, the maximum number of stations the train can move between two applications of the gadget and the initial position of the train, respectively. Each of the next 4500 lines should contain a single integer x (1 ≀ x ≀ n) β€” the positions of the train after each query. Two consecutive positions (including the initial one) should not differ by more than k. For example, the following lines are the first lines of the sample test. 10 2 5 5 3 5 7 7 ... Example Input 10 2 Yes No Yes Yes Output 3 5 3 3 3 4 5 5 Note In the first sample, the train was initially at the station 5, after the first application of the gadget it did not move, after the second application it moved to the station 3, and after the third application moved again to the station 5.
from random import randint import sys def ask(l, r): print(l, r) sys.stdout.flush() a = input() return a == "Yes" n, k = map(int, input().split()) l, r = 1, n while True: if r - l < 61: x = randint(l, r) if ask(x, x): exit(0) else: m = (l + r) // 2 if ask(l, m): r = m else: l = m + 1 l, r = max(l - k, 1), min(r + k, n)
{ "input": [ "10 2\n\nYes\n\nNo\n\nYes\n\nYes\n" ], "output": [ "2 2\n" ] }
2,460
9
The Squareland national forest is divided into equal 1 Γ— 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C in the forest. Initially, all plots in the forest (including the plots A, B, C) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots A, B, C from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side. <image> For example, A=(0,0), B=(1,1), C=(2,2). The minimal number of plots to be cleared is 5. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees. Input The first line contains two integers x_A and y_A β€” coordinates of the plot A (0 ≀ x_A, y_A ≀ 1000). The following two lines describe coordinates (x_B, y_B) and (x_C, y_C) of plots B and C respectively in the same format (0 ≀ x_B, y_B, x_C, y_C ≀ 1000). It is guaranteed that all three plots are distinct. Output On the first line print a single integer k β€” the smallest number of plots needed to be cleaned from trees. The following k lines should contain coordinates of all plots needed to be cleaned. All k plots should be distinct. You can output the plots in any order. If there are multiple solutions, print any of them. Examples Input 0 0 1 1 2 2 Output 5 0 0 1 0 1 1 1 2 2 2 Input 0 0 2 0 1 1 Output 4 0 0 1 0 1 1 2 0 Note The first example is shown on the picture in the legend. The second example is illustrated with the following image: <image>
def solve(x1, x2, y1, y2): ans.add((x1, y1)) while x1 != x2 or y1 != y2: if x1 < x2: x1 += 1 ans.add((x1, y1)) elif x1 > x2: x1 -= 1 ans.add((x1, y1)) if y1 < y2: y1 += 1 ans.add((x1, y1)) elif y1 > y2: y1 -= 1 ans.add((x1, y1)) x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) x3, y3 = map(int, input().split()) ans = set() x = sorted([x1, x2, x3])[1] y = sorted([y1, y2, y3])[1] solve(x, x1, y, y1) solve(x, x2, y, y2) solve(x, x3, y, y3) print(len(ans)) for row in ans: print(*row)
{ "input": [ "0 0\n1 1\n2 2\n", "0 0\n2 0\n1 1\n" ], "output": [ "5\n0 0\n1 0\n1 1\n1 2\n2 2\n", "4\n0 0\n1 0\n1 1\n2 0\n" ] }
2,461
7
Salem gave you n sticks with integer positive lengths a_1, a_2, …, a_n. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x. A stick length a_i is called almost good for some integer t if |a_i - t| ≀ 1. Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer t and the total cost of changing is minimum possible. The value of t is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of t and the minimum cost. If there are multiple optimal choices for t, print any of them. Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of sticks. The second line contains n integers a_i (1 ≀ a_i ≀ 100) β€” the lengths of the sticks. Output Print the value of t and the minimum possible cost. If there are multiple optimal choices for t, print any of them. Examples Input 3 10 1 4 Output 3 7 Input 5 1 1 2 2 3 Output 2 0 Note In the first example, we can change 1 into 2 and 10 into 4 with cost |1 - 2| + |10 - 4| = 1 + 6 = 7 and the resulting lengths [2, 4, 4] are almost good for t = 3. In the second example, the sticks lengths are already almost good for t = 2, so we don't have to do anything.
n=int(input()) ar=list(map(int,input().split())) def f(i): ans=0 for e in ar: if(e==i):continue else:ans+=abs(e-i)-1 return ans a=float('inf') b=0 for x in range(1,1001): if(f(x)<a): a=f(x) b=x print(b,a)
{ "input": [ "3\n10 1 4\n", "5\n1 1 2 2 3\n" ], "output": [ "3 7\n", "2 0\n" ] }
2,462
11
Let's define a function f(p) on a permutation p as follows. Let g_i be the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of elements p_1, p_2, ..., p_i (in other words, it is the GCD of the prefix of length i). Then f(p) is the number of distinct elements among g_1, g_2, ..., g_n. Let f_{max}(n) be the maximum value of f(p) among all permutations p of integers 1, 2, ..., n. Given an integers n, count the number of permutations p of integers 1, 2, ..., n, such that f(p) is equal to f_{max}(n). Since the answer may be large, print the remainder of its division by 1000 000 007 = 10^9 + 7. Input The only line contains the integer n (2 ≀ n ≀ 10^6) β€” the length of the permutations. Output The only line should contain your answer modulo 10^9+7. Examples Input 2 Output 1 Input 3 Output 4 Input 6 Output 120 Note Consider the second example: these are the permutations of length 3: * [1,2,3], f(p)=1. * [1,3,2], f(p)=1. * [2,1,3], f(p)=2. * [2,3,1], f(p)=2. * [3,1,2], f(p)=2. * [3,2,1], f(p)=2. The maximum value f_{max}(3) = 2, and there are 4 permutations p such that f(p)=2.
p=10**9+7 import math def r(l): x=1 for m in l: x=x*m%p return x n=int(input()) a,k,x,t=[],int(math.log2(n)),n,0 while x>0: a.append(x-x//2) x//=2 b=[n//(3*2**i)-n//(6*2**i) for i in range(k+1)] d=[n//2**i-n//(3*2**i) for i in range(k+1)] y=r(i for i in range(2,n+1)) s=k if n<3*2**(k-1) else 0 for j in range(s,k+1): e=[a[i] for i in range(j)]+[d[j]]+[b[i] for i in range(j,k)] x=y*r(e)%p f=r(sum(e[:i+1]) for i in range(k+1)) while f>1: x*=p//f+1 f=f*(p//f+1)%p t+=x%p print(t%p)
{ "input": [ "2\n", "3\n", "6\n" ], "output": [ "1\n", "4\n", "120\n" ] }
2,463
9
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him? You're given a tree β€” a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself. Each vertex v is assigned its beauty x_v β€” a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u. Your task is to find the sum $$$ βˆ‘_{u is an ancestor of v} f(u, v). $$$ As the result might be too large, please output it modulo 10^9 + 7. Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0. Input The first line contains a single integer n (2 ≀ n ≀ 100 000) β€” the number of vertices in the tree. The following line contains n integers x_1, x_2, ..., x_n (0 ≀ x_i ≀ 10^{12}). The value x_v denotes the beauty of vertex v. The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 ≀ a, b ≀ n, a β‰  b) β€” the vertices connected by a single edge. Output Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7. Examples Input 5 4 5 6 0 8 1 2 1 3 1 4 4 5 Output 42 Input 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 Output 30 Note The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42: <image>
from math import gcd from collections import deque from bisect import bisect_left from sys import setrecursionlimit MOD = 1000000007 def main(): n = int(input()) setrecursionlimit(n+100) xx = [0] + [int(x) for x in input().split()] edges = [] neighbors = [[] for _ in range(n+1)] for _ in range(n-1): v1, v2 = [int(x) for x in input().split()] neighbors[v1].append(v2) neighbors[v2].append(v1) visited = [False] * (n+1) dq = deque() dq.append((1,[])) sum = 0 while dq: u,gcds = dq.popleft() gcdns = [[xx[u], 1]] sum = (sum + xx[u]) % MOD for g, c in gcds: gcdn = gcd(xx[u], g) sum = (sum + gcdn*c) % MOD if gcdn == gcdns[-1][0]: gcdns[-1][1] += c else: gcdns.append([gcdn, c]) visited[u] = True for v in neighbors[u]: if not visited[v]: dq.append((v, gcdns)) print(sum) if __name__ == "__main__": main()
{ "input": [ "7\n0 2 3 0 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n", "5\n4 5 6 0 8\n1 2\n1 3\n1 4\n4 5\n" ], "output": [ "30\n", "42\n" ] }
2,464
9
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them! A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≀ a ≀ b ≀ n). For example, "auto" and "ton" are substrings of "automaton". Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only k Latin letters c_1, c_2, …, c_k out of 26. After that, Norge became interested in how many substrings of the string s he could still type using his broken keyboard. Help him to find this number. Input The first line contains two space-separated integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 26) β€” the length of the string s and the number of Latin letters still available on the keyboard. The second line contains the string s consisting of exactly n lowercase Latin letters. The third line contains k space-separated distinct lowercase Latin letters c_1, c_2, …, c_k β€” the letters still available on the keyboard. Output Print a single number β€” the number of substrings of s that can be typed using only available letters c_1, c_2, …, c_k. Examples Input 7 2 abacaba a b Output 12 Input 10 3 sadfaasdda f a d Output 21 Input 7 1 aaaaaaa b Output 0 Note In the first example Norge can print substrings s[1…2], s[2…3], s[1…3], s[1…1], s[2…2], s[3…3], s[5…6], s[6…7], s[5…7], s[5…5], s[6…6], s[7…7].
def cal(x): return x*(x+1)//2 n,k=map(int,input().split()) s=input() s+='0' l=input().split() r,x=0,-1 for i in range(n+1): if s[i] not in l: r+=cal(i-x-1) x=i print(r)
{ "input": [ "7 2\nabacaba\na b\n", "10 3\nsadfaasdda\nf a d\n", "7 1\naaaaaaa\nb\n" ], "output": [ "12\n", "21\n", "0\n" ] }
2,465
10
You are given two integers a and m. Calculate the number of integers x such that 0 ≀ x < m and \gcd(a, m) = \gcd(a + x, m). Note: \gcd(a, b) is the greatest common divisor of a and b. Input The first line contains the single integer T (1 ≀ T ≀ 50) β€” the number of test cases. Next T lines contain test cases β€” one per line. Each line contains two integers a and m (1 ≀ a < m ≀ 10^{10}). Output Print T integers β€” one per test case. For each test case print the number of appropriate x-s. Example Input 3 4 9 5 10 42 9999999967 Output 6 1 9999999966 Note In the first test case appropriate x-s are [0, 1, 3, 4, 6, 7]. In the second test case the only appropriate x is 0.
import math t = int(input()) def phi(n): res = n i = 2 while i*i<=n: if n%i==0: res/=i res*=(i-1) while n%i==0: n/=i i+=1 if n>1: res/=n res*=(n-1) return int(res) while t: a,m = list(map(int,input().split())) g = math.gcd(a,m) print(phi(m//g)) t-=1
{ "input": [ "3\n4 9\n5 10\n42 9999999967\n" ], "output": [ "6\n1\n9999999966\n" ] }
2,466
10
Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the nΓ— n board. Rows and columns of this board are numbered from 1 to n. The cell on the intersection of the r-th row and c-th column is denoted by (r, c). Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 5 characters β€” U, D, L, R or X β€” instructions for the player. Suppose that the current cell is (r, c). If the character is R, the player should move to the right cell (r, c+1), for L the player should move to the left cell (r, c-1), for U the player should move to the top cell (r-1, c), for D the player should move to the bottom cell (r+1, c). Finally, if the character in the cell is X, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on). It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts. As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long. For every of the n^2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r, c) she wrote: * a pair (x,y), meaning if a player had started at (r, c), he would end up at cell (x,y). * or a pair (-1,-1), meaning if a player had started at (r, c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them. Input The first line of the input contains a single integer n (1 ≀ n ≀ 10^{3}) β€” the side of the board. The i-th of the next n lines of the input contains 2n integers x_1, y_1, x_2, y_2, ..., x_n, y_n, where (x_j, y_j) (1 ≀ x_j ≀ n, 1 ≀ y_j ≀ n, or (x_j,y_j)=(-1,-1)) is the pair written by Alice for the cell (i, j). Output If there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the i-th of the next n lines, print the string of n characters, corresponding to the characters in the i-th row of the suitable board you found. Each character of a string can either be U, D, L, R or X. If there exist several different boards that satisfy the provided information, you can find any of them. Examples Input 2 1 1 1 1 2 2 2 2 Output VALID XL RX Input 3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 Output VALID RRD UXD ULL Note For the sample test 1 : The given grid in output is a valid one. * If the player starts at (1,1), he doesn't move any further following X and stops there. * If the player starts at (1,2), he moves to left following L and stops at (1,1). * If the player starts at (2,1), he moves to right following R and stops at (2,2). * If the player starts at (2,2), he doesn't move any further following X and stops there. The simulation can be seen below : <image> For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2), he wouldn't have moved further following instruction X . The simulation can be seen below : <image>
from collections import deque N = int(input()) m = [[None]*N for i in range(N)] v = [[False]*N for i in range(N)] for i in range(N): r = list(map(int, input().split())) for j in range(N): x, y = r[2*j] - 1, r[2*j + 1] - 1 m[i][j] = (x, y) def bfs(x, y): # x, y is the coordinate of our input q = deque() q.append((x, y)) while len(q): x, y = q.popleft() for i, j, d in [(x - 1, y, 'D'), (x + 1, y, 'U'), (x, y - 1, 'R'), (x, y + 1, 'L')]: if i != -1 and i != N and j != -1 and j != N: if m[i][j] != m[x][y]: continue if not v[i][j]: v[i][j] = d q.append((i, j)) for i in range(N): for j in range(N): if m[i][j] == (i, j): v[i][j] = 'X' bfs(i, j) elif m[i][j] == (-2, -2): for a, b, nxt, prev in [(i - 1, j, 'U', 'D'), (i + 1, j, 'D', 'U'), (i, j - 1,'L', 'R'), (i, j + 1, 'R', 'L')]: if a != -1 and a != N and b != -1 and b != N: if m[i][j] != m[a][b]: continue else: v[i][j] = nxt v[a][b] = prev break for i in range(N): for j in range(N): if not v[i][j]: print('INVALID') exit() print('VALID') print('\n'.join([''.join(r) for r in v]))
{ "input": [ "3\n-1 -1 -1 -1 -1 -1\n-1 -1 2 2 -1 -1\n-1 -1 -1 -1 -1 -1\n", "2\n1 1 1 1\n2 2 2 2\n" ], "output": [ "VALID\nDRD\nDXD\nURU\n", "VALID\nXL\nRX\n" ] }
2,467
7
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division. To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that: * p_i is divisible by x_i; * x_i is not divisible by q_i. Oleg is really good at division and managed to find all the answers quickly, how about you? Input The first line contains an integer t (1 ≀ t ≀ 50) β€” the number of pairs. Each of the following t lines contains two integers p_i and q_i (1 ≀ p_i ≀ 10^{18}; 2 ≀ q_i ≀ 10^{9}) β€” the i-th pair of integers. Output Print t integers: the i-th integer is the largest x_i such that p_i is divisible by x_i, but x_i is not divisible by q_i. One can show that there is always at least one value of x_i satisfying the divisibility conditions for the given constraints. Example Input 3 10 4 12 6 179 822 Output 10 4 179 Note For the first pair, where p_1 = 10 and q_1 = 4, the answer is x_1 = 10, since it is the greatest divisor of 10 and 10 is not divisible by 4. For the second pair, where p_2 = 12 and q_2 = 6, note that * 12 is not a valid x_2, since 12 is divisible by q_2 = 6; * 6 is not valid x_2 as well: 6 is also divisible by q_2 = 6. The next available divisor of p_2 = 12 is 4, which is the answer, since 4 is not divisible by 6.
def solve(): l=[] j=2 z=q while j*j<=z: if(z%j==0): l.append(j) while z%j==0: z//=j j+=1 if(z>1): l.append(z) return l for _ in range(int(input())): p,q=map(int,input().split()) l=solve() x=1 for s in l: a=p while a%q==0: a//=s x=max(x,a) print(x)
{ "input": [ "3\n10 4\n12 6\n179 822\n" ], "output": [ "10\n4\n179\n" ] }
2,468
8
Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue. After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence r consisted of all red elements of a in the order they appeared in a; similarly, the sequence b consisted of all blue elements of a in the order they appeared in a as well. Unfortunately, the original sequence was lost, and Monocarp only has the sequences r and b. He wants to restore the original sequence. In case there are multiple ways to restore it, he wants to choose a way to restore that maximizes the value of $$$f(a) = max(0, a_1, (a_1 + a_2), (a_1 + a_2 + a_3), ..., (a_1 + a_2 + a_3 + ... + a_{n + m}))$$$ Help Monocarp to calculate the maximum possible value of f(a). Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case consists of four lines. The first line of each test case contains one integer n (1 ≀ n ≀ 100). The second line contains n integers r_1, r_2, ..., r_n (-100 ≀ r_i ≀ 100). The third line contains one integer m (1 ≀ m ≀ 100). The fourth line contains m integers b_1, b_2, ..., b_m (-100 ≀ b_i ≀ 100). Output For each test case, print one integer β€” the maximum possible value of f(a). Example Input 4 4 6 -5 7 -3 3 2 3 -4 2 1 1 4 10 -3 2 2 5 -1 -2 -3 -4 -5 5 -1 -2 -3 -4 -5 1 0 1 0 Output 13 13 0 0 Note In the explanations for the sample test cases, red elements are marked as bold. In the first test case, one of the possible sequences a is [6, 2, -5, 3, 7, -3, -4]. In the second test case, one of the possible sequences a is [10, 1, -3, 1, 2, 2]. In the third test case, one of the possible sequences a is [-1, -1, -2, -3, -2, -4, -5, -3, -4, -5]. In the fourth test case, one of the possible sequences a is [0, 0].
def maxsum(l): m=0 c=0 for i in l: c+=i m=max(c,m) return m for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) m=int(input()) b=list(map(int,input().split())) print(maxsum(a)+maxsum(b))
{ "input": [ "4\n4\n6 -5 7 -3\n3\n2 3 -4\n2\n1 1\n4\n10 -3 2 2\n5\n-1 -2 -3 -4 -5\n5\n-1 -2 -3 -4 -5\n1\n0\n1\n0\n" ], "output": [ "\n13\n13\n0\n0\n" ] }
2,469
10
The Dogeforces company has k employees. Each employee, except for lower-level employees, has at least 2 subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates. The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company. Input The first line contains a single integer n (2 ≀ n ≀ 500) β€” the number of lower-level employees. This is followed by n lines, where i-th line contains n integers a_{i,1}, a_{i,2}, ..., a_{i,n} (1 ≀ a_{i,j} ≀ 5000) β€” salary of the common supervisor of employees with numbers i and j. It is guaranteed that a_{i,j} = a_{j,i}. Note that a_{i,i} is equal to the salary of the i-th employee. Output In the first line, print a single integer k β€” the number of employees in the company. In the second line, print k integers c_1, c_2, ..., c_k, where c_i is the salary of the employee with the number i. In the third line, print a single integer r β€” the number of the employee who is the head of the company. In the following k-1 lines, print two integers v and u (1 ≀ v, u ≀ k) β€” the number of the employee and his direct supervisor. Note that the lower-level employees have numbers from 1 to n, and for the rest of the employees, you have to assign numbers from n+1 to k. If there are several correct company structures, you can print any of them. Example Input 3 2 5 7 5 1 7 7 7 4 Output 5 2 1 4 7 5 4 1 5 2 5 5 4 3 4 Note One of the possible structures in the first example: <image>
t = int(input());a = [None for _ in range(t)];res = [];parents = [] for i in range(t): a[i] = list(map(int, input().split())); res.append(a[i][i]) def split(ids): if len(ids) == 1: return ids[0] + 1 groups = []; d = set(ids); mx = max([x for i, x in enumerate(a[ids[0]]) if i in d]); res.append(mx); cur = len(res) for id in ids: found = False for group in groups: if a[group[0]][id] < mx: group.append(id); found = True; break if not found: groups.append([id]) for group in groups: parents.append([split(group), cur]) return cur chief = split([i for i in range(t)]) print(len(res));print(*res, sep=' ');print(chief) for r in parents: print(*r, sep=' ')
{ "input": [ "3\n2 5 7\n5 1 7\n7 7 4\n" ], "output": [ "\n5\n2 1 4 7 5 \n4\n1 5\n2 5\n5 4\n3 4\n" ] }
2,470
9
Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it: Consider an n by n chessboard. Its rows are numbered from 1 to n from the top to the bottom. Its columns are numbered from 1 to n from the left to the right. A cell on an intersection of x-th row and y-th column is denoted (x, y). The main diagonal of the chessboard is cells (x, x) for all 1 ≀ x ≀ n. A permutation of \{1, 2, 3, ..., n\} is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly 1+2+ … +n such cells) into n connected regions satisfying the following constraints: 1. Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell. 2. The x-th region should contain cell on the main diagonal with number x for all 1≀ x≀ n. 3. The number of cells that belong to the x-th region should be equal to x for all 1≀ x≀ n. 4. Each cell under and on the main diagonal should belong to exactly one region. Input The first line contains a single integer n (1≀ n ≀ 500) denoting the size of the chessboard. The second line contains n integers p_1, p_2, ..., p_n. p_i is the number written on cell (i, i). It is guaranteed that each integer from \{1, …, n\} appears exactly once in p_1, ..., p_n. Output If no solution exists, output -1. Otherwise, output n lines. The i-th line should contain i numbers. The j-th number on the i-th line should be x if cell (i, j) belongs to the the region with x cells. Examples Input 3 2 3 1 Output 2 2 3 3 3 1 Input 5 1 2 3 4 5 Output 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Note The solutions to the examples are illustrated in the following pictures: <image> <image>
n=int(input()) a=list(map(int,input().split())) ans=[[-1]*n for i in range(n)] def yo(ans,temp,k,i,j): if temp==1: return if j-1>=0 and ans[i][j-1]==-1: ans[i][j-1]=k yo(ans,temp-1,k,i,j-1) elif i+1<n: ans[i+1][j]=k yo(ans,temp-1,k,i+1,j) for k in range(n): ans[k][k]=a[k] yo(ans,a[k],a[k],k,k) temp=0 for i in ans: print(*i[:temp+1]) temp+=1
{ "input": [ "3\n2 3 1\n", "5\n1 2 3 4 5\n" ], "output": [ "\n2\n2 3\n3 3 1\n", "\n1\n2 2\n3 3 3\n4 4 4 4\n5 5 5 5 5\n" ] }
2,471
8
Cirno gave AquaMoon a chessboard of size 1 Γ— n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≀ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 β‰₯ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10 000) β€” the number of test cases. The first line contains a single integer n (1 ≀ n ≀ 10^5) β€” the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
def ncr(n,r,p): num,den=1,1 for i in range(r): num=(num*(n-i))%p den=(den*(i+1))%p return (num*pow(den,p-2,p))%p p=998244353 t=int(input()) for i in range(t): n=int(input()) zoz=input() z=zoz.count("0") k=0 j=1 while j<n: if zoz[j]=="1" and zoz[j-1]=="1": k+=1 j+=2 else: j+=1 print(ncr(z+k,z,p))
{ "input": [ "6\n4\n0110\n6\n011011\n5\n01010\n20\n10001111110110111000\n20\n00110110100110111101\n20\n11101111011000100010\n" ], "output": [ "3\n6\n1\n1287\n1287\n715\n" ] }
2,472
7
Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789".
import sys def main(): _, *l = sys.stdin.read().strip().split('\n') c = 0 for i in zip(*l): if len(set(i)) != 1: break c += 1 return c print(main())
{ "input": [ "4\n00209\n00219\n00999\n00909\n", "2\n1\n2\n", "3\n77012345678999999999\n77012345678901234567\n77012345678998765432\n" ], "output": [ "2\n", "0\n", "12\n" ] }
2,473
8
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously. In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles. The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible. Input The first line contains integer n (1 ≀ n ≀ 103) β€” the boulevard's length in tiles. The second line contains n space-separated integers ai β€” the number of days after which the i-th tile gets destroyed (1 ≀ ai ≀ 103). Output Print a single number β€” the sought number of days. Examples Input 4 10 3 5 10 Output 5 Input 5 10 2 8 3 5 Output 5 Note In the first sample the second tile gets destroyed after day three, and the only path left is 1 β†’ 3 β†’ 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it. In the second sample path 1 β†’ 3 β†’ 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.
def main(): input() aa = list(map(int, input().split())) l, a = [aa[-1]], aa[0] for b in aa: l.append(a if a > b else b) a = b print(min(l)) if __name__ == '__main__': main()
{ "input": [ "5\n10 2 8 3 5\n", "4\n10 3 5 10\n" ], "output": [ "5\n", "5\n" ] }
2,474
8
One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people. We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A. The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench. Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last. Input The first line contains two integers n and m (2 ≀ n ≀ 100, 1 ≀ m ≀ 100) β€” the number of students and the number of pairs of archenemies correspondingly. Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi) β€” the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies. You can consider the students indexed in some manner with distinct integers from 1 to n. Output Print a single integer β€” the minimum number of students you will have to send to the bench in order to start the game. Examples Input 5 4 1 2 2 4 5 3 1 4 Output 1 Input 6 2 1 4 3 4 Output 0 Input 6 6 1 2 2 3 3 1 4 5 5 6 6 4 Output 2
n,m=map(int,input().split()) a=[[0]*(n+1) for i in range(n+1)] for _ in range(m): u,v=map(int,input().split()) a[u][v]=1 a[v][u]=1 d=[-1]*(n+1) def dfs(i,v): d[i]=v for j in range(1,n+1): if a[i][j] and d[j]==-1: dfs(j,1-v) for i in range(1,n+1): if d[i]==-1: dfs(i,1) res=0 for i in range(1,n+1): for j in range(i+1,n+1): if a[i][j] and d[i]==d[j]: res+=1 if (n-res)%2: print(res+1) else: print(res)
{ "input": [ "6 2\n1 4\n3 4\n", "5 4\n1 2\n2 4\n5 3\n1 4\n", "6 6\n1 2\n2 3\n3 1\n4 5\n5 6\n6 4\n" ], "output": [ "0", "1", "2" ] }
2,475
8
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount of people that could stay at the party in the end? Input The first input line contains one number t β€” amount of tests (1 ≀ t ≀ 105). Each of the following t lines contains one integer number n (1 ≀ n ≀ 105). Output For each test output in a separate line one number β€” the maximum amount of people that could stay in the end. Examples Input 1 3 Output 1
def party(lst): a = list() for i in range(len(lst)): if lst[i] < 3: a.append(0) else: a.append(lst[i] - 2) return a t = int(input()) c = list() for i in range(t): numb = int(input()) c.append(numb) print(*party(c), sep='\n')
{ "input": [ "1\n3\n" ], "output": [ "1\n" ] }
2,476
8
One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively. Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2 - 1, inclusive. On the day number i the following things happened: 1. The fly arrived at the coordinate plane at the center of the circle with number <image> (<image> is the result of dividing number x by number y, rounded down to an integer). 2. The fly went along the coordinate plane to the center of the circle number <image> (<image> is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction. Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days. Input The first line contains two integers m, R (1 ≀ m ≀ 105, 1 ≀ R ≀ 10). Output In a single line print a single real number β€” the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. Examples Input 1 1 Output 2.0000000000 Input 2 2 Output 5.4142135624 Note <image> Figure to the second sample
m, r = map(int, input().split()) def calc(k): if k < 1: return 0 else: return (1 + 2 * (k - 1)) * 2**0.5 + k * 2 + (k - 1) * (k - 2) avg = 0 div = m ** 2 for i in range(0, m): avg += r * (2 + calc(i) + calc(m - 1 - i)) / div print(avg)
{ "input": [ "1 1\n", "2 2\n" ], "output": [ "2.00000000", "5.41421356" ] }
2,477
9
Simon has a prime number x and an array of non-negative integers a1, a2, ..., an. Simon loves fractions very much. Today he wrote out number <image> on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: <image>, where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). Input The first line contains two positive integers n and x (1 ≀ n ≀ 105, 2 ≀ x ≀ 109) β€” the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≀ a1 ≀ a2 ≀ ... ≀ an ≀ 109). Output Print a single number β€” the answer to the problem modulo 1000000007 (109 + 7). Examples Input 2 2 2 2 Output 8 Input 3 3 1 2 3 Output 27 Input 2 2 29 29 Output 73741817 Input 4 5 0 0 0 0 Output 1 Note In the first sample <image>. Thus, the answer to the problem is 8. In the second sample, <image>. The answer to the problem is 27, as 351 = 13Β·27, 729 = 27Β·27. In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817. In the fourth sample <image>. Thus, the answer to the problem is 1.
def Solve(x, a_i): v = max(a_i) count = a_i.count(v) A = sum(a_i) s = A - v while count % x == 0: s +=1 v -= 1 count += count//x + a_i.count(v) return pow(x, min(s, A), 1000000007) n, x = map(int, input().split()) a_i = list(map(int, input().split())) print(Solve(x, a_i))
{ "input": [ "3 3\n1 2 3\n", "4 5\n0 0 0 0\n", "2 2\n2 2\n", "2 2\n29 29\n" ], "output": [ "27\n", "1\n", "8\n", "73741817\n" ] }
2,478
8
Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers a, b, w, x (0 ≀ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: c = c - 1. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if b β‰₯ x, perform the assignment b = b - x, if b < x, then perform two consecutive assignments a = a - 1; b = w - (x - b). You've got numbers a, b, w, x, c. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if c ≀ a. Input The first line contains integers a, b, w, x, c (1 ≀ a ≀ 2Β·109, 1 ≀ w ≀ 1000, 0 ≀ b < w, 0 < x < w, 1 ≀ c ≀ 2Β·109). Output Print a single integer β€” the minimum time in seconds Alexander needs to get ahead of Arthur. You can prove that the described situation always occurs within the problem's limits. Examples Input 4 2 3 1 6 Output 2 Input 4 2 3 1 7 Output 4 Input 1 2 3 2 6 Output 13 Input 1 1 2 1 1 Output 0
a, b, w, x, c = map(int, input().split()) def result(a, b, w, x, c, s): na = a - (s * x - b) / w nc = c - s return (na, nc) def solve(a, b, w, x, c): left = 0 right = 10e15 if (c <= a): return 0 while (left < right): half = (left+right) // 2 ret = result(a, b, w, x, c, half) if (ret[1] <= ret[0]): right = half else: left = half + 1 return left print(int(solve(a, b, w, x, c)))
{ "input": [ "4 2 3 1 7\n", "1 1 2 1 1\n", "4 2 3 1 6\n", "1 2 3 2 6\n" ], "output": [ "4\n", "0\n", "2\n", "13\n" ] }
2,479
7
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≀ k ≀ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≀ t ≀ 5) β€” the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≀ n ≀ 24; p β‰₯ 0; <image>) β€” the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≀ ai, bi ≀ n; ai β‰  bi) β€” two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6
import sys def compute(n,p): count=0 for i in range(1,n+1,1): for j in range(i+1,n+1,1): print('{0} {1}'.format(i,j)) count += 1 if(count >= (2*n+p)): return t = int(input()) for case in range(t): n,p = list(map(int,input().split())) compute(n,p)
{ "input": [ "1\n6 0\n" ], "output": [ "1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n" ] }
2,480
8
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color. For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls. Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy. Input The first line of input contains three integers: n (1 ≀ n ≀ 100), k (1 ≀ k ≀ 100) and x (1 ≀ x ≀ k). The next line contains n space-separated integers c1, c2, ..., cn (1 ≀ ci ≀ k). Number ci means that the i-th ball in the row has color ci. It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color. Output Print a single integer β€” the maximum number of balls Iahub can destroy. Examples Input 6 2 2 1 1 2 2 1 1 Output 6 Input 1 1 1 1 Output 0
def solve(a): for i in range(len(a)-1): j = i + 1 while j < len(a) and a[j] == a[i]: j += 1 num = j - i if num >= 3: return num + solve(a[:i] + a[j:]) return 0 n, k, x = [int(x) for x in input().split()] c = [int(x) for x in input().split()] best = 0 for i in range(len(c)): if c[i] == x: best = max(best, solve(c[:i] + [x] + c[i:])-1) print(best)
{ "input": [ "1 1 1\n1\n", "6 2 2\n1 1 2 2 1 1\n" ], "output": [ "0", "6" ] }
2,481
9
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
def read(): return map(int, input().split()) x1, y1 = read() x2, y2 = read() n, = read() ans = 0 for _ in range(n): ai, bi, ci = read() home = ai * x1 + bi * y1 + ci uni = ai * x2 + bi * y2 + ci if (home // abs(home)) * (uni // abs(uni)) < 0: ans += 1 print(ans)
{ "input": [ "1 1\n-1 -1\n2\n0 1 0\n1 0 0\n", "1 1\n-1 -1\n3\n1 0 0\n0 1 0\n1 1 -3\n" ], "output": [ "2", "2" ] }
2,482
10
You are given sequence a1, a2, ..., an and m queries lj, rj (1 ≀ lj ≀ rj ≀ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x β‰  y), that: * both indexes of the elements lie within range [lj, rj], that is, lj ≀ x, y ≀ rj; * the values of the elements are equal, that is ax = ay. The text above understands distance as |x - y|. Input The first line of the input contains a pair of integers n, m (1 ≀ n, m ≀ 5Β·105) β€” the length of the sequence and the number of queries, correspondingly. The second line contains the sequence of integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109). Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the indexes of the query range limits. Output Print m integers β€” the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query. Examples Input 5 3 1 1 2 3 2 1 5 2 4 3 5 Output 1 -1 2 Input 6 5 1 2 1 3 2 3 4 6 1 3 2 5 2 4 1 6 Output 2 2 3 -1 2
import sys class Fenwick(object): def __init__(self, n): self.n = n self.a = [10**9 for i in range(n)] self.w= 10**9 def zag(self, i, zn): self.w= min(self.w, zn) while i < self.n: self.a[i] = min(self.a[i], zn) i = (i | (i + 1)) def pol(self, r): ans= 10**9 while r >= 0: if ans> self.a[r]: ans= self.a[r] if ans== self.w: break r = (r & (r + 1)) - 1 return ans n, m = [int(x) for x in sys.stdin.readline().split()] a = [int(x) for x in sys.stdin.readline().split()] nd= [-1 for i in range(0, len(a))] vi= {} for i in range(0, len(a)): if a[i] in vi: nd[i] = vi[a[i]] vi[a[i]] = i inp= sys.stdin.readlines() och= [[] for i in range(n)] for i in range(m): l, r = inp[i].split() och[int(r) - 1].append((int(l) - 1, i)) der = Fenwick(2 ** 19) ans= [None for i in range(0, m)] le= -1 for r in range(n): if nd[r] != -1: der.zag(500000 - nd[r] + 1, r - nd[r]) le = max(le, nd[r]) for (l, ind) in och[r]: if l > le: ans[ind] = -1 continue zn= der.pol(500000 - l + 1) if zn== 10**9: zn= -1 ans[ind] = zn print('\n'.join(str(zn) for zn in ans))
{ "input": [ "5 3\n1 1 2 3 2\n1 5\n2 4\n3 5\n", "6 5\n1 2 1 3 2 3\n4 6\n1 3\n2 5\n2 4\n1 6\n" ], "output": [ "1\n-1\n2\n", "2\n2\n3\n-1\n2\n" ] }
2,483
9
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them. Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and Ο€. For example, opposite directions vectors have angle equals to Ο€. Input First line of the input contains a single integer n (2 ≀ n ≀ 100 000) β€” the number of vectors. The i-th of the following n lines contains two integers xi and yi (|x|, |y| ≀ 10 000, x2 + y2 > 0) β€” the coordinates of the i-th vector. Vectors are numbered from 1 to n in order of appearing in the input. It is guaranteed that no two vectors in the input share the same direction (but they still can have opposite directions). Output Print two integer numbers a and b (a β‰  b) β€” a pair of indices of vectors with the minimal non-oriented angle. You can print the numbers in any order. If there are many possible answers, print any. Examples Input 4 -1 0 0 -1 1 0 1 1 Output 3 4 Input 6 -1 0 0 -1 1 0 1 1 -4 -5 -4 -6 Output 6 5
from math import atan2 def skal(a, b): return a[0][0] * b[0][0] + a[0][1] * b[0][1] def vect(a, b): return a[0][0] * b[0][1] - b[0][0] * a[0][1] n = int(input()) a = [] for i in range(n): x, y = map(int, input().split()) a.append([[x, y], i + 1]) a.sort(key = lambda x: atan2(x[0][1],x[0][0])) a.append(a[0]) c = [[skal(a[0],a[1]),abs(vect(a[0],a[1]))],[a[0][1],a[1][1]]] for i in range(1, n): d = [[skal(a[i],a[i+1]),abs(vect(a[i],a[i+1]))],[a[i][1],a[i+1][1]]] if vect(d, c) > 0: c = d print(c[1][0],c[1][1])
{ "input": [ "6\n-1 0\n0 -1\n1 0\n1 1\n-4 -5\n-4 -6\n", "4\n-1 0\n0 -1\n1 0\n1 1\n" ], "output": [ "5 6\n", "3 4\n" ] }
2,484
7
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate. Input There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100. Output Write one line β€” the corresponding answer. Do not omit the leading 0s. Examples Input 1010100 0100101 Output 1110001 Input 000 111 Output 111 Input 1110 1010 Output 0100 Input 01110 01100 Output 00010
def main(): a = input() b = input() print("{:0{l}b}".format(int(a,2)^int(b,2), l=len(a))) main()
{ "input": [ "1010100\n0100101\n", "000\n111\n", "1110\n1010\n", "01110\n01100\n" ], "output": [ "1110001\n", "111\n", "0100\n", "00010\n" ] }
2,485
9
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
from sys import * setrecursionlimit(10001) s=input() ans,f=set(),{} def per(l,ll=0): if (l,ll) in f: return global ans f[(l,ll)]=1 if l>6 and s[l-2:l]!=s[l:l+ll]: ans|={s[l-2:l]}; per(l-2,2) if l>7 and s[l-3:l]!=s[l:l+ll]: ans|={s[l-3:l]}; per(l-3,3) per(len(s)) print(len(ans)) for x in sorted(ans): print(x)
{ "input": [ "abacabaca\n", "abaca\n" ], "output": [ "3\naca\nba\nca\n", "0\n" ] }
2,486
9
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly: 1. It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). 2. There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid. Input The first line of the input contains two space-separated integers n and m (1 ≀ n, m ≀ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≀ a, b ≀ n, a β‰  b). Output The output consists of one line, containing either yes or no depending on whether the nervous system is valid. Examples Input 4 4 1 2 2 3 3 1 4 1 Output no Input 6 5 1 2 2 3 3 4 4 5 3 6 Output yes
f = lambda: map(int, input().split()) n, m = f() p = list(range(n)) def g(i): while i != p[i]: i = p[i] return i q = 'yes' if m == n - 1 else 'no' for j in range(m): a, b = f() u, v = g(a - 1), g(b - 1) if u == v: q = 'no' p[u] = v print(q)
{ "input": [ "6 5\n1 2\n2 3\n3 4\n4 5\n3 6\n", "4 4\n1 2\n2 3\n3 1\n4 1\n" ], "output": [ "yes\n", "no\n" ] }
2,487
9
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions. Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. 1. Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x. 2. Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions. Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions. Input The first line of the input contains three integers n, m, k (1 ≀ n ≀ 2Β·109, 1 ≀ m, k ≀ 2Β·105) β€” the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers x and s (2 ≀ x ≀ 2Β·109, 1 ≀ s ≀ 2Β·109) β€” the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains m integers ai (1 ≀ ai < x) β€” the number of seconds it will take to prepare one potion if the i-th spell of the first type is used. The fourth line contains m integers bi (1 ≀ bi ≀ 2Β·109) β€” the number of manapoints to use the i-th spell of the first type. There are k integers ci (1 ≀ ci ≀ n) in the fifth line β€” the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci ≀ cj if i < j. The sixth line contains k integers di (1 ≀ di ≀ 2Β·109) β€” the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di ≀ dj if i < j. Output Print one integer β€” the minimum time one has to spent in order to prepare n potions. Examples Input 20 3 2 10 99 2 4 3 20 10 40 4 15 10 80 Output 20 Input 20 3 2 10 99 2 4 3 200 100 400 4 15 100 800 Output 200 Note In the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10 + 80 = 90, and the preparation time is 4Β·5 = 20 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each). In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20Β·10 = 200.
#!/usr/bin/env python3 from bisect import * def ri(): return map(int, input().split()) n, m, k = ri() x, s = ri() a = list(ri()) b = list(ri()) c = list(ri()) d = list(ri()) a.append(x) b.append(0) min_time = n * max(a) for i in range(m+1): mm = s - b[i] if mm >= 0: j = bisect_right(d, mm) if j > 0: min_time = min(min_time, (n - c[j-1]) * a[i]) else: min_time = min(min_time, n * a[i]) print(min_time)
{ "input": [ "20 3 2\n10 99\n2 4 3\n20 10 40\n4 15\n10 80\n", "20 3 2\n10 99\n2 4 3\n200 100 400\n4 15\n100 800\n" ], "output": [ "20\n", "200\n" ] }
2,488
9
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others. Seating in the class looks like a rectangle, where n rows with m pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the 1-st row, the 2-nd row, ..., the n - 1-st row, the n-th row, the n - 1-st row, ..., the 2-nd row, the 1-st row, the 2-nd row, ... The order of asking of pupils on the same row is always the same: the 1-st pupil, the 2-nd pupil, ..., the m-th pupil. During the lesson the teacher managed to ask exactly k questions from pupils in order described above. Sergei seats on the x-th row, on the y-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values: 1. the maximum number of questions a particular pupil is asked, 2. the minimum number of questions a particular pupil is asked, 3. how many times the teacher asked Sergei. If there is only one row in the class, then the teacher always asks children from this row. Input The first and the only line contains five integers n, m, k, x and y (1 ≀ n, m ≀ 100, 1 ≀ k ≀ 1018, 1 ≀ x ≀ n, 1 ≀ y ≀ m). Output Print three integers: 1. the maximum number of questions a particular pupil is asked, 2. the minimum number of questions a particular pupil is asked, 3. how many times the teacher asked Sergei. Examples Input 1 3 8 1 1 Output 3 2 3 Input 4 2 9 4 2 Output 2 1 1 Input 5 5 25 4 3 Output 1 1 1 Input 100 100 1000000000000000000 100 100 Output 101010101010101 50505050505051 50505050505051 Note The order of asking pupils in the first test: 1. the pupil from the first row who seats at the first table, it means it is Sergei; 2. the pupil from the first row who seats at the second table; 3. the pupil from the first row who seats at the third table; 4. the pupil from the first row who seats at the first table, it means it is Sergei; 5. the pupil from the first row who seats at the second table; 6. the pupil from the first row who seats at the third table; 7. the pupil from the first row who seats at the first table, it means it is Sergei; 8. the pupil from the first row who seats at the second table; The order of asking pupils in the second test: 1. the pupil from the first row who seats at the first table; 2. the pupil from the first row who seats at the second table; 3. the pupil from the second row who seats at the first table; 4. the pupil from the second row who seats at the second table; 5. the pupil from the third row who seats at the first table; 6. the pupil from the third row who seats at the second table; 7. the pupil from the fourth row who seats at the first table; 8. the pupil from the fourth row who seats at the second table, it means it is Sergei; 9. the pupil from the third row who seats at the first table;
n, m, k, x, y = map(int, input().split()) def cnt(r, c): a = k if n == 1: return (a // m + ((a % m) >= c)) res = a // ((2 * n - 2) * m) if r != 1 and r != n: res *= 2 a %= (2 * n - 2) * m if a > n * m: return res + 1 + (1 if r != n and a-n*m >= (n-r-1)*m + c else 0) else: return res + (1 if a >= (r-1)*m + c else 0) r1 = cnt(1, 1) r2 = cnt(2, 1) r3 = cnt(n - 1, 1) r4 = cnt(n, m) r5 = cnt(x, y) print(max(r1, r2, r3), r4, r5)
{ "input": [ "100 100 1000000000000000000 100 100\n", "4 2 9 4 2\n", "1 3 8 1 1\n", "5 5 25 4 3\n" ], "output": [ "101010101010101 50505050505051 50505050505051\n", "2 1 1\n", "3 2 3\n", "1 1 1\n" ] }
2,489
7
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 mere mortals from the effect of this terrible evil. The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: a for Mephisto, b for Diablo and c for Baal. Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a <image> of experience, rounded down, where x will be the amount of experience for the killed megaboss and y β€” the number of people in the team. Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum. It is known that some heroes like others. But if hero p likes hero q, this does not mean that the hero q likes hero p. No hero likes himself. The total amount of liking in teams is the amount of ordered pairs (p, q), such that heroes p and q are in the same group, and hero p likes hero q (but it is not important if hero q likes hero p). In case of heroes p and q likes each other and they are in the same group, this pair should be counted twice, as (p, q) and (q, p). A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team. It is guaranteed that every hero is able to destroy any megaboss alone. Input The first line contains a single non-negative integer n (0 ≀ n ≀ 42) β€” amount of liking between the heroes. Next n lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p β‰  q). Every liking is described in the input exactly once, no hero likes himself. In the last line are given three integers a, b and c (1 ≀ a, b, c ≀ 2Β·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal. In all the pretests, except for examples from the statement, the following condition is satisfied: a = b = c. Output Print two integers β€” the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team). When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking. Examples Input 3 Troll likes Dracul Dracul likes Anka Snowy likes Hexadecimal 210 200 180 Output 30 3 Input 2 Anka likes Chapay Chapay likes Anka 10000 50 50 Output 1950 2 Note A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo ΠΈ Chapay.
R=range S=str.split I=input L=S('Anka Chapay Cleo Troll Dracul Snowy Hexadecimal') h={} for i in R(7):h[L[i]]=i d=[[]for i in R(9)] for z in '0'*int(I()):a,_,b=S(I());d[h[a]]+=[h[b]] a,b,c=map(int,S(I())) o=[10**9,0] def C(q,w,e,n): if n==7: if not(q and w and e):return p=[a//len(q),b//len(w),c//(len(e))];p=max(p)-min(p);l=sum(k in g for g in(q,w,e)for h in g for k in d[h]);global o if o[0]>p or o[0]==p and o[1]<l:o=p,l else:C(q+[n],w,e,n+1);C(q,w+[n],e,n+1);C(q,w,e+[n],n+1) C([],[],[],0) print(o[0],o[1])
{ "input": [ "2\nAnka likes Chapay\nChapay likes Anka\n10000 50 50\n", "3\nTroll likes Dracul\nDracul likes Anka\nSnowy likes Hexadecimal\n210 200 180\n" ], "output": [ "1950 2\n", "30 3\n" ] }
2,490
10
Wherever the destination is, whoever we meet, let's render this song together. On a Cartesian coordinate plane lies a rectangular stage of size w Γ— h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage. On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: * Vertical: stands at (xi, 0), moves in positive y direction (upwards); * Horizontal: stands at (0, yi), moves in positive x direction (rightwards). <image> According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. <image> Dancers stop when a border of the stage is reached. Find out every dancer's stopping position. Input The first line of input contains three space-separated positive integers n, w and h (1 ≀ n ≀ 100 000, 2 ≀ w, h ≀ 100 000) β€” the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≀ gi ≀ 2, 1 ≀ pi ≀ 99 999, 0 ≀ ti ≀ 100 000), describing a dancer's group gi (gi = 1 β€” vertical, gi = 2 β€” horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≀ xi ≀ w - 1 and 1 ≀ yi ≀ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. Output Output n lines, the i-th of which contains two space-separated integers (xi, yi) β€” the stopping position of the i-th dancer in the input. Examples Input 8 10 8 1 1 10 1 4 13 1 7 1 1 8 2 2 2 0 2 5 14 2 6 0 2 6 1 Output 4 8 10 5 8 8 10 6 10 2 1 8 7 8 10 6 Input 3 2 3 1 1 2 2 1 1 1 1 5 Output 1 3 2 1 1 3 Note The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. <image> In the second example, no dancers collide.
n,w,h = map(int,input().split()) def it(n): for i in range(n): g,p,t = map(int,input().split()) yield (p-t, p if g==1 else -p, i) D = sorted(it(n)) from bisect import bisect from itertools import chain res = [None]*n i = 0 while i < len(D): k = D[i][0] j = bisect(D, (k+1,-n,0), lo=i) m = bisect(D, (k,0,0), lo=i,hi=j) for s,t in zip(range(i,j),chain(range(m,j),range(i,j))): p,d = D[t][1],D[s][2] res[d] = (p,h) if p > 0 else (w,-p) i = j print('\n'.join(' '.join(map(str,r)) for r in res))
{ "input": [ "3 2 3\n1 1 2\n2 1 1\n1 1 5\n", "8 10 8\n1 1 10\n1 4 13\n1 7 1\n1 8 2\n2 2 0\n2 5 14\n2 6 0\n2 6 1\n" ], "output": [ "1 3\n2 1\n1 3\n", "4 8\n10 5\n8 8\n10 6\n10 2\n1 8\n7 8\n10 6\n" ] }
2,491
7
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself. Input The first line contains single integer q (1 ≀ q ≀ 105) β€” the number of queries. q lines follow. The (i + 1)-th line contains single integer ni (1 ≀ ni ≀ 109) β€” the i-th query. Output For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings. Examples Input 1 12 Output 3 Input 2 6 8 Output 1 2 Input 3 1 2 3 Output -1 -1 -1 Note 12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands. 8 = 4 + 4, 6 can't be split into several composite summands. 1, 2, 3 are less than any composite number, so they do not have valid splittings.
def find(n): if n%4==0: return n//4 elif n%4==1: if n>=4*2+1: return n//4-1 else: return -1 elif n%4==2: if n>2: return n//4 else: return -1 else: if n>=4*3+3: return n//4-1 else: return -1 for _ in range(int(input())): print(find(int(input())))
{ "input": [ "3\n1\n2\n3\n", "2\n6\n8\n", "1\n12\n" ], "output": [ "-1\n-1\n-1\n", "1\n2\n", "3\n" ] }
2,492
7
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded. For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct. For given n find out to which integer will Vasya round it. Input The first line contains single integer n (0 ≀ n ≀ 109) β€” number that Vasya has. Output Print result of rounding n. Pay attention that in some cases answer isn't unique. In that case print any correct answer. Examples Input 5 Output 0 Input 113 Output 110 Input 1000000000 Output 1000000000 Input 5432359 Output 5432360 Note In the first example n = 5. Nearest integers, that ends up with zero are 0 and 10. Any of these answers is correct, so you can print 0 or 10.
import sys def main(): k = int(sys.stdin.read().strip()) return k - k%10 + (k%10 > 4)*10 print(main())
{ "input": [ "5\n", "5432359\n", "1000000000\n", "113\n" ], "output": [ "0\n", "5432360\n", "1000000000\n", "110\n" ] }
2,493
8
We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer. Input A single line with a positive integer k (1 ≀ k ≀ 10 000). Output A single number, denoting the k-th smallest perfect integer. Examples Input 1 Output 19 Input 2 Output 28 Note The first perfect integer is 19 and the second one is 28.
def y(x): t=0 while x: t=t+x%10 x=x//10 return t n=int(input()) z=19 while n>1: z=z+9 if y(z)==10: n=n-1 print (z)
{ "input": [ "1\n", "2\n" ], "output": [ "19", "28" ] }
2,494
7
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of B - C? Input The first line contains one integer n (1 ≀ n ≀ 100) β€” the number of elements in a. The second line contains n integers a1, a2, ..., an ( - 100 ≀ ai ≀ 100) β€” the elements of sequence a. Output Print the maximum possible value of B - C, where B is the sum of elements of sequence b, and C is the sum of elements of sequence c. Examples Input 3 1 -2 0 Output 3 Input 6 16 23 16 15 42 8 Output 120 Note In the first example we may choose b = {1, 0}, c = { - 2}. Then B = 1, C = - 2, B - C = 3. In the second example we choose b = {16, 23, 16, 15, 42, 8}, c = {} (an empty sequence). Then B = 120, C = 0, B - C = 120.
def get(x): return abs(int(x)) n = int(input()) a = list(map(get, input().split())) print(sum(a))
{ "input": [ "3\n1 -2 0\n", "6\n16 23 16 15 42 8\n" ], "output": [ "3\n", "120\n" ] }
2,495
10
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths. Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially. At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1 ≀ x, y ≀ n). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1 ≀ ui, vi ≀ n, 1 ≀ wi ≀ 109) β€” they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1 ≀ ti, ci ≀ 109), which describe the taxi driver that waits at the i-th junction β€” the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character. Output If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator. Examples Input 4 4 1 3 1 2 3 1 4 1 2 4 1 2 3 5 2 7 7 2 1 2 7 7 Output 9 Note An optimal way β€” ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.
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.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ from math import factorial from collections import Counter, defaultdict from heapq import heapify, heappop, heappush def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def ctd(chr): return ord(chr)-ord("a") mod = 998244353 INF = float('inf') from heapq import heappush, heappop # ------------------------------ # f = open('./input.txt') # sys.stdin = f def main(): n, m = RL() x, y = RL() gp = defaultdict(dict) for _ in range(m): u, v, w = RL() gp[u][v] = min(gp[u].get(v, INF), w) gp[v][u] = min(gp[v].get(u, INF), w) cars = [[0, 0]] for _ in range(n): t, c = RL() cars.append([t, c]) disarr = [[INF]*(n+1) for _ in range(n+1)] for i in range(1, n+1): disarr[i][i] = 0 newg = [[INF]*(n+1) for _ in range(n+1)] dnex = defaultdict(list) def dij(s): q = [(0, s)] while q: d, nd = heappop(q) for nex in gp[nd]: dis = gp[nd][nex]+disarr[s][nd] if dis<disarr[s][nex]: disarr[s][nex] = dis heappush(q, (dis, nex)) for i in range(1, n+1): cd, cc = cars[s] d = disarr[s][i] if d<=cd: newg[s][i] = min(newg[s][i], cc) dnex[s].append(i) def dij1(s): q = [(0, s)] cst = [INF] * (n + 1) cst[s] = 0 while q: d, nd = heappop(q) for nex in dnex[nd]: cs = cst[nd]+newg[nd][nex] if cs<cst[nex]: cst[nex] = cs heappush(q, (cs, nex)) if cst[y]==INF: print(-1) else: print(cst[y]) for i in range(1, n+1): dij(i) dij1(x) # for i in newg:print(i) if __name__ == "__main__": main()
{ "input": [ "4 4\n1 3\n1 2 3\n1 4 1\n2 4 1\n2 3 5\n2 7\n7 2\n1 2\n7 7\n" ], "output": [ "9\n" ] }
2,496
10
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers. Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not. Input The first line contains two integers n and m (1 ≀ n, m ≀ 12) β€” the number of pairs the first participant communicated to the second and vice versa. The second line contains n pairs of integers, each between 1 and 9, β€” pairs of numbers communicated from first participant to the second. The third line contains m pairs of integers, each between 1 and 9, β€” pairs of numbers communicated from the second participant to the first. All pairs within each set are distinct (in particular, if there is a pair (1,2), there will be no pair (2,1) within the same set), and no pair contains the same number twice. It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number. Output If you can deduce the shared number with certainty, print that number. If you can with certainty deduce that both participants know the shared number, but you do not know it, print 0. Otherwise print -1. Examples Input 2 2 1 2 3 4 1 5 3 4 Output 1 Input 2 2 1 2 3 4 1 5 6 4 Output 0 Input 2 3 1 2 4 5 1 2 1 3 2 3 Output -1 Note In the first example the first participant communicated pairs (1,2) and (3,4), and the second communicated (1,5), (3,4). Since we know that the actual pairs they received share exactly one number, it can't be that they both have (3,4). Thus, the first participant has (1,2) and the second has (1,5), and at this point you already know the shared number is 1. In the second example either the first participant has (1,2) and the second has (1,5), or the first has (3,4) and the second has (6,4). In the first case both of them know the shared number is 1, in the second case both of them know the shared number is 4. You don't have enough information to tell 1 and 4 apart. In the third case if the first participant was given (1,2), they don't know what the shared number is, since from their perspective the second participant might have been given either (1,3), in which case the shared number is 1, or (2,3), in which case the shared number is 2. While the second participant does know the number with certainty, neither you nor the first participant do, so the output is -1.
def rp(): cs = list(map(int, input().split(' '))) cs = list(zip(cs[0::2], cs[1::2])) return cs def dist(p1, p2): return len(set(p1).union(set(p2))) - 2 input() ps = [rp(), rp()] theyCan = True myPos = set() for ps1, ps2 in [ps, ps[::-1]]: for p1 in ps1: pos = set() for p2 in ps2: if dist(p1, p2) == 1: pos = pos.union( set(p1).intersection(set(p2)) ) if len(pos) >= 2: theyCan = False myPos = myPos.union(pos) print(next(iter(myPos)) if len(myPos)==1 else 0 if theyCan else -1)
{ "input": [ "2 2\n1 2 3 4\n1 5 3 4\n", "2 2\n1 2 3 4\n1 5 6 4\n", "2 3\n1 2 4 5\n1 2 1 3 2 3\n" ], "output": [ "1", "0", "-1" ] }
2,497
8
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, …, x_{k-1}. Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 ≀ i ≀ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q. For example, if the x = [1, 2, 3] and n = 5, then: * a_0 = 0, * a_1 = x_{0mod 3}+a_0=x_0+0=1, * a_2 = x_{1mod 3}+a_1=x_1+1=3, * a_3 = x_{2mod 3}+a_2=x_2+3=6, * a_4 = x_{3mod 3}+a_3=x_0+6=7, * a_5 = x_{4mod 3}+a_4=x_1+7=9. So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9]. Now the boy hopes that he will be able to restore x from a! Knowing that 1 ≀ k ≀ n, help him and find all possible values of k β€” possible lengths of the lost array. Input The first line contains exactly one integer n (1 ≀ n ≀ 1000) β€” the length of the array a, excluding the element a_0. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^6). Note that a_0 is always 0 and is not given in the input. Output The first line of the output should contain one integer l denoting the number of correct lengths of the lost array. The second line of the output should contain l integers β€” possible lengths of the lost array in increasing order. Examples Input 5 1 2 3 4 5 Output 5 1 2 3 4 5 Input 5 1 3 5 6 8 Output 2 3 5 Input 3 1 5 3 Output 1 3 Note In the first example, any k is suitable, since a is an arithmetic progression. Possible arrays x: * [1] * [1, 1] * [1, 1, 1] * [1, 1, 1, 1] * [1, 1, 1, 1, 1] In the second example, Bajtek's array can have three or five elements. Possible arrays x: * [1, 2, 2] * [1, 2, 2, 1, 2] For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction. In the third example, only k = n is good. Array [1, 4, -2] satisfies the requirements. Note that x_i may be negative.
def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) n = ii() a = [0] + li() d = [a[i] - a[i - 1] for i in range(1, n + 1)] ans = [] for i in range(1, n + 1): ok = all(d[j] == d[j % i] for j in range(n)) if ok: ans.append(i) print(len(ans)) print(*ans)
{ "input": [ "5\n1 2 3 4 5\n", "5\n1 3 5 6 8\n", "3\n1 5 3\n" ], "output": [ "5\n1 2 3 4 5 ", "2\n3 5 ", "1\n3 " ] }
2,498
11
Vasya has a string s of length n consisting only of digits 0 and 1. Also he has an array a of length n. Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string 111110 he will get the string 110. Vasya gets a_x points for erasing substring of length x. Vasya wants to maximize his total points, so help him with this! Input The first line contains one integer n (1 ≀ n ≀ 100) β€” the length of string s. The second line contains string s, consisting only of digits 0 and 1. The third line contains n integers a_1, a_2, ... a_n (1 ≀ a_i ≀ 10^9), where a_i is the number of points for erasing the substring of length i. Output Print one integer β€” the maximum total points Vasya can get. Examples Input 7 1101001 3 4 9 100 1 2 3 Output 109 Input 5 10101 3 10 15 15 15 Output 23 Note In the first example the optimal sequence of erasings is: 1101001 β†’ 111001 β†’ 11101 β†’ 1111 β†’ βˆ…. In the second example the optimal sequence of erasings is: 10101 β†’ 1001 β†’ 11 β†’ βˆ….
import sys sys.setrecursionlimit(10 ** 6) n = int(input()) s = input().strip() a = [0] + list(map(int, input().split())) MX = 105 dp = [0] * (MX ** 3) def f(i, j, k): if i == j: return 0 idx = i * MX * MX + j * MX + k if not dp[idx]: dp[idx] = f(i + 1, j, 1) + a[k] for m in range(i + 1, j): if s[i] == s[m]: dp[idx] = max(dp[idx], f(i + 1, m, 1) + f(m, j, k + 1)) return dp[idx] print(f(0, n, 1))
{ "input": [ "7\n1101001\n3 4 9 100 1 2 3\n", "5\n10101\n3 10 15 15 15\n" ], "output": [ "109\n", "23\n" ] }
2,499
8
A telephone number is a sequence of exactly 11 digits such that its first digit is 8. Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string s becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins. You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves). Input The first line contains one integer n (13 ≀ n < 10^5, n is odd) β€” the length of string s. The second line contains the string s (|s| = n) consisting only of decimal digits. Output If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO. Examples Input 13 8380011223344 Output YES Input 15 807345619350641 Output NO Note In the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number. In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
def win(n, s): return s[:-10].count('8') >= (n-9)//2 n = int(input().strip()) s = input().strip() print("YES" if win(n, s) else "NO")
{ "input": [ "15\n807345619350641\n", "13\n8380011223344\n" ], "output": [ "NO\n", "YES\n" ] }