index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
3,500
9
Gaurang has grown up in a mystical universe. He is faced by n consecutive 2D planes. He shoots a particle of decay age k at the planes. A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age k-1. If a particle has decay age equal to 1, it will NOT produce a copy. For example, if there are two planes and a particle is shot with decay age 3 (towards the right), the process is as follows: (here, D(x) refers to a single particle with decay age x) 1. the first plane produces a D(2) to the left and lets D(3) continue on to the right; 2. the second plane produces a D(2) to the left and lets D(3) continue on to the right; 3. the first plane lets D(2) continue on to the left and produces a D(1) to the right; 4. the second plane lets D(1) continue on to the right (D(1) cannot produce any copies). In total, the final multiset S of particles is \\{D(3), D(2), D(2), D(1)\}. (See notes for visual explanation of this test case.) Gaurang is unable to cope up with the complexity of this situation when the number of planes is too large. Help Gaurang find the size of the multiset S, given n and k. Since the size of the multiset can be very large, you have to output it modulo 10^9+7. Note: Particles can go back and forth between the planes without colliding with each other. Input The first line of the input contains the number of test cases t (1 ≀ t ≀ 100). Then, t lines follow, each containing two integers n and k (1 ≀ n, k ≀ 1000). Additionally, the sum of n over all test cases will not exceed 1000, and the sum of k over all test cases will not exceed 1000. All test cases in one test are different. Output Output t integers. The i-th of them should be equal to the answer to the i-th test case. Examples Input 4 2 3 2 2 3 1 1 3 Output 4 3 1 2 Input 3 1 1 1 500 500 250 Output 1 2 257950823 Note Let us explain the first example with four test cases. Test case 1: (n = 2, k = 3) is already explained in the problem statement. See the below figure of this simulation. Each straight line with a different color represents the path of a different particle. As you can see, there are four distinct particles in the multiset. Note that the vertical spacing between reflected particles is for visual clarity only (as mentioned before, no two distinct particles collide with each other) <image> Test case 2: (n = 2, k = 2) is explained as follows: 1. the first plane produces a D(1) to the left and lets D(2) continue on to the right; 2. the second plane produces a D(1) to the left and lets D(2) continue on to the right; 3. the first plane lets D(1) continue on to the left (D(1) cannot produce any copies). Total size of multiset obtained \\{D(1), D(1), D(2)\} is equal to three. Test case 3: (n = 3, k = 1), there are three planes, but decay age is only one. So no new copies are produced while the one particle passes through the planes. Hence, the answer is one. Test case 4: (n = 1, k = 3) there is only one plane. The particle produces a new copy to the left. The multiset \\{D(2), D(3)\} is of size two.
MOD = int(1e9+7) def solve(k,n): global dp for i in range(1,k+1): for j in range(1, n+1): dp[i][j] = (dp[i][j-1] + dp[i-1][n-j])%MOD return dp[k][n] for _ in range(int(input())): n_,k_ = map(int, input().split()) dp = [[0 for i in range(n_+1)] for j in range(k_+1)] for i in range(k_+1): dp[i][0] = 1 dp[0][0] = 0 print(solve(k_, n_)) # for i in dp: # print(i)
{ "input": [ "3\n1 1\n1 500\n500 250\n", "4\n2 3\n2 2\n3 1\n1 3\n" ], "output": [ "\n1\n2\n257950823\n", "\n4\n3\n1\n2\n" ] }
3,501
8
Let's call a positive integer n ordinary if in the decimal notation all its digits are the same. For example, 1, 2 and 99 are ordinary numbers, but 719 and 2021 are not ordinary numbers. For a given number n, find the number of ordinary numbers among the numbers from 1 to n. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. Each test case is characterized by one integer n (1 ≀ n ≀ 10^9). Output For each test case output the number of ordinary numbers among numbers from 1 to n. Example Input 6 1 2 3 4 5 100 Output 1 2 3 4 5 18
import sys input = sys.stdin.readline def solve(n): res = 0 for d in range(1,10): for l in range(1,11): if n>=int(str(d)*l): res+=1 print(res) for _ in range(int(input())): n = int(input()) solve(n)
{ "input": [ "6\n1\n2\n3\n4\n5\n100\n" ], "output": [ "\n1\n2\n3\n4\n5\n18\n" ] }
3,502
8
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document. In the Pindows operating system a strings are the lexemes of the command line β€” the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces. To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited β€” that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space). It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them. You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters. Input The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme. Output In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples. Examples Input "RUn.exe O" "" " 2ne, " two! . " " Output &lt;RUn.exe O&gt; &lt;&gt; &lt; 2ne, &gt; &lt;two!&gt; &lt;.&gt; &lt; &gt; Input firstarg second "" Output &lt;firstarg&gt; &lt;second&gt; &lt;&gt;
def main(): res = [] for i, s in enumerate(input().split('"')): if i & 1: res += ["<", s, ">\n"] else: for t in s.split(): res += ["<", t, ">\n"] print(''.join(res), end='') if __name__ == '__main__': main()
{ "input": [ "\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"\n", "firstarg second \"\" \n" ], "output": [ "<RUn.exe O>\n<>\n< 2ne, >\n<two!>\n<.>\n< >\n", "<firstarg>\n<second>\n<>\n" ] }
3,503
8
Little boy Petya loves stairs very much. But he is bored from simple going up and down them β€” he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once. One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only. Input The first line contains two integers n and m (1 ≀ n ≀ 109, 0 ≀ m ≀ 3000) β€” the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d1, d2, ..., dm (1 ≀ di ≀ n) β€” the numbers of the dirty stairs (in an arbitrary order). Output Print "YES" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print "NO". Examples Input 10 5 2 4 8 3 6 Output NO Input 10 5 2 4 5 7 9 Output YES
def readln(): return tuple(map(int, input().split())) n, m = readln() d = sorted(readln()) if m else [] if m and (d[0] == 1 or d[-1] == n) or m > 2 and [1 for i, j, k in zip(d[:-2], d[1:-1], d[2:]) if i + 2 == k]: print('NO') else: print('YES')
{ "input": [ "10 5\n2 4 5 7 9\n", "10 5\n2 4 8 3 6\n" ], "output": [ "YES\n", "NO\n" ] }
3,504
11
Our bear's forest has a checkered field. The checkered field is an n Γ— n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains growing raspberry, at that, the cell (x, y) of the field contains x + y raspberry bushes. The bear came out to walk across the field. At the beginning of the walk his speed is (dx, dy). Then the bear spends exactly t seconds on the field. Each second the following takes place: * Let's suppose that at the current moment the bear is in cell (x, y). * First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from k bushes, he increases each component of his speed by k. In other words, if before eating the k bushes of raspberry his speed was (dx, dy), then after eating the berry his speed equals (dx + k, dy + k). * Let's denote the current speed of the bear (dx, dy) (it was increased after the previous step). Then the bear moves from cell (x, y) to cell (((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1). * Then one additional raspberry bush grows in each cell of the field. You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell (sx, sy). Assume that each bush has infinitely much raspberry and the bear will never eat all of it. Input The first line of the input contains six space-separated integers: n, sx, sy, dx, dy, t (1 ≀ n ≀ 109; 1 ≀ sx, sy ≀ n; - 100 ≀ dx, dy ≀ 100; 0 ≀ t ≀ 1018). Output Print two integers β€” the coordinates of the cell the bear will end up in after t seconds. Examples Input 5 1 2 0 1 2 Output 3 1 Input 1 1 1 -1 -1 2 Output 1 1 Note Operation a mod b means taking the remainder after dividing a by b. Note that the result of the operation is always non-negative. For example, ( - 1) mod 3 = 2. In the first sample before the first move the speed vector will equal (3,4) and the bear will get to cell (4,1). Before the second move the speed vector will equal (9,10) and he bear will get to cell (3,1). Don't forget that at the second move, the number of berry bushes increased by 1. In the second sample before the first move the speed vector will equal (1,1) and the bear will get to cell (1,1). Before the second move, the speed vector will equal (4,4) and the bear will get to cell (1,1). Don't forget that at the second move, the number of berry bushes increased by 1.
mod, sx, sy, dx, dy, t = map(int, input().split()) class Matrix(): def __init__(self, n): self.n = n self.a = [[0] * n for _ in range(n)] def __mul__(self, b): res = Matrix(self.n) for i in range(self.n): for j in range(self.n): for k in range(self.n): res.a[i][j] += self.a[i][k] * b.a[k][j] % mod res.a[i][j] %= mod return res def __pow__(self, e): res = Matrix(self.n) for i in range(self.n): res.a[i][i] = 1 tmp = self while e: if e & 1: res = res * tmp e >>= 1 tmp = tmp * tmp return res M = Matrix(6) M.a = [[2, 1, 1, 0, 1, 2], [1, 2, 0, 1, 1, 2], [1, 1, 1, 0, 1, 2], [1, 1, 0, 1, 1, 2], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1]] sx -= 1 sy -= 1 r = M ** t f = lambda i: (r.a[i][0] * sx + r.a[i][1] * sy + r.a[i][2] * dx + r.a[i][3] * dy + r.a[i][5]) % mod + 1 print(f(0), f(1))
{ "input": [ "1 1 1 -1 -1 2\n", "5 1 2 0 1 2\n" ], "output": [ "1 1\n", "3 1\n" ] }
3,505
8
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: (1n + 2n + 3n + 4n) mod 5 for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language). Input The single line contains a single integer n (0 ≀ n ≀ 10105). The number doesn't contain any leading zeroes. Output Print the value of the expression without leading zeros. Examples Input 4 Output 4 Input 124356983594583453458888889 Output 0 Note Operation x mod y means taking remainder after division x by y. Note to the first sample: <image>
def main(): print((4, 0)[int(input()[-2:]) & 3 > 0]) main()
{ "input": [ "124356983594583453458888889\n", "4\n" ], "output": [ "0\n", "4\n" ] }
3,506
7
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of rectangles. Each of the following n lines contains four integers x1, y1, x2, y2 (1 ≀ x1 ≀ x2 ≀ 100, 1 ≀ y1 ≀ y2 ≀ 100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle. Output In a single line print the sum of all values in the cells of the table. Examples Input 2 1 1 2 3 2 2 3 3 Output 10 Input 2 1 1 3 3 1 1 3 3 Output 18 Note Note to the first sample test: Values of the table in the first three rows and columns will be as follows: 121 121 110 So, the sum of values will be equal to 10. Note to the second sample test: Values of the table in the first three rows and columns will be as follows: 222 222 222 So, the sum of values will be equal to 18.
#!/usr/bin/python3 def calc(x0,y0,x1,y1): return (abs(x0-x1)+1)*(abs(y0-y1)+1) n=int(input()) print (sum(calc(*map(int,input().split())) for i in range(0,n)))
{ "input": [ "2\n1 1 3 3\n1 1 3 3\n", "2\n1 1 2 3\n2 2 3 3\n" ], "output": [ "18", "10" ] }
3,507
7
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days? Input The only line containing one integer x (1 ≀ x ≀ 109). Output The only line containing one integer: the answer. Examples Input 5 Output 2 Input 8 Output 1 Note For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2. For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
def main(): print(bin(int(input())).count('1')) if __name__=='__main__': main()
{ "input": [ "8\n", "5\n" ], "output": [ "1\n", "2\n" ] }
3,508
11
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night. In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other. An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills. Input The first line of the input data contains an integer number n (3 ≀ n ≀ 106), n β€” the amount of hills around the capital. The second line contains n numbers β€” heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109. Output Print the required amount of pairs. Examples Input 5 1 2 4 5 3 Output 7
#!/usr/bin/env python def main(): n = int(input()) hill = tuple(map(int, input().split())) pairs = 0 highest, at = max((h, k) for k, h in enumerate(hill)) last = highest count = 0 previous = list() push = previous.append pop = previous.pop for at in range(at - 1, at - n, -1): current = hill[at] while current > last: pairs += count last, count = pop() if current == last: count += 1 pairs += count else: pairs += 1 push((last, count)) last = current count = 1 push((last, count)) end = len(previous) pairs += sum(previous[k][1] for k in range((1 if previous[0][1] else 2), end)) print(pairs) if __name__ == '__main__': main()
{ "input": [ "5\n1 2 4 5 3\n" ], "output": [ "7\n" ] }
3,509
9
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi. For the i-th query find any position pi (li ≀ pi ≀ ri) so that api β‰  xi. Input The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the number of elements in a and the number of queries. The second line contains n integers ai (1 ≀ ai ≀ 106) β€” the elements of the array a. Each of the next m lines contains three integers li, ri, xi (1 ≀ li ≀ ri ≀ n, 1 ≀ xi ≀ 106) β€” the parameters of the i-th query. Output Print m lines. On the i-th line print integer pi β€” the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number. Examples Input 6 4 1 2 1 1 3 5 1 4 1 2 6 2 3 4 1 3 4 2 Output 2 6 -1 4
__author__ = 'Utena' from sys import * def input(): return stdin.readline() n,m=map(int,input().split()) ans1=[] prev=[-1 for i in range(n)] s=input().split() for i in range(1,n): if s[i]!=s[i-1]: prev[i]=i-1 now=i else: prev[i]=prev[i-1] for j in range(m): l,r,x=input().split() l,r=int(l),int(r) if s[r-1]!=x: ans=r else: if prev[r-1]<l-1:ans=-1 else:ans=prev[r-1]+1 ans1.append(str(ans)) print('\n'.join(ans1))
{ "input": [ "6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2\n" ], "output": [ "2\n3\n-1\n3\n" ] }
3,510
11
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))": * 1st bracket is paired with 8th, * 2d bracket is paired with 3d, * 3d bracket is paired with 2d, * 4th bracket is paired with 7th, * 5th bracket is paired with 6th, * 6th bracket is paired with 5th, * 7th bracket is paired with 4th, * 8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported: * Β«LΒ» β€” move the cursor one position to the left, * Β«RΒ» β€” move the cursor one position to the right, * Β«DΒ» β€” delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below. <image> All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor. Polycarp is very proud of his development, can you implement the functionality of his editor? Input The first line contains three positive integers n, m and p (2 ≀ n ≀ 500 000, 1 ≀ m ≀ 500 000, 1 ≀ p ≀ n) β€” the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even. It is followed by the string of n characters "(" and ")" forming the correct bracket sequence. Then follow a string of m characters "L", "R" and "D" β€” a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty. Output Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence. Examples Input 8 4 5 (())()() RDLD Output () Input 12 5 3 ((()())(())) RRDLD Output (()(())) Input 8 8 8 (())()() LLLLLLDD Output ()() Note In the first sample the cursor is initially at position 5. Consider actions of the editor: 1. command "R" β€” the cursor moves to the position 6 on the right; 2. command "D" β€” the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5; 3. command "L" β€” the cursor moves to the position 4 on the left; 4. command "D" β€” the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to ().
def main(): n, m, p = map(int, input().split()) xlat, l, s, ll, lr = [0] * n, [], input(), list(range(-1, n)), list(range(1, n + 2)) p -= 1 for i, c in enumerate(s): if c == '(': l.append(i) else: j = l.pop() xlat[i] = j xlat[j] = i for c in input(): if c == 'D': if s[p] == '(': p = xlat[p] q = ll[xlat[p]] p = lr[p] ll[p], lr[q] = q, p if p == n: p = ll[p] else: p = (lr if c == 'R' else ll)[p] q = p while p != -1: l.append(s[p]) p = ll[p] l.reverse() del l[-1] while q != n: l.append(s[q]) q = lr[q] print(''.join(l)) if __name__ == '__main__': main()
{ "input": [ "12 5 3\n((()())(()))\nRRDLD\n", "8 8 8\n(())()()\nLLLLLLDD\n", "8 4 5\n(())()()\nRDLD\n" ], "output": [ "(()(()))\n", "()()\n", "()\n" ] }
3,511
8
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. <image> Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows: let starting_time be an array of length n current_time = 0 dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u) As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)). Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help. Input The first line of input contains a single integer n (1 ≀ n ≀ 105) β€” the number of cities in USC. The second line contains n - 1 integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC. Output In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6. Examples Input 7 1 2 1 1 4 4 Output 1.0 4.0 5.0 3.5 4.5 5.0 5.0 Input 12 1 1 2 2 4 4 3 3 1 10 8 Output 1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
import sys input = sys.stdin.readline n = int(input()) par = [-1] + [int(i) - 1 for i in input().split()] child = [[] for i in range(n)] for i in range(1, n): child[par[i]].append(i) size = [1] * n def dfs(): stack = [0] visit = [False] * n while stack: u = stack[-1] if not visit[u]: for v in child[u]: stack.append(v) visit[u] = True else: for v in child[u]: size[u] += size[v] stack.pop() ans = [0] * n ans[0] = 1 def dfs2(): stack = [0] while stack: u = stack.pop() sm = 0 for v in child[u]: sm += size[v] for v in child[u]: ans[v] = (sm - size[v]) * 0.5 + 1 + ans[u] stack.append(v) dfs() dfs2() print(*ans)
{ "input": [ "7\n1 2 1 1 4 4\n", "12\n1 1 2 2 4 4 3 3 1 10 8\n" ], "output": [ "1.00000000 4.00000000 5.00000000 3.50000000 4.50000000 5.00000000 5.00000000 ", "1.00000000 5.00000000 5.50000000 6.50000000 7.50000000 8.00000000 8.00000000 7.00000000 7.50000000 6.50000000 7.50000000 8.00000000 " ] }
3,512
9
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007. Input The first line of input contains integer n (1 ≀ n ≀ 100 000) β€” the number of tasks. The next n lines contain exactly one integer number ai (1 ≀ ai ≀ 100 000) β€” both the difficulty of the initial task and the laziness of the i-th students. Output Print the minimum total time to finish all tasks modulo 10 007. Example Input 2 1 3 Output 6 Note In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
def main(): n = int(input()) total = 0 list1 = [] for i in range(n): a = int(input()) list1.append(a) list1 = sorted(list1) for i in range(n): total = total + list1[i]*list1[n-i-1] print(total%10007) main()
{ "input": [ "2\n1\n3\n" ], "output": [ "6\n" ] }
3,513
10
Dasha logged into the system and began to solve problems. One of them is as follows: Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai. About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l ≀ ai ≀ r and l ≀ bi ≀ r. About sequence c we know that all its elements are distinct. <image> Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test. Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively. Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct. Input The first line contains three integers n, l, r (1 ≀ n ≀ 105, 1 ≀ l ≀ r ≀ 109) β€” the length of the sequence and boundaries of the segment where the elements of sequences a and b are. The next line contains n integers a1, a2, ..., an (l ≀ ai ≀ r) β€” the elements of the sequence a. The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the compressed sequence of the sequence c. Output If there is no the suitable sequence b, then in the only line print "-1". Otherwise, in the only line print n integers β€” the elements of any suitable sequence b. Examples Input 5 1 5 1 1 1 1 1 3 1 5 4 2 Output 3 1 5 4 2 Input 4 2 9 3 4 8 9 3 2 1 4 Output 2 2 2 9 Input 6 1 5 1 1 1 1 1 1 2 3 5 4 1 6 Output -1 Note Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
#!/usr/bin/env python3 from sys import stdin,stdout def ri(): return map(int, input().split()) n, l, r = ri() a = list(ri()) p = list(ri()) pi = [i for i in range(n)] pi.sort(key=lambda e: p[e]) b = [0 for i in range(n)] i = pi[0] b[i] = l cp = b[i] - a[i] for ii in range(1,n): i = pi[ii] if a[i] + cp + 1 >=l: b[i] = a[i] + cp + 1 else: b[i] = l cp = b[i] - a[i] if b[i] > r: print(-1) exit() print(*b)
{ "input": [ "4 2 9\n3 4 8 9\n3 2 1 4\n", "6 1 5\n1 1 1 1 1 1\n2 3 5 4 1 6\n", "5 1 5\n1 1 1 1 1\n3 1 5 4 2\n" ], "output": [ "2 2 2 9 ", "-1", "3 1 5 4 2 " ] }
3,514
8
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset. Input First line contains three integers n, k and m (2 ≀ k ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000) β€” number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the numbers in the multiset. Output If it is not possible to select k numbers in the desired way, output Β«NoΒ» (without the quotes). Otherwise, in the first line of output print Β«YesΒ» (without the quotes). In the second line print k integers b1, b2, ..., bk β€” the selected numbers. If there are multiple possible solutions, print any of them. Examples Input 3 2 3 1 8 4 Output Yes 1 4 Input 3 3 3 1 8 4 Output No Input 4 3 5 2 7 7 7 Output Yes 2 7 7
def solution(): n, k, m = map(int, input().split()) a = list(map(int, input().split())) d = [[] for i in range(m)] for i in a: d[i%m].append(i) for i in d: if len(i) >= k: print("Yes") print(*i[:k]) return print("No") solution()
{ "input": [ "3 3 3\n1 8 4\n", "4 3 5\n2 7 7 7\n", "3 2 3\n1 8 4\n" ], "output": [ "No\n", "Yes\n2 7 7\n", "Yes\n1 4\n" ] }
3,515
8
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug β€” the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
def check(l): global i return (l in squares and squares.index(l)!=i) inp= input() x,y=0,0 squares=[[x,y]] for i in range(len(inp)): if inp[i]=='L': x-=1 elif inp[i]=='R': x+=1 elif inp[i]=='U': y+=1 elif inp[i]=='D': y-=1 if [x,y]==[0,0] or check([x+1,y]) or check([x-1,y]) or check([x,y+1]) or check([x,y-1]): print("BUG") exit() squares.append([x,y]) print("OK")
{ "input": [ "RRUULLDD\n", "LLUUUR\n" ], "output": [ "BUG\n", "OK\n" ] }
3,516
7
Imp likes his plush toy a lot. <image> Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies. Initially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly x copied toys and y original toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies. Input The only line contains two integers x and y (0 ≀ x, y ≀ 109) β€” the number of copies and the number of original toys Imp wants to get (including the initial one). Output Print "Yes", if the desired configuration is possible, and "No" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input 6 3 Output Yes Input 4 2 Output No Input 1000 1001 Output Yes Note In the first example, Imp has to apply the machine twice to original toys and then twice to copies.
def psb(x,y): return y>=x-1 and (y-x)%2 and x>=2 or (x==1 and y==0) y,x=map(int,input().split()) if psb(x,y): s='Yes' else: s='No' print(s)
{ "input": [ "4 2\n", "1000 1001\n", "6 3\n" ], "output": [ "No\n", "Yes\n", "Yes\n" ] }
3,517
8
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something. The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people" Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" β€” he kept on repeating in his mind. β€” "Let's take, say, Max, Ilya, Vova β€” here, they all know each other! And now let's add Dima and Oleg to Vova β€” none of them is acquainted with each other! Now, that math is just rubbish!" Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people. Input The first line contains an integer m (0 ≀ m ≀ 10), which is the number of relations of acquaintances among the five friends of Igor's. Each of the following m lines contains two integers ai and bi (1 ≀ ai, bi ≀ 5;ai β‰  bi), where (ai, bi) is a pair of acquainted people. It is guaranteed that each pair of the acquaintances is described exactly once. The acquaintance relation is symmetrical, i.e. if x is acquainted with y, then y is also acquainted with x. Output Print "FAIL", if among those five people there are no either three pairwise acquainted or three pairwise unacquainted people. Otherwise print "WIN". Examples Input 4 1 3 2 3 1 4 5 3 Output WIN Input 5 1 2 2 3 3 4 4 5 5 1 Output FAIL
def s(): m = int(input()) s = set(tuple(sorted(list(map(int,input().split()))))for _ in range(m)) for i in range(1,4): for j in range(i+1,5): for k in range(j+1,6): r = ((i,j)in s) + ((j,k)in s) + ((i,k)in s) if r%3 == 0: print('WIN') return print('FAIL') s()
{ "input": [ "4\n1 3\n2 3\n1 4\n5 3\n", "5\n1 2\n2 3\n3 4\n4 5\n5 1\n" ], "output": [ "WIN\n", "FAIL\n" ] }
3,518
12
You are given an integer array of length n. You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to [x, x + 1, ..., x + k - 1] for some value x and length k. Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array [5, 3, 1, 2, 4] the following arrays are subsequences: [3], [5, 3, 1, 2, 4], [5, 1, 4], but the array [1, 3] is not. Input The first line of the input containing integer number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array. The second line of the input containing n integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9) β€” the array itself. Output On the first line print k β€” the maximum length of the subsequence of the given array that forms an increasing sequence of consecutive integers. On the second line print the sequence of the indices of the any maximum length subsequence of the given array that forms an increasing sequence of consecutive integers. Examples Input 7 3 3 4 7 5 6 8 Output 4 2 3 5 6 Input 6 1 3 5 2 4 6 Output 2 1 4 Input 4 10 9 8 7 Output 1 1 Input 9 6 7 8 3 4 5 9 10 11 Output 6 1 2 3 7 8 9 Note All valid answers for the first example (as sequences of indices): * [1, 3, 5, 6] * [2, 3, 5, 6] All valid answers for the second example: * [1, 4] * [2, 5] * [3, 6] All valid answers for the third example: * [1] * [2] * [3] * [4] All valid answers for the fourth example: * [1, 2, 3, 7, 8, 9]
import sys from math import * def input(): return sys.stdin.readline().strip() def input_line(): return map(int, input().split()) n = int(input()) a = list(input_line()) d = dict() p = dict() o = [0]*n q = [0]*n r = (0,0) for i in range(n): x = a[i] v = d.get(x-1, 0) + 1 r = max(r, (v, i)) o[i] = v q[i] = p.get(x-1, -1) d[x] = o[i] p[x] = i print(r[0]) z = [] x = r[1] while len(z) < r[0]: z.append(x+1) x = q[x] print(*z[::-1])
{ "input": [ "4\n10 9 8 7\n", "6\n1 3 5 2 4 6\n", "7\n3 3 4 7 5 6 8\n", "9\n6 7 8 3 4 5 9 10 11\n" ], "output": [ "1\n1 \n", "2\n1 4 \n", "4\n2 3 5 6 \n", "6\n1 2 3 7 8 9 \n" ] }
3,519
11
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider empty cells are denoted by '.', then the following figures are stars: <image> The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n Γ— m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n β‹… m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes. In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n β‹… m stars. Input The first line of the input contains two integers n and m (3 ≀ n, m ≀ 1000) β€” the sizes of the given grid. The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only. Output If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer k (0 ≀ k ≀ n β‹… m) β€” the number of stars needed to draw the given grid. The next k lines should contain three integers each β€” x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid. Examples Input 6 8 ....*... ...**... ..*****. ...**... ....*... ........ Output 3 3 4 1 3 5 2 3 5 1 Input 5 5 .*... ****. .**** ..**. ..... Output 3 2 2 1 3 3 1 3 4 1 Input 5 5 .*... ***.. .*... .*... ..... Output -1 Input 3 3 *.* .*. *.* Output -1 Note In the first example the output 2 3 4 1 3 5 2 is also correct.
def main(): n, m = map(int, input().split()) w = [c == '*' for i in range(n) for c in input()] nm = n * m q = [*[range(i, i + m) for i in range(0, nm, m)], *[range(i, nm, m) for i in range(m)]] e = [1000] * nm for f in True, False: for r in q: v = 0 for i in r: if w[i]: v += 1 if e[i] > v: e[i] = v else: v = e[i] = 0 if f: w.reverse() e.reverse() e = [c if c != 1 else 0 for c in e] for f in True, False: for r in q: v = 0 for i in r: if v > e[i]: v -= 1 else: v = e[i] if v: w[i] = False if f: w.reverse() e.reverse() if any(w): print(-1) else: r = [] for i, c in enumerate(e): if c: r.append(f'{i//m+1} {i%m+1} {c-1}') print(len(r), '\n'.join(r), sep='\n') main()
{ "input": [ "5 5\n.*...\n****.\n.****\n..**.\n.....\n", "6 8\n....*...\n...**...\n..*****.\n...**...\n....*...\n........\n", "3 3\n*.*\n.*.\n*.*\n", "5 5\n.*...\n***..\n.*...\n.*...\n.....\n" ], "output": [ "3\n2 2 1\n3 3 1\n3 4 1\n", "2\n3 4 1\n3 5 2\n", "-1\n", "-1\n" ] }
3,520
7
You are given a 4x4 grid. You play a game β€” there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time. Input The only line contains a string s consisting of zeroes and ones (1 ≀ |s| ≀ 1000). Zero describes vertical tile, one describes horizontal tile. Output Output |s| lines β€” for each tile you should output two positive integers r,c, not exceeding 4, representing numbers of smallest row and column intersecting with it. If there exist multiple solutions, print any of them. Example Input 010 Output 1 1 1 2 1 4 Note Following image illustrates the example after placing all three tiles: <image> Then the first row is deleted: <image>
import os import sys import math import heapq from decimal import * from io import BytesIO, IOBase from collections import defaultdict, deque def r(): return int(input()) def rm(): return map(int,input().split()) def rl(): return list(map(int,input().split())) '''A''' s = input() n = len(s) zero = False one = False for i in range(n): if s[i]=='0': if zero: print(3,1) else: print(1,1) zero = not zero else: if one: print(4,1) else: print(4,3) one = not one
{ "input": [ "010\n" ], "output": [ "1 1\n4 3\n3 1\n" ] }
3,521
7
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 β‰₯ w_2. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field. The rectangles are placed on field in the following way: * the second rectangle is on top the first rectangle; * they are aligned to the left, i.e. their left sides are on the same line; * the rectangles are adjacent to each other without a gap. See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue. Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates (1, 1), the rightmost top cell of the first rectangle has coordinates (w_1, h_1), the leftmost bottom cell of the second rectangle has coordinates (1, h_1 + 1) and the rightmost top cell of the second rectangle has coordinates (w_2, h_1 + h_2). After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green. Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction. Input Four lines contain integers w_1, h_1, w_2 and h_2 (1 ≀ w_1, h_1, w_2, h_2 ≀ 10^8, w_1 β‰₯ w_2) β€” the width of the first rectangle, the height of the first rectangle, the width of the second rectangle and the height of the second rectangle. You can't rotate the rectangles. Output Print exactly one integer β€” the number of cells, which should be marked after the ship is destroyed. Examples Input 2 1 2 1 Output 12 Input 2 2 1 2 Output 16 Note In the first example the field looks as follows (the first rectangle is red, the second rectangle is blue, green shows the marked squares): <image> In the second example the field looks as: <image>
def main(): w1,h1,w2,h2=map(int,input().split()) print(2*(h1+h2+w1+2)) main()
{ "input": [ "2 1 2 1\n", "2 2 1 2\n" ], "output": [ "12\n", "16\n" ] }
3,522
9
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task. Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, …), and the second set consists of even positive numbers (2, 4, 6, 8, …). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage β€” the first two numbers from the second set, on the third stage β€” the next four numbers from the first set, on the fourth β€” the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: 1, 2, 4, 3, 5, 7, 9, 6, 8, 10. Let's number the numbers written, starting with one. The task is to find the sum of numbers with numbers from l to r for given integers l and r. The answer may be big, so you need to find the remainder of the division by 1000000007 (10^9+7). Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem. Input The first line contains two integers l and r (1 ≀ l ≀ r ≀ 10^{18}) β€” the range in which you need to find the sum. Output Print a single integer β€” the answer modulo 1000000007 (10^9+7). Examples Input 1 3 Output 7 Input 5 14 Output 105 Input 88005553535 99999999999 Output 761141116 Note In the first example, the answer is the sum of the first three numbers written out (1 + 2 + 4 = 7). In the second example, the numbers with numbers from 5 to 14: 5, 7, 9, 6, 8, 10, 12, 14, 16, 18. Their sum is 105.
def cnts(n): t = 1 set_num = 1 cnt = [0, 0] while t < n: cnt[set_num] += t n -= t t <<= 1 set_num ^= 1 cnt[set_num] += n return cnt def f(n): l, r = cnts(n) return l * (l + 1) + r * r l, r = map(int, input().split()) print((f(r) - f(l - 1)) % int(1e9 + 7))
{ "input": [ "5 14\n", "1 3\n", "88005553535 99999999999\n" ], "output": [ "105\n", "7\n", "761141116\n" ] }
3,523
8
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a mΓ— m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered from 1 to n on the chessboard, the i-th piece lies on (r_i,\,c_i), while the following rule is satisfied: for all pairs of pieces i and j, |r_i-r_j|+|c_i-c_j|β‰₯|i-j|. Here |x| means the absolute value of x. However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small. She wants to find the smallest chessboard on which she can put n pieces according to the rules. She also wonders how to place the pieces on such a chessboard. Can you help her? Input The only line contains a single integer n (1≀ n≀ 1000) β€” the number of chess pieces for the game. Output The first line contains a single integer β€” the minimum value of m, where m is the length of sides of the suitable chessboard. The i-th of the next n lines contains two integers r_i and c_i (1≀ r_i,c_i≀ m) β€” the coordinates of the i-th chess piece. If there are multiple answers, print any. Examples Input 2 Output 2 1 1 1 2 Input 4 Output 3 1 1 1 3 3 1 3 3 Note In the first example, you can't place the two pieces on a 1Γ—1 chessboard without breaking the rule. But you can place two pieces on a 2Γ—2 chessboard like this: <image> In the second example, you can't place four pieces on a 2Γ—2 chessboard without breaking the rule. For example, if you place the pieces like this: <image> then |r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1, |1-3|=2, 1<2; and |r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2, |1-4|=3, 2<3. It doesn't satisfy the rule. However, on a 3Γ—3 chessboard, you can place four pieces like this: <image>
def func(n,k): i=1 for i in range(k): print(f"{1} {i+1}") a = k-(n-k)+1 while(a<k or a == k): print(f"{k} {a}") a+=1 n = int(input()) k = int((n/2)+1) print(k) func(n,k)
{ "input": [ "2\n", "4\n" ], "output": [ "2\n1 1\n1 2\n", "3\n1 1\n1 2\n1 3\n2 3\n" ] }
3,524
8
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya was delivered a string s, containing only digits. He needs to find a string that * represents a lucky number without leading zeroes, * is not empty, * is contained in s as a substring the maximum number of times. Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya. Input The single line contains a non-empty string s whose length can range from 1 to 50, inclusive. The string only contains digits. The string can contain leading zeroes. Output In the only line print the answer to Petya's problem. If the sought string does not exist, print "-1" (without quotes). Examples Input 047 Output 4 Input 16 Output -1 Input 472747 Output 7 Note The lexicographical comparison of strings is performed by the < operator in the modern programming languages. String x is lexicographically less than string y either if x is a prefix of y, or exists such i (1 ≀ i ≀ min(|x|, |y|)), that xi < yi and for any j (1 ≀ j < i) xj = yj. Here |a| denotes the length of string a. In the first sample three conditions are fulfilled for strings "4", "7" and "47". The lexicographically minimum one is "4". In the second sample s has no substrings which are lucky numbers. In the third sample the three conditions are only fulfilled for string "7".
def lucky(string): if string.count("4")==0 and string.count("7")==0: return -1 return (max("4","7",key=lambda s:string.count(s))) print(lucky(input()))
{ "input": [ "472747\n", "16\n", "047\n" ], "output": [ "7\n", "-1\n", "4\n" ] }
3,525
7
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string s appeared on the screen. When Polycarp presses a button with character c, one of the following events happened: * if the button was working correctly, a character c appeared at the end of the string Polycarp was typing; * if the button was malfunctioning, two characters c appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a β†’ abb β†’ abba β†’ abbac β†’ abbaca β†’ abbacabb β†’ abbacabba. You are given a string s which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning). You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string s consisting of no less than 1 and no more than 500 lowercase Latin letters. Output For each test case, print one line containing a string res. The string res should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, res should be empty. Example Input 4 a zzaaz ccff cbddbb Output a z bc
def solve(s): r = {} t = s[0] for v in s[1:] + ' ': if v != t: if len(t) == 1: r[t] = 1 t = v else: t += v return ''.join(sorted(r)) for _ in range(int(input())): print(solve(input()))
{ "input": [ "4\na\nzzaaz\nccff\ncbddbb\n" ], "output": [ "a\nz\n\nbc\n" ] }
3,526
11
Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≀ l_1 ≀ r_1 ≀ n) and a segment [l_2, r_2] (1 ≀ l_2 ≀ r_2 ≀ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≀ x ≀ r_1 and l_2 ≀ x ≀ r_2; * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. Input The first line contains integers n and m (1 ≀ n ≀ 500 000, 2 ≀ m ≀ 2 β‹… n) β€” the length of strings a and b and the length of the string s. The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m. All strings consist of lowercase English letters. Output Print one integer β€” the number of ways to choose a pair of segments, which satisfy Vasya's conditions. Examples Input 6 5 aabbaa baaaab aaaaa Output 4 Input 5 4 azaza zazaz azaz Output 11 Input 9 12 abcabcabc xyzxyzxyz abcabcayzxyz Output 2 Note Let's list all the pairs of segments that Vasya could choose in the first example: 1. [2, 2] and [2, 5]; 2. [1, 2] and [2, 4]; 3. [5, 5] and [2, 5]; 4. [5, 6] and [3, 5];
import sys, logging logging.basicConfig(level=logging.INFO) logging.disable(logging.INFO) def build(S, n): Z = [0 for i in range(3 * n + 3)] #logging.info(S) n = len(S) L = 0 R = 0 Z[0] = n for i in range(1, n): if(i > R): L = R = i while(R < n and S[R] == S[R - L]): R += 1 Z[i] = R - L R -= 1 else: k = i - L if(Z[k] < R - i + 1): Z[i] = Z[k] else: L = i while(R < n and S[R] == S[R - L]): R += 1 Z[i] = R - L R -= 1 return Z def update1(n, x, val): while(x <= n + 1): bit1[x] += val x += x & -x def get1(n, x): ans = 0 while(x > 0): ans += bit1[x] x -= x & -x return ans def update2(n, x, val): while(x <= n + 1): bit2[x] += val x += x & -x def get2(n, x): ans = 0 while(x > 0): ans += bit2[x] x -= x & -x return ans def process(n, m, fa, fb): r2 = int(1) ans = 0 for l1 in range(1, n + 1): while(r2 <= min(n, l1 + m - 2)): update1(n, m - fb[r2] + 1, 1) update2(n, m - fb[r2] + 1, fb[r2] - m + 1) r2 += 1 ans += get1(n, fa[l1] + 1) * fa[l1] + get2(n, fa[l1] + 1) update1(n, m - fb[l1] + 1, -1) update2(n, m - fb[l1] + 1, m - 1 - fb[l1]) print(ans) def main(): n, m = map(int, sys.stdin.readline().split()) a = sys.stdin.readline() b = sys.stdin.readline() s = sys.stdin.readline() a = a[:(len(a) - 1)] b = b[:(len(b) - 1)] s = s[:(len(s) - 1)] fa = build(s + a, n) kb = build(s[::-1] + b[::-1], n) fb = [0 for k in range(n + 2)] for i in range(m, m + n): fa[i - m + 1] = fa[i] if(fa[i - m + 1] >= m): fa[i - m + 1] = m - 1 fb[m + n - i] = kb[i] if(fb[m + n - i] >= m): fb[m + n - i] = m - 1 logging.info(fa[1:(n + 1)]) logging.info(fb[1:(n + 1)]) process(n, m, fa, fb) bit1 = [0 for i in range(500004)] bit2 = [0 for i in range(500004)] if __name__ == "__main__": try: sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass main()
{ "input": [ "5 4\nazaza\nzazaz\nazaz\n", "6 5\naabbaa\nbaaaab\naaaaa\n", "9 12\nabcabcabc\nxyzxyzxyz\nabcabcayzxyz\n" ], "output": [ "11", "4", "2" ] }
3,527
9
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≀ n ≀ 3000). The second line contains a string T of length m (1 ≀ m ≀ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer β€” the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6Γ—2=12.
from sys import stdin, stdout def kaavi_and_magic_spell(S, T): MOD = 998244353 n = len(S) m = len(T) dp = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): if comp(S, T, 0, i): dp[i][i] = 1 for l in range(2, n+1): for i in range(n - l + 1): if comp(S, T, l-1, i): # front dp[i][i+l-1] += dp[i+1][i+l-1] dp[i][i+l-1] %= MOD if comp(S, T, l-1, i+l-1): # back dp[i][i+l-1] += dp[i][i+l-2] dp[i][i+l-1] %= MOD r = 0 for j in range(m-1, n): r += dp[0][j] r %= MOD r *= 2 r %= MOD return r def comp(S, T, i, j): if j >= len(T): return True return S[i] == T[j] S = stdin.readline().strip() T = stdin.readline().strip() r = kaavi_and_magic_spell(S, T) stdout.write(str(r) + '\n')
{ "input": [ "defineintlonglong\nsignedmain\n", "rotator\nrotator\n", "cacdcdbbbb\nbdcaccdbbb\n", "abab\nba\n" ], "output": [ "0", "4", "24", "12" ] }
3,528
12
Oh, no! The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem. You are given two arrays A and B of size n. You can do operations of two types with array A: * Reverse array A. That is the array [A_1,\ A_2,\ …,\ A_n] transformes into [A_n,\ A_{n-1},\ …,\ A_1]. * Replace A with an array of its prefix sums. That is, the array [A_1,\ A_2,\ …,\ A_n] goes to [A_1,\ (A_1+A_2),\ …,\ (A_1+A_2+…+A_n)]. You need to understand if you can get an array B from the array A. If it is possible, you will have to restore the order of these operations by minimizing the number of operations of the second type. Fortunately, the coronavirus is good today, so he has allowed you not to restore actions if the minimum number of second type operations is more than 2β‹… 10^5. But coronavirus resents you, so if you restore the answer, the total number of operations should not exceed 5β‹… 10^5. Solve this problem and get the cookie, or the coronavirus will extend the quarantine for five years and make the whole economy collapse! Input The first line contains a single integer n (1≀ n ≀ 2β‹… 10^5). The second line contains n integers A_1, A_2, …, A_n (1 ≀ A_i ≀ 10 ^ {12}). The third line contains n integers B_1, B_2, …, B_n (1 ≀ B_i ≀ 10 ^ {12}). Output If you cannot get B from the A array, print "IMPOSSIBLE" (without quotes) on a single line. If the minimum number of operations of the second type exceeds 2β‹… 10^5, print "BIG" (without quotes). In the second line print the number of operations of the second type, that needs to be applied to get array B from A. Otherwise, in the first line print "SMALL" (without quotes). In the second line print the total number of operations of the first and second types m ≀ 5β‹… 10^5 (it is guaranteed that in this case there is such a sequence of actions). In the third line print a line of length m, consisting of characters 'R"and 'P' (without quotes). The i-th character should be 'R', if the i-th action is of the first type, and should be 'P', otherwise. If there are several such sequences, you can print any of them. You can print each character in the uppercase or in the lowercase. Examples Input 2 5 7 5 7 Output SMALL 0 Input 2 1 1 300000 1 Output BIG 299999 Input 2 10 1 13 14 Output SMALL 6 RPPPRP Input 3 1 2 1 2 1 2 Output IMPOSSIBLE Note In the first example, the arrays A and B already equal, so the number of required operations =0. In the second example, we need to replace A with the prefix sums 299999 times and then reverse the array. Since 299999>2β‹… 10^5, there is no need to restore the answer. In the fourth example, you cannot get B from the A.
import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): n=II() aa=LI() raa=aa[::-1] bb=LI() if n==1: if aa==bb: print("SMALL") print(0) else: print("IMPOSSIBLE") exit() if n==2: mna=min(aa) cntp=0 x,y=bb if x>y:x,y=y,x while mna<x: c=y//x cntp+=c y-=c*x if x>y:x,y=y,x d=y-max(aa) if mna!=x or d%x: print("IMPOSSIBLE") exit() cntp+=d//x if cntp>200000: print("BIG") print(cntp) exit() ans="" cntp=0 while 1: if aa==bb: if cntp > 200000: print("BIG") print(cntp) else: print("SMALL") print(len(ans)) if ans:print(ans[::-1]) exit() if raa==bb: if cntp > 200000: print("BIG") print(cntp) else: ans+="R" print("SMALL") print(len(ans)) if ans:print(ans[::-1]) exit() if bb[0]<=bb[-1]: if cntp<=200000:ans+="P" cntp+=1 for i in range(n-2,-1,-1): bb[i+1]-=bb[i] if bb[i+1]<=0: print("IMPOSSIBLE") exit() else: if cntp<=200000:ans+="R" bb.reverse() main()
{ "input": [ "2\n5 7\n5 7\n", "3\n1 2 1\n2 1 2\n", "2\n10 1\n13 14\n", "2\n1 1\n300000 1\n" ], "output": [ "SMALL\n0\n\n", "IMPOSSIBLE\n", "SMALL\n6\nRPPPRP\n", "BIG\n299999\n" ] }
3,529
8
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≀ a,b,c ≀ r, and then he computes the encrypted value m = n β‹… a + b - c. Unfortunately, an adversary intercepted the values l, r and m. Is it possible to recover the original values of a, b and c from this information? More formally, you are asked to find any values of a, b and c such that * a, b and c are integers, * l ≀ a, b, c ≀ r, * there exists a strictly positive integer n, such that n β‹… a + b - c = m. Input The first line contains the only integer t (1 ≀ t ≀ 20) β€” the number of test cases. The following t lines describe one test case each. Each test case consists of three integers l, r and m (1 ≀ l ≀ r ≀ 500 000, 1 ≀ m ≀ 10^{10}). The numbers are such that the answer to the problem exists. Output For each test case output three integers a, b and c such that, l ≀ a, b, c ≀ r and there exists a strictly positive integer n such that n β‹… a + b - c = m. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions. Example Input 2 4 6 13 2 3 1 Output 4 6 5 2 2 3 Note In the first example n = 3 is possible, then n β‹… 4 + 6 - 5 = 13 = m. Other possible solutions include: a = 4, b = 5, c = 4 (when n = 3); a = 5, b = 4, c = 6 (when n = 3); a = 6, b = 6, c = 5 (when n = 2); a = 6, b = 5, c = 4 (when n = 2). In the second example the only possible case is n = 1: in this case n β‹… 2 + 2 - 3 = 1 = m. Note that, n = 0 is not possible, since in that case n is not a strictly positive integer.
def solve(): l,r,m = list(map(int,input().split())) for a in range(l,r+1): mod = m%a if(m//a==0):mod -= a if(mod>r-l):mod=mod-a if(mod < r-l+1 and mod>l-r-1): if(mod<0):print(a,' ',l, ' ',l-mod) else: print(a,' ',l+mod,' ',l) return tt = int(input()) for i in range(tt): solve()
{ "input": [ "2\n4 6 13\n2 3 1\n" ], "output": [ "4 5 4\n2 2 3\n" ] }
3,530
12
You are given n segments on a coordinate axis OX. The i-th segment has borders [l_i; r_i]. All points x, for which l_i ≀ x ≀ r_i holds, belong to the i-th segment. Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one. Two segments [l_i; r_i] and [l_j; r_j] are non-intersecting if they have no common points. For example, segments [1; 2] and [3; 4], [1; 3] and [5; 5] are non-intersecting, while segments [1; 2] and [2; 3], [1; 2] and [2; 2] are intersecting. The segment [l_i; r_i] lies inside the segment [l_j; r_j] if l_j ≀ l_i and r_i ≀ r_j. For example, segments [2; 2], [2, 3], [3; 4] and [2; 4] lie inside the segment [2; 4], while [2; 5] and [1; 4] are not. 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 first line of the test case contains one integer n (1 ≀ n ≀ 3000) β€” the number of segments. The next n lines describe segments. The i-th segment is given as two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 2 β‹… 10^5), where l_i is the left border of the i-th segment and r_i is the right border of the i-th segment. Additional constraint on the input: there are no duplicates in the list of segments. It is guaranteed that the sum of n does not exceed 3000 (βˆ‘ n ≀ 3000). Output For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one. Example Input 4 4 1 5 2 4 2 3 3 4 5 1 5 2 3 2 5 3 5 2 2 3 1 3 2 4 2 3 7 1 10 2 8 2 5 3 4 4 4 6 8 7 7 Output 3 4 2 7
def solve(): n = int(input()) LR = [tuple(map(int,input().split())) for i in range(n)] s = set() for l,r in LR: s.add(l) s.add(r) dic = {x:i for i,x in enumerate(sorted(list(s)))} le = len(s) seg = [[] for i in range(le)] for l,r in LR: seg[dic[r]].append(dic[l]) dp = [[len(seg[0])]] for i in range(1,le): dp.append(dp[-1]+[0]) for l in sorted(seg[i],reverse=True): dp[i][l] += 1 for j in range(l): dp[i][j] = max(dp[i][j],dp[i][l]+dp[l-1][j]) return dp[-1][0] t = int(input()) for _ in range(t): ans = solve() print(ans)
{ "input": [ "4\n4\n1 5\n2 4\n2 3\n3 4\n5\n1 5\n2 3\n2 5\n3 5\n2 2\n3\n1 3\n2 4\n2 3\n7\n1 10\n2 8\n2 5\n3 4\n4 4\n6 8\n7 7\n" ], "output": [ "3\n4\n2\n7\n" ] }
3,531
9
You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u β†’ v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u β†’ v by an edge v β†’ u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≀ n, m ≀ 200 000). The next m lines contain two integers each: u, v (1 ≀ u, v ≀ n; u β‰  v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
import sys input = sys.stdin.readline import heapq mod=998244353 n,m=map(int,input().split()) E=[[] for i in range(n+1)] E2=[[] for i in range(n+1)] for i in range(m): x,y=map(int,input().split()) E[x].append(y) E2[y].append(x) TIME=[1<<29]*(n+1) TIME[1]=0 def shuku(x,y): return (x<<20)+y Q=[] ANS=[] for k in range(n+1): NQ=[] if k<=1: heapq.heappush(Q,shuku(0,1)) if k%2==0: while Q: #print(Q) x=heapq.heappop(Q) time=x>>20 town=x-(time<<20) #print(x,time,town) if TIME[town]<time: continue for to in E[town]: if TIME[to]>time+1: TIME[to]=time+1 heapq.heappush(Q,shuku(TIME[to],to)) heapq.heappush(NQ,shuku(TIME[to],to)) else: while Q: x=heapq.heappop(Q) time=x>>20 town=x-(time<<20) #print(x,time,town) if TIME[town]<time: continue for to in E2[town]: if TIME[to]>time+1: TIME[to]=time+1 heapq.heappush(Q,shuku(TIME[to],to)) heapq.heappush(NQ,shuku(TIME[to],to)) #print(k,TIME) Q=NQ ANS.append(TIME[n]) if k>=100 and TIME[n]!=1<<29: break A=ANS[0] for k in range(1,len(ANS)): if ANS[k]==1<<29: continue if ANS[k-1]==1<<29: A=(ANS[k]+pow(2,k,mod)-1)%mod if k<60 and ANS[k-1]-ANS[k]>pow(2,k-1): A=(ANS[k]+pow(2,k,mod)-1)%mod print(A)
{ "input": [ "4 3\n2 1\n2 3\n4 3\n", "4 4\n1 2\n2 3\n3 4\n4 1\n" ], "output": [ "10\n", "2\n" ] }
3,532
11
Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 ≀ i ≀ 4). These segments can intersect with each other, and each segment should be either horizontal or vertical. Monocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible. For example, if Monocarp wants to draw four segments with lengths 1, 2, 3 and 4, he can do it the following way: <image> Here, Monocarp has drawn segments AB (with length 1), CD (with length 2), BC (with length 3) and EF (with length 4). He got a rectangle ABCF with area equal to 3 that is enclosed by the segments. Calculate the maximum area of a rectangle Monocarp can enclose with four segments. Input The first line contains one integer t (1 ≀ t ≀ 3 β‹… 10^4) β€” the number of test cases. Each test case consists of a single line containing four integers a_1, a_2, a_3, a_4 (1 ≀ a_i ≀ 10^4) β€” the lengths of the segments Monocarp wants to draw. Output For each test case, print one integer β€” the maximum area of a rectangle Monocarp can enclose with four segments (it can be shown that the answer is always an integer). Example Input 4 1 2 3 4 5 5 5 5 3 1 4 1 100 20 20 100 Output 3 25 3 2000 Note The first test case of the example is described in the statement. For the second test case, Monocarp can draw the segments AB, BC, CD and DA as follows: <image> Here, Monocarp has drawn segments AB (with length 5), BC (with length 5), CD (with length 5) and DA (with length 5). He got a rectangle ABCD with area equal to 25 that is enclosed by the segments.
def solve(): n = [ int(x) for x in input().split() ] n.sort() print(n[0]*n[2]) t = int(input()) while t > 0: solve() t -= 1
{ "input": [ "4\n1 2 3 4\n5 5 5 5\n3 1 4 1\n100 20 20 100\n" ], "output": [ "\n3\n25\n3\n2000\n" ] }
3,533
10
You are given three integers a, b, k. Find two binary integers x and y (x β‰₯ y) such that 1. both x and y consist of a zeroes and b ones; 2. x - y (also written in binary form) has exactly k ones. You are not allowed to use leading zeros for x and y. Input The only line contains three integers a, b, and k (0 ≀ a; 1 ≀ b; 0 ≀ k ≀ a + b ≀ 2 β‹… 10^5) β€” the number of zeroes, ones, and the number of ones in the result. Output If it's possible to find two suitable integers, print "Yes" followed by x and y in base-2. Otherwise print "No". If there are multiple possible answers, print any of them. Examples Input 4 2 3 Output Yes 101000 100001 Input 3 2 1 Output Yes 10100 10010 Input 3 2 5 Output No Note In the first example, x = 101000_2 = 2^5 + 2^3 = 40_{10}, y = 100001_2 = 2^5 + 2^0 = 33_{10}, 40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}. Hence x-y has 3 ones in base-2. In the second example, x = 10100_2 = 2^4 + 2^2 = 20_{10}, y = 10010_2 = 2^4 + 2^1 = 18, x - y = 20 - 18 = 2_{10} = 10_{2}. This is precisely one 1. In the third example, one may show, that it's impossible to find an answer.
def solution(): a, b, k = map(int, input().split()) if k > max(a + b - 2, 0) or (b == 1 and k != 0) or (a == 0 and k != 0): print("No") elif k <= a: print("Yes", b * "1" + a * "0", (b - 1) * "1" + k * "0" + "1" + (a - k) * "0", sep="\n") else: print("Yes", b * "1" + a * "0", (b + a - k - 1) * "1" + "0" + (k - a) * "1" + (a - 1) * "0" + "1", sep="\n") solution()
{ "input": [ "4 2 3\n", "3 2 5\n", "3 2 1\n" ], "output": [ "\nYes\n101000\n100001\n", "\nNo\n", "\nYes\n10100\n10010\n" ] }
3,534
11
There are n computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer i-1 and computer i+1 are both on, computer i (2 ≀ i ≀ n-1) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn on a computer that already turned on automatically. If we only consider the sequence of computers that Phoenix turns on manually, how many ways can he turn on all the computers? Two sequences are distinct if either the set of computers turned on manually is distinct, or the order of computers turned on manually is distinct. Since this number may be large, please print it modulo M. Input The first line contains two integers n and M (3 ≀ n ≀ 400; 10^8 ≀ M ≀ 10^9) β€” the number of computers and the modulo. It is guaranteed that M is prime. Output Print one integer β€” the number of ways to turn on the computers modulo M. Examples Input 3 100000007 Output 6 Input 4 100000007 Output 20 Input 400 234567899 Output 20914007 Note In the first example, these are the 6 orders in which Phoenix can turn on all computers: * [1,3]. Turn on computer 1, then 3. Note that computer 2 turns on automatically after computer 3 is turned on manually, but we only consider the sequence of computers that are turned on manually. * [3,1]. Turn on computer 3, then 1. * [1,2,3]. Turn on computer 1, 2, then 3. * [2,1,3] * [2,3,1] * [3,2,1]
from math import factorial n, mod = map(int, input().split()) def binom(n, m): return factorial(n) // factorial(m) // factorial(n-m) def foo(x, k): ans = 0 for i in range(k, 0, -1):sign = 1 if (i-k)%2 == 0 else -1;ans += sign * binom(k, i) * (i**x);ans %= mod return ans def f(x, k): return (foo(x, k) * pow(2, x-k, mod)) % mod ans = 0 for i in range((n+1)//2):ans = (ans + f(n-i, i+1));ans %= mod print(ans)
{ "input": [ "400 234567899\n", "4 100000007\n", "3 100000007\n" ], "output": [ "\n20914007\n", "\n20\n", "\n6\n" ] }
3,535
10
You are given a sequence A, where its elements are either in the form + x or -, where x is an integer. For such a sequence S where its elements are either in the form + x or -, define f(S) as follows: * iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through it. * for each element, if it's in the form + x, add x to T; otherwise, erase the smallest element from T (if T is empty, do nothing). * after iterating through all S's elements, compute the sum of all elements in T. f(S) is defined as the sum. The sequence b is a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For all A's subsequences B, compute the sum of f(B), modulo 998 244 353. Input The first line contains an integer n (1≀ n≀ 500) β€” the length of A. Each of the next n lines begins with an operator + or -. If the operator is +, then it's followed by an integer x (1≀ x<998 244 353). The i-th line of those n lines describes the i-th element in A. Output Print one integer, which is the answer to the problem, modulo 998 244 353. Examples Input 4 - + 1 + 2 - Output 16 Input 15 + 2432543 - + 4567886 + 65638788 - + 578943 - - + 62356680 - + 711111 - + 998244352 - - Output 750759115 Note In the first example, the following are all possible pairs of B and f(B): * B= {}, f(B)=0. * B= {-}, f(B)=0. * B= {+ 1, -}, f(B)=0. * B= {-, + 1, -}, f(B)=0. * B= {+ 2, -}, f(B)=0. * B= {-, + 2, -}, f(B)=0. * B= {-}, f(B)=0. * B= {-, -}, f(B)=0. * B= {+ 1, + 2}, f(B)=3. * B= {+ 1, + 2, -}, f(B)=2. * B= {-, + 1, + 2}, f(B)=3. * B= {-, + 1, + 2, -}, f(B)=2. * B= {-, + 1}, f(B)=1. * B= {+ 1}, f(B)=1. * B= {-, + 2}, f(B)=2. * B= {+ 2}, f(B)=2. The sum of these values is 16.
def main(): mod=998244353 n=int(input()) a=[] for i in range(n): t=input() if t[0]=='-': a.append(-1) else: a.append(int(t.split()[-1])) ans=0 for i in range(n): if a[i]==-1: continue dp=[0]*(n+1) dp[0]=1 buf=1 for j in range(n): if j<i: if a[j]==-1: dp[0]=dp[0]*2%mod for k in range(1,j+1): dp[k-1]=(dp[k-1]+dp[k])%mod elif a[j]<=a[i]: for k in range(j,-1,-1): dp[k+1]=(dp[k+1]+dp[k])%mod else: buf=buf*2%mod elif i<j: if a[j]==-1: for k in range(1,j+1): dp[k-1]=(dp[k-1]+dp[k])%mod elif a[j]<a[i]: for k in range(j,-1,-1): dp[k+1]=(dp[k+1]+dp[k])%mod else: buf=buf*2%mod ans=(ans+a[i]*sum(dp)*buf)%mod print(ans) main()
{ "input": [ "15\n+ 2432543\n-\n+ 4567886\n+ 65638788\n-\n+ 578943\n-\n-\n+ 62356680\n-\n+ 711111\n-\n+ 998244352\n-\n-\n", "4\n-\n+ 1\n+ 2\n-\n" ], "output": [ "750759115\n", "16\n" ] }
3,536
10
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: Β«[date:time]: messageΒ», where for each Β«[date:time]Β» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer β€” Alex β€” managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format Β«[time]: messageΒ». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written. So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications). We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day. Input The first input line contains number n (1 ≀ n ≀ 100). The following n lines contain recordings in format Β«[time]: messageΒ», where time is given in format Β«hh:mm x.m.Β». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character Β«aΒ» or character Β«pΒ». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20. Output Output one number β€” the minimum amount of days covered by the log. Examples Input 5 [05:00 a.m.]: Server is started [05:00 a.m.]: Rescan initialized [01:13 p.m.]: Request processed [01:10 p.m.]: Request processed [11:40 p.m.]: Rescan completed Output 2 Input 3 [09:00 a.m.]: User logged in [08:00 a.m.]: User logged in [07:00 a.m.]: User logged in Output 3 Note Formally the 12-hour time format is described at: * http://en.wikipedia.org/wiki/12-hour_clock. The problem authors recommend you to look through these descriptions before you start with the problem.
def gt(a): hr = a[:2] mi = a[3:5] t = a[6] p = (int(hr)%12)*60+int(mi) if t == "p": return p + 100000 return p n = int(input()) s = [input()[1:8] for i in range(n)] cnt = 1 sc = 1 for i in range(1, n): if s[i] == s[i-1]: sc += 1 if sc == 11: sc = 1 cnt += 1 else: sc = 1 cnt += (gt(s[i-1]) > gt(s[i])) print(cnt)
{ "input": [ "5\n[05:00 a.m.]: Server is started\n[05:00 a.m.]: Rescan initialized\n[01:13 p.m.]: Request processed\n[01:10 p.m.]: Request processed\n[11:40 p.m.]: Rescan completed\n", "3\n[09:00 a.m.]: User logged in\n[08:00 a.m.]: User logged in\n[07:00 a.m.]: User logged in\n" ], "output": [ "2\n", "3\n" ] }
3,537
8
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal β€” their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β€” that's the strategy the flatlanders usually follow when they besiege cities. The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs. That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β‰₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β€” as a disk (including the border) with the center at the point where the radar is placed. Input The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≀ 104; 1 ≀ ri ≀ 104) β€” the city's coordinates and the distance from the city to the flatlanders, correspondingly. It is guaranteed that the cities are located at different points. Output Print a single real number β€” the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6. Examples Input 0 0 1 6 0 3 Output 1.000000000000000 Input -10 10 3 10 -10 3 Output 11.142135623730951 Note The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0). <image> The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0). <image>
x1, y1, r1 = map(int, input().split()) x2, y2, r2 = map(int, input().split()) sq = lambda x : x * x dis = (sq(x1 - x2) + sq(y1 - y2))**0.5 def solve(L, r1, r2): if r1 < r2: r1, r2 = r2, r1 if L >= r1 + r2: return L - r1 - r2 elif L <= r1 - r2: return r1 - L - r2 else: return 0 print(solve(dis, r1, r2) / 2)
{ "input": [ "0 0 1\n6 0 3\n", "-10 10 3\n10 -10 3\n" ], "output": [ "1.0000000000\n", "11.1421356237\n" ] }
3,538
8
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes. Each digit is allowed to occur in the number the same number of times it occurs in the set. Input A single line contains a single integer n (1 ≀ n ≀ 100000) β€” the number of digits in the set. The second line contains n digits, the digits are separated by a single space. Output On a single line print the answer to the problem. If such number does not exist, then you should print -1. Examples Input 1 0 Output 0 Input 11 3 4 5 4 5 3 5 3 4 4 0 Output 5554443330 Input 8 3 2 5 1 5 2 2 3 Output -1 Note In the first sample there is only one number you can make β€” 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.
def ep(msg): print(str(msg)) exit() n = input() l = list(map(int, input().split())) if 0 not in l: ep(-1) if sum(l) == 0: ep(0) l.sort() r = sum(l) % 3 if r == 0: l.reverse() ep(''.join(map(str, l))) i = next((i for i, v in enumerate(l) if v % 3 == r), -1) if i != -1: del l[i] else: del l[next(i for i, v in enumerate(l) if v % 3 == 3 - r)] del l[next(i for i, v in enumerate(l) if v % 3 == 3 - r)] if sum(l) == 0: ep(0) l.reverse() ep(''.join(map(str, l)))
{ "input": [ "1\n0\n", "11\n3 4 5 4 5 3 5 3 4 4 0\n", "8\n3 2 5 1 5 2 2 3\n" ], "output": [ "0\n", "5554443330\n", "-1\n" ] }
3,539
8
This problem is the most boring one you've ever seen. Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the result subsequences. Note, that one of the result subsequences can be empty. Let's define function f(ai, aj) on pairs of distinct elements (that is i β‰  j) in the original sequence. If ai and aj are in the same subsequence in the current partition then f(ai, aj) = ai + aj otherwise f(ai, aj) = ai + aj + h. Consider all possible values of the function f for some partition. We'll call the goodness of this partiotion the difference between the maximum value of function f and the minimum value of function f. Your task is to find a partition of the given sequence a that have the minimal possible goodness among all possible partitions. Input The first line of input contains integers n and h (2 ≀ n ≀ 105, 0 ≀ h ≀ 108). In the second line there is a list of n space-separated integers representing a1, a2, ..., an (0 ≀ ai ≀ 108). Output The first line of output should contain the required minimum goodness. The second line describes the optimal partition. You should print n whitespace-separated integers in the second line. The i-th integer is 1 if ai is in the first subsequence otherwise it should be 2. If there are several possible correct answers you are allowed to print any of them. Examples Input 3 2 1 2 3 Output 1 1 2 2 Input 5 10 0 1 0 2 1 Output 3 2 2 2 2 2 Note In the first sample the values of f are as follows: f(1, 2) = 1 + 2 + 2 = 5, f(1, 3) = 1 + 3 + 2 = 6 and f(2, 3) = 2 + 3 = 5. So the difference between maximum and minimum values of f is 1. In the second sample the value of h is large, so it's better for one of the sub-sequences to be empty.
#https://codeforces.com/problemset/problem/238/B n, h = map(int, input().split()) a = list(map(int, input().split())) b = [[x, i] for i, x in enumerate(a)] b = sorted(b, key=lambda x:x[0]) def solve(a, n, h): if n == 2: return 0, [1, 1] min_ = (a[-1][0] + a[-2][0]) - (a[0][0] + a[1][0]) # move a[0] to 2th-group min_2 = max(a[-1][0] + a[-2][0], a[-1][0] + a[0][0] + h) - min(a[0][0] + a[1][0] +h, a[1][0] + a[2][0]) ans = [1] * n if min_2 < min_: min_ = min_2 ans[a[0][1]] = 2 return min_, ans min_, ans = solve(b, n, h) print(min_) print(' '.join([str(x) for x in ans])) #5 10 #0 1 0 2 1 #3 2 #1 2 3
{ "input": [ "5 10\n0 1 0 2 1\n", "3 2\n1 2 3\n" ], "output": [ "3\n1 1 1 1 1\n", "1\n1 2 2 \n" ] }
3,540
11
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) Γ— (m + 1): <image> Maxim asks you to count, how many numbers m (1 ≀ m ≀ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t. Expression (x xor y) means applying the operation of bitwise excluding "OR" to numbers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal β€” by "xor". Input A single line contains two integers n and t (1 ≀ n, t ≀ 1012, t ≀ n + 1). Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Output In a single line print a single integer β€” the answer to the problem. Examples Input 1 1 Output 1 Input 3 2 Output 1 Input 3 3 Output 0 Input 1000000000000 1048576 Output 118606527258
def comb(n, r): if r > n or r < 0: return 0 r = min(r, n-r) result = 1 for i in range(1, r+1): result = result*(n+1-i)//i return result def F(n, t): if t == 0: return 1 elif n == 0: return 0 elif n == 1: return int(t == 1) m = len(bin(n)) - 3 return F(n-(1 << m), t-1) + comb(m, t) n, t = map(int, input().strip().split()) T = len(bin(t)) - 3 if (1 << T) != t: print(0) else: print(F(n+1, T+1) - int(t == 1))
{ "input": [ "1000000000000 1048576\n", "3 3\n", "1 1\n", "3 2\n" ], "output": [ "118606527258", "0", "1", "1" ] }
3,541
9
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen. One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get? The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want. Input The single line contains a single integer n (1 ≀ n ≀ 1017). Please, do not use the %lld specifier to read or write 64 bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with. Examples Input 1 Output 1 Input 4 Output 2 Note In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change. In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives.
def main(): n = int(input()) while n % 3 == 0: n //= 3 print(n // 3 + 1) if __name__ == "__main__": main()
{ "input": [ "1\n", "4\n" ], "output": [ " 1\n", " 2\n" ] }
3,542
9
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: * There are n knights participating in the tournament. Each knight was assigned his unique number β€” an integer from 1 to n. * The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament. * After the i-th fight among all participants of the fight only one knight won β€” the knight number xi, he continued participating in the tournament. Other knights left the tournament. * The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a. Write the code that calculates for each knight, the name of the knight that beat him. Input The first line contains two integers n, m (2 ≀ n ≀ 3Β·105; 1 ≀ m ≀ 3Β·105) β€” the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≀ li < ri ≀ n; li ≀ xi ≀ ri) β€” the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle. Output Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0. Examples Input 4 3 1 2 1 1 3 3 1 4 4 Output 3 1 4 0 Input 8 4 3 5 4 3 7 6 2 8 8 1 8 1 Output 0 8 4 6 4 8 6 1 Note Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
from collections import * from sys import stdin def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return list(stdin.readline()[:-1]) class segmenttree: def __init__(self, arr, n): self.tree, self.n = [0] * (2 * n), n # build tree if arr: for i in range(2 * n - 1, 0, -1): if i >= n: self.tree[i] = arr[i - n] else: self.tree[i] = self.tree[i << 1] + self.tree[(i << 1) + 1] # get interval[l,r) def query(self, l, r, val): res = 0 l += self.n r += self.n while l < r: if l & 1: self.tree[l] = val l += 1 if r & 1: r -= 1 self.tree[r] = val l >>= 1 r >>= 1 return res def search(self, ix): ix += self.n # move up ret = [0, 0] while ix > 1: if self.tree[ix] and self.tree[ix][1] >= ret[1]: ret = self.tree[ix].copy() ix >>= 1 return ret n, m = map(int, input().split()) ans, tree = [0] * (n + 1), segmenttree([], n) quaries, c = [arr_inp(1) for i in range(m)], 0 for l, r, x in (quaries[::-1]): tree.query(l - 1, x - 1, [x, c]) tree.query(x, r, [x, c]) c += 1 for i in range(n): if quaries[-1][2] != i + 1: ans[i + 1] = tree.search(i)[0] print(*ans[1:])
{ "input": [ "4 3\n1 2 1\n1 3 3\n1 4 4\n", "8 4\n3 5 4\n3 7 6\n2 8 8\n1 8 1\n" ], "output": [ "3 1 4 0 \n", "0 8 4 6 4 8 6 1 \n" ] }
3,543
7
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value. Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero? You can assume that initially Vanya had infinitely many cards with each integer number from - x to x. Input The first line contains two integers: n (1 ≀ n ≀ 1000) β€” the number of found cards and x (1 ≀ x ≀ 1000) β€” the maximum absolute value of the number on a card. The second line contains n space-separated integers β€” the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value. Output Print a single number β€” the answer to the problem. Examples Input 3 2 -1 1 2 Output 1 Input 2 3 -2 -2 Output 2 Note In the first sample, Vanya needs to find a single card with number -2. In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.
#!/usr/bin/env python3 def read_ints(): return map(int, input().strip().split()) n, x = read_ints() s = abs(sum(read_ints())) print((s+x-1)//x)
{ "input": [ "3 2\n-1 1 2\n", "2 3\n-2 -2\n" ], "output": [ "1\n", "2\n" ] }
3,544
8
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout. If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs. Input The first line of the input contains two integers n and m (3 ≀ n, m ≀ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≀ a[i][j] ≀ 105). Output The output contains a single number β€” the maximum total gain possible. Examples Input 3 3 100 100 100 100 1 100 100 100 100 Output 800 Note Iahub will choose exercises a[1][1] β†’ a[1][2] β†’ a[2][2] β†’ a[3][2] β†’ a[3][3]. Iahubina will choose exercises a[3][1] β†’ a[2][1] β†’ a[2][2] β†’ a[2][3] β†’ a[1][3].
# -*- coding:utf-8 -*- """ created by shuangquan.huang at 1/7/20 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M+2)] for _ in range(N+2)] dpb = [[0 for _ in range(M+2)] for _ in range(N+2)] dpc = [[0 for _ in range(M+2)] for _ in range(N+2)] dpd = [[0 for _ in range(M+2)] for _ in range(N+2)] for r in range(1, N+1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r-1][c], dpa[r][c-1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r+1][c], dpb[r][c+1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M+1): dpc[r][c] = max(dpc[r+1][c], dpc[r][c-1]) + A[r][c] for r in range(1, N+1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r-1][c], dpd[r][c+1]) + A[r][c] ans = 0 for r in range(2, N): for c in range(2, M): a = dpa[r][c-1] + dpb[r][c+1] + dpc[r+1][c] + dpd[r-1][c] b = dpc[r][c-1] + dpd[r][c+1] + dpa[r-1][c] + dpb[r+1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M+2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M+2)]) print(solve(N, M, A))
{ "input": [ "3 3\n100 100 100\n100 1 100\n100 100 100\n" ], "output": [ "800\n" ] }
3,545
11
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≀ n ≀ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers β€” the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0
apples=int(input()) if apples<=3: print(0) else: halfpr=int(apples/2) def primes(n): isPrime = [True for i in range(n + 1)] isPrime[0] = isPrime[1] = False idx = 2 while idx * idx <= n: if isPrime[idx]: for i in range(idx * 2, n, idx): isPrime[i] = False idx += 1 return isPrime primeslist=primes(halfpr) totallist=[False]*(apples+1) applepairs=[] for prime in range(len(primeslist)-1, 1, -1): if primeslist[prime]: numprimes=int(apples/prime) primesx=[int(i*prime) for i in range(1, numprimes+1) if not totallist[i*prime]] if len(primesx)%2==1: primesx.remove(2*prime) for pr in primesx: applepairs.append(pr) totallist[pr]=True print(int(len(applepairs)/2)) for t in range(int(len(applepairs)/2)): print(applepairs[2*t], applepairs[2*t+1])
{ "input": [ "6\n", "2\n", "9\n" ], "output": [ "2\n3 6\n2 4\n", "0\n", "3\n3 9\n2 4\n6 8\n" ] }
3,546
8
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers. To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets. Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options? Input The first line contains a single integer n β€” the length of the sequence of games (1 ≀ n ≀ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record. Output In the first line print a single number k β€” the number of options for numbers s and t. In each of the following k lines print two integers si and ti β€” the option for numbers s and t. Print the options in the order of increasing si, and for equal si β€” in the order of increasing ti. Examples Input 5 1 2 1 2 1 Output 2 1 3 3 1 Input 4 1 1 1 1 Output 3 1 4 2 2 4 1 Input 4 1 2 1 2 Output 0 Input 8 2 1 2 1 1 1 1 1 Output 3 1 6 2 3 6 1
from itertools import chain def main(n,a, info=False): winner = a[-1] looser = 3-winner csw, csl, pw, pl, ans = [0], [0], [-1], [-1], [] nw,nl = a.count(winner), a.count(looser) for i in range(n): if a[i]==winner: pw.append(i) else: pl.append(i) csw.append(csw[-1] + int(a[i]==winner)) csl.append(csl[-1] + int(a[i]==looser)) pw += [n*10]*n pl += [n*10]*n csw += [0]*n csl += [0]*n if info: print("a: ",a) print("csw: ",csw) print("csl: ",csl) print("pw: ",pw) print("pl: ",pl) for t in chain(range(1,nw//2+1),[nw]): s = l = i = 0 sw = sl = 0 while i < n: xw = pw[csw[i]+t] xl = pl[csl[i]+t] if xw < xl: s += 1 else: l += 1 i = min(xw,xl)+1 if info: print(s,t,": ",t,i,s,l,xw,xl) if s>l and i<=n and csw[i]==nw: ans.append((s,t)) print(len(ans)) for x,y in sorted(ans): print(x,y) def main_input(): n = int(input()) a = [int(i) for i in input().split()] main(n,a) if __name__ == "__main__": main_input()
{ "input": [ "4\n1 2 1 2\n", "8\n2 1 2 1 1 1 1 1\n", "4\n1 1 1 1\n", "5\n1 2 1 2 1\n" ], "output": [ "0\n", "3\n1 6\n2 3\n6 1\n", "3\n1 4\n2 2\n4 1\n", "2\n1 3\n3 1\n" ] }
3,547
7
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. <image> He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length. He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length. Input The first line of input contains string s containing lowercase English letters (1 ≀ |s| ≀ 1000). The second line contains integer k (1 ≀ k ≀ 1000). Output Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise. Examples Input saba 2 Output NO Input saddastavvat 2 Output YES Note Palindrome is a string reading the same forward and backward. In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".
def pal(s): return s == s[::-1] s, k = input(), int(input()) if len(s) % k != 0: print('NO') else: n = len(s) // k print('YES' if all(pal(s[i * n:(i + 1) * n]) for i in range(k)) else 'NO')
{ "input": [ "saddastavvat\n2\n", "saba\n2\n" ], "output": [ "YES\n", "NO\n" ] }
3,548
9
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot? Input First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players. Output Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise. Examples Input 4 75 150 75 50 Output Yes Input 3 100 150 250 Output No Note In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid. It can be shown that in the second sample test there is no way to make all bids equal.
def divby(m): for k in range(len(arr)): while((arr[k]%m)==0): arr[k]/=m def issame(): return len(set(arr)) <= 1 n=int(input()) arr=list(map(int,input().split())) arr.sort() divby(2) divby(3) if issame(): print("Yes") else: print("No")
{ "input": [ "4\n75 150 75 50\n", "3\n100 150 250\n" ], "output": [ "Yes", "No" ] }
3,549
7
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices. Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool. Input The first line of the input contains a single integer n (1 ≀ n ≀ 4) β€” the number of vertices that were not erased by Wilbur's friend. Each of the following n lines contains two integers xi and yi ( - 1000 ≀ xi, yi ≀ 1000) β€”the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order. It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes. Output Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print - 1. Examples Input 2 0 0 1 1 Output 1 Input 1 1 1 Output -1 Note In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square. In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.
def area(ps): xl = [p[0] for p in ps] yl = [p[1] for p in ps] lx = max(xl)-min(xl) ly = max(yl)-min(yl) return lx*ly if lx*ly>0 else -1 ps = [list(map(int,input().split())) for _ in range(int(input()))] print(area(ps))
{ "input": [ "1\n1 1\n", "2\n0 0\n1 1\n" ], "output": [ "-1\n", "1\n" ] }
3,550
9
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values r1(r1 β‰₯ 0) and r2(r2 β‰₯ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains. You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value. Input The first line of the input contains integers n, x1, y1, x2, y2 (1 ≀ n ≀ 2000, - 107 ≀ x1, y1, x2, y2 ≀ 107) β€” the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≀ xi, yi ≀ 107) β€” the coordinates of the i-th flower. It is guaranteed that all n + 2 points in the input are distinct. Output Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer. Examples Input 2 -1 0 5 3 0 2 5 2 Output 6 Input 4 0 0 5 0 9 4 8 3 -1 0 1 4 Output 33 Note The first sample is (r12 = 5, r22 = 1): <image> The second sample is (r12 = 1, r22 = 32): <image>
def ds(x,y,x2,y2):return (x2-x)**2+(y2-y)**2 n,x1,y1,x2,y2=map(int,input().split()) a=list() for i in range(n): x,y=map(int,input().split()) a.append([ds(x,y,x1,y1),ds(x,y,x2,y2)]) a.sort(reverse=True) ans=float('inf') k=0 for i in a+[[0,0]]: ans=min(ans,i[0]+k) k=max(k,i[1]) print(ans)
{ "input": [ "2 -1 0 5 3\n0 2\n5 2\n", "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4\n" ], "output": [ "6\n", "33\n" ] }
3,551
10
A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump β€” to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle. On the way of an athlete are n obstacles at coordinates x1, x2, ..., xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point. Input The first line of the input containsd four integers n, m, s and d (1 ≀ n ≀ 200 000, 2 ≀ m ≀ 109, 1 ≀ s, d ≀ 109) β€” the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (1 ≀ ai ≀ m - 1) β€” the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order. Output If the runner cannot reach the finishing point, print in the first line of the output "IMPOSSIBLE" (without the quotes). If the athlete can get from start to finish, print any way to do this in the following format: * print a line of form "RUN X>" (where "X" should be a positive integer), if the athlete should run for "X" more meters; * print a line of form "JUMP Y" (where "Y" should be a positive integer), if the sportsman starts a jump and should remain in air for "Y" more meters. All commands "RUN" and "JUMP" should strictly alternate, starting with "RUN", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish. Examples Input 3 10 1 3 3 4 7 Output RUN 2 JUMP 3 RUN 1 JUMP 2 RUN 2 Input 2 9 2 3 6 4 Output IMPOSSIBLE
n, m, s, d = map(int, input().split()) a = sorted(list(map(int, input().split()))) def e(): print('IMPOSSIBLE') exit() if d == 1: e() ans = list() if a[0] - 1 < s: e() ans.append(f'RUN {a[0] - 1}') now = 2 for i in range(1, n): if a[i] - a[i - 1] - 2 < s: now += a[i] - a[i - 1] if now > d: e() else: ans.append(f'JUMP {now}') ans.append(f'RUN {a[i] - a[i - 1] - 2}') now = 2 ans.append(f'JUMP {now}') if m - a[-1] - 1: ans.append(f'RUN {m - a[-1] - 1}') print('\n'.join(ans))
{ "input": [ "2 9 2 3\n6 4\n", "3 10 1 3\n3 4 7\n" ], "output": [ "IMPOSSIBLE\n", "RUN 2\nJUMP 3\nRUN 1\nJUMP 2\nRUN 2\n" ] }
3,552
10
A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 ≀ i < j ≀ k), xi + xj is a prime. You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size. A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it. Input The first line contains integer n (1 ≀ n ≀ 1000) β€” the number of integers in the array a. The second line contains n integers ai (1 ≀ ai ≀ 106) β€” the elements of the array a. Output On the first line print integer m β€” the maximum possible size of simple subset of a. On the second line print m integers bl β€” the elements of the simple subset of the array a with the maximum size. If there is more than one solution you can print any of them. You can print the elements of the subset in any order. Examples Input 2 2 3 Output 2 3 2 Input 2 2 2 Output 1 2 Input 3 2 1 1 Output 3 1 1 2 Input 2 83 14 Output 2 14 83
def main(): input() l0, l1, ones = [], [], 0 for a in map(int, input().split()): if a == 1: ones += 1 else: (l1 if a & 1 else l0).append(a) seive = [False, True] * (((max(l0) if l0 else 0) + (max(l1) if l1 else 0)) // 2 + 1) a = len(seive) for i in range(3, int(a ** .5) + 1, 2): if seive[i]: for j in range(i * i, a, i): seive[j] = False if ones: res = ['1'] * ones for a in l0: if a > 1 and seive[a + 1]: res.append(str(a)) break if len(res) > 1: print(len(res)) print(' '.join(res)) return for a in l1: for b in l0: if seive[a + b]: print(2) print(a, b) return print(1) print(1 if ones else (l0 if l0 else l1)[0]) if __name__ == '__main__': main()
{ "input": [ "2\n2 2\n", "2\n2 3\n", "2\n83 14\n", "3\n2 1 1\n" ], "output": [ "1\n2", "2\n2 3", "2\n83 14", "3\n1 1 2" ] }
3,553
8
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by <image> units. Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers. Input First line of the input contains two integers n and k (1 ≀ n ≀ 10000, 0 ≀ k ≀ 99) β€” number of accumulators and the percent of energy that is lost during transfers. Next line contains n integers a1, a2, ... , an β€” amounts of energy in the first, second, .., n-th accumulator respectively (0 ≀ ai ≀ 1000, 1 ≀ i ≀ n). Output Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy. The absolute or relative error in the answer should not exceed 10 - 6. Examples Input 3 50 4 2 1 Output 2.000000000 Input 2 90 1 11 Output 1.909090909
n,k=map(int,input().split(" ")) a=list(map(int,input().split(" "))) def check(x): pw=0 for i in a: if(i>=x): rem=(i-x) pw+=(rem-(rem*k/100)) else: pw-=(x-i) if(pw>=0): return True return False l=0 h=max(a) ans=0 while(l+0.0000001<=h): mid=(l+h)/2 if(check(mid)): ans=mid l=mid else: h=mid print(ans)
{ "input": [ "2 90\n1 11\n", "3 50\n4 2 1\n" ], "output": [ "1.9090909088\n", "2.0000000001\n" ] }
3,554
11
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland. In Udayland, there are 2n days in a year. ZS the Coder wants to interview k people from Udayland, each of them has birthday in one of 2n days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day. ZS the Coder knows that the answer can be written as an irreducible fraction <image>. He wants to find the values of A and B (he does not like to deal with floating point numbers). Can you help him? Input The first and only line of the input contains two integers n and k (1 ≀ n ≀ 1018, 2 ≀ k ≀ 1018), meaning that there are 2n days in a year and that ZS the Coder wants to interview exactly k people. Output If the probability of at least two k people having the same birthday in 2n days long year equals <image> (A β‰₯ 0, B β‰₯ 1, <image>), print the A and B in a single line. Since these numbers may be too large, print them modulo 106 + 3. Note that A and B must be coprime before their remainders modulo 106 + 3 are taken. Examples Input 3 2 Output 1 8 Input 1 3 Output 1 1 Input 4 3 Output 23 128 Note In the first sample case, there are 23 = 8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly <image>, so A = 1, B = 8. In the second sample case, there are only 21 = 2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and A = B = 1.
import sys mod = 10 ** 6 + 3 n, k = map(int, input().split()) if n < 100: if 2 ** n < k: print(1, 1) sys.exit() def factor(n, p): if n < p: return 0 return n // p + factor(n // p, p) def inv(n): return pow(n, mod - 2, mod) # 2^nk - P(2^n,k) / 2^nk two = inv(pow(2, n + factor(k - 1, 2), mod)) v = 1 if k >= mod: v = 0 else: N = pow(2, n, mod) for i in range(k): v = v * (N - i) % mod A = (pow(2, n * k, mod) - v) * two % mod B = pow(2, n * k, mod) * two % mod print(A, B)
{ "input": [ "1 3\n", "4 3\n", "3 2\n" ], "output": [ "1 1", "23 128", "1 8\n" ] }
3,555
8
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. Input The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≀ n ≀ 5000; 1 ≀ m ≀ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly m bits. 2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. Output In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. Examples Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 Note In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
f = {'OR': lambda x, y: x | y, 'AND': lambda x, y: x & y, 'XOR': lambda x, y: x ^ y} n, m = map(int, input().split()) u, v = [], [] d = {'?': n} for i in range(n): q, s = input().split(' := ') if ' ' in s: x, t, y = s.split() u += [(i, d[x], f[t], d[y])] else: v += [(i, s)] d[q] = i s = [0] * (n + 1) def g(k, j): s[n] = k for i, q in v: s[i] = q[j] == '1' for i, x, f, y in u: s[i] = f(s[x], s[y]) return sum(s) - k a = b = '' for j in range(m): d = g(1, j) - g(0, j) a += '01'[d < 0] b += '01'[d > 0] print(a, b)
{ "input": [ "5 1\na := 1\nbb := 0\ncx := ? OR a\nd := ? XOR ?\ne := d AND bb\n", "3 3\na := 101\nb := 011\nc := ? XOR b\n" ], "output": [ "0\n0\n", "011\n100\n" ] }
3,556
11
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations. Can you help Heidi estimate each village's population? Input Same as the easy version. Output Output one line per village, in the same order as provided in the input, containing your (integer) population estimate. Your answer is considered correct if it is an integer that falls into the interval <image>, where P is the real population of the village, used to create the distribution (either Poisson or uniform) from which the marmots drew their answers.
def sampleVariance(V): X = sum(V) / len(V) S = 0.0 for x in V: S += (X-x)**2 S /= (len(V)-1) return (X, S) #That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester for i in range(int(input())): V = list(map(int, input().split())) X, S = sampleVariance(V) v1 = X v2 = (2*X) ** 2 / 12 if abs(v1-S) < abs(v2-S): print(int(X)) else: print((max(V)+min(V)) // 2)
{ "input": [], "output": [] }
3,557
7
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: * Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). * Digits are written one by one in order corresponding to number and separated by single '0' character. Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number. Input The first line contains one integer number n (1 ≀ n ≀ 89) β€” length of the string s. The second line contains string s β€” sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'. Output Print the decoded number. Examples Input 3 111 Output 3 Input 9 110011101 Output 2031
def main(): input() s = input() for i in s.split('0'): print(len(i), end='') if __name__ == '__main__': main()
{ "input": [ "3\n111\n", "9\n110011101\n" ], "output": [ "3\n", "2031\n" ] }
3,558
7
What are you doing at the end of the world? Are you busy? Will you save us? <image> Nephren is playing a game with little leprechauns. She gives them an infinite array of strings, f0... ∞. f0 is "What are you doing at the end of the world? Are you busy? Will you save us?". She wants to let more people know about it, so she defines fi = "What are you doing while sending "fi - 1"? Are you busy? Will you send "fi - 1"?" for all i β‰₯ 1. For example, f1 is "What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1. It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces. Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes). Can you answer her queries? Input The first line contains one integer q (1 ≀ q ≀ 10) β€” the number of Nephren's questions. Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≀ n ≀ 105, 1 ≀ k ≀ 1018). Output One line containing q characters. The i-th character in it should be the answer for the i-th query. Examples Input 3 1 1 1 2 1 111111111111 Output Wh. Input 5 0 69 1 194 1 139 0 47 1 66 Output abdef Input 10 4 1825 3 75 3 530 4 1829 4 1651 3 187 4 584 4 255 4 774 2 474 Output Areyoubusy Note For the first two examples, refer to f0 and f1 given in the legend.
s = "What are you doing at the end of the world? Are you busy? Will you save us?" s1 = 'What are you doing while sending "' s2 = '"? Are you busy? Will you send "' s3 = '"?' l1,l2,l3=len(s1),len(s2),len(s3) def count(n): if n>=60:return 10**20 return (1<<n)*75+((1<<n)-1)*68 def find(n,k): if count(n)<k:return '.' if n==0:return s[k-1] if k<=l1:return s1[k-1] c=count(n-1) k-=l1 if k<=c: return find(n-1,k) k-=c if k<=l2:return s2[k-1] k-=l2 if k<=c: return find(n-1,k) k-=c if k<=l3:return s3[k-1] q=int(input()) ans='' while q: n,k=map(int,input().split()) while n > 70 and k > 34: k -= 34 n -= 1 if n > 0 and k <= 34: ans+=s1[k - 1] else :ans+=find(n,k) q-=1 print(ans)
{ "input": [ "10\n4 1825\n3 75\n3 530\n4 1829\n4 1651\n3 187\n4 584\n4 255\n4 774\n2 474\n", "3\n1 1\n1 2\n1 111111111111\n", "5\n0 69\n1 194\n1 139\n0 47\n1 66\n" ], "output": [ "Areyoubusy\n", "Wh.\n", "abdef\n" ] }
3,559
8
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter. <image> Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time. Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game? You have to determine the winner of the game for all initial positions of the marbles. Input The first line of input contains two integers n and m (2 ≀ n ≀ 100, <image>). The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≀ v, u ≀ n, v β‰  u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic. Output Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise. Examples Input 4 4 1 2 b 1 3 a 2 4 c 3 4 b Output BAAA ABAA BBBA BBBB Input 5 8 5 3 h 1 2 c 3 1 c 3 2 r 5 1 r 4 3 z 5 4 r 5 2 h Output BABBB BBBBB AABBB AAABA AAAAB Note Here's the graph in the first sample test case: <image> Here's the graph in the second sample test case: <image>
import sys # sys.setrecursionlimit(10**5) n,m=map(int,input().split()) g={i:[] for i in range(1,n+1)} dp=[[[-1]*26 for _ in range(n+1)] for i in range(n+1)] def rec(i,j,ch): if dp[i][j][ord(ch)-ord('a')]!=-1: return dp[i][j][ord(ch)-ord('a')] for x in g[i]: if ord(x[1])>=ord(ch): v=rec(j,x[0],x[1]) if not v: dp[i][j][ord(ch)-ord('a')]=1 return 1 dp[i][j][ord(ch)-ord('a')]=0 return 0 for _ in range(m): line=input().split() a=int(line[0]) b=int(line[1]) c=line[2] g[a].append([b,c]) for i in range(1,n+1): for j in range(1,n+1): print('A',end="") if rec(i,j,'a') else print('B',end="") print()
{ "input": [ "4 4\n1 2 b\n1 3 a\n2 4 c\n3 4 b\n", "5 8\n5 3 h\n1 2 c\n3 1 c\n3 2 r\n5 1 r\n4 3 z\n5 4 r\n5 2 h\n" ], "output": [ "BAAA\nABAA\nBBBA\nBBBB\n", "BABBB\nBBBBB\nAABBB\nAAABA\nAAAAB\n" ] }
3,560
8
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles β€” one bottle of each kind. We know that the volume of milk in each bottle equals w. When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem β€” and what is actually the way to do it? Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible! Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup. Input The only input data file contains three integers n, w and m (1 ≀ n ≀ 50, 100 ≀ w ≀ 1000, 2 ≀ m ≀ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company. Output Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO". If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 ≀ b ≀ n). All numbers b on each line should be different. If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point. Examples Input 2 500 3 Output YES 1 333.333333 2 333.333333 2 166.666667 1 166.666667 Input 4 100 5 Output YES 3 20.000000 4 60.000000 1 80.000000 4 40.000000 2 40.000000 3 80.000000 2 60.000000 1 20.000000 Input 4 100 7 Output NO Input 5 500 2 Output YES 4 250.000000 5 500.000000 2 500.000000 3 500.000000 1 500.000000 4 250.000000
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w, m = map(int, input().split()) w = float(w) eps = 1e-9 req = n * w / m cup = [req] * m ans = [[] for _ in range(m)] j = 0 for i in range(n): milk = w cnt = 0 while j < m and milk > eps: x = min(milk, cup[j]) milk -= x cup[j] -= x ans[j].append(f'{i+1} {x:.8f}') cnt += 1 if cup[j] < eps: j += 1 if cnt > 2: print('NO') exit() print('YES') print('\n'.join(' '.join(line) for line in ans))
{ "input": [ "5 500 2\n", "2 500 3\n", "4 100 7\n", "4 100 5\n" ], "output": [ "YES\n1 500.00000000000000000000 2 500.00000000000000000000 3 250.00000000000000000000 \n3 250.00000000000000000000 4 500.00000000000000000000 5 500.00000000000000000000 \n", "YES\n1 333.33333333333331438553 \n1 166.66666666666665719276 2 166.66666666666665719276 \n2 333.33333333333331438553 \n", "NO\n", "YES\n1 80.00000000000000000000 \n1 20.00000000000000000000 2 60.00000000000000000000 \n2 40.00000000000000000000 3 40.00000000000000000000 \n3 60.00000000000000000000 4 20.00000000000000000000 \n4 80.00000000000000000000 \n" ] }
3,561
7
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two pockets as follows: [1, 2, 3], [2, 3, 4]. Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that. Input The first line of the input contains one integer n (1 ≀ n ≀ 100) β€” the number of coins. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 100) β€” values of coins. Output Print only one integer β€” the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket. Examples Input 6 1 2 4 3 3 2 Output 2 Input 1 100 Output 1
from collections import Counter def main(): n = input() print(max(Counter([int(i) for i in input().split()]).values())) main()
{ "input": [ "6\n1 2 4 3 3 2\n", "1\n100\n" ], "output": [ "2\n", "1\n" ] }
3,562
8
You are given a chessboard of size n Γ— n. It is filled with numbers from 1 to n^2 in the following way: the first ⌈ (n^2)/(2) βŒ‰ numbers from 1 to ⌈ (n^2)/(2) βŒ‰ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest n^2 - ⌈ (n^2)/(2) βŒ‰ numbers from ⌈ (n^2)/(2) βŒ‰ + 1 to n^2 are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation ⌈x/yβŒ‰ means division x by y rounded up. For example, the left board on the following picture is the chessboard which is given for n=4 and the right board is the chessboard which is given for n=5. <image> You are given q queries. The i-th query is described as a pair x_i, y_i. The answer to the i-th query is the number written in the cell x_i, y_i (x_i is the row, y_i is the column). Rows and columns are numbered from 1 to n. Input The first line contains two integers n and q (1 ≀ n ≀ 10^9, 1 ≀ q ≀ 10^5) β€” the size of the board and the number of queries. The next q lines contain two integers each. The i-th line contains two integers x_i, y_i (1 ≀ x_i, y_i ≀ n) β€” description of the i-th query. Output For each query from 1 to q print the answer to this query. The answer to the i-th query is the number written in the cell x_i, y_i (x_i is the row, y_i is the column). Rows and columns are numbered from 1 to n. Queries are numbered from 1 to q in order of the input. Examples Input 4 5 1 1 4 4 4 3 3 2 2 4 Output 1 8 16 13 4 Input 5 4 2 1 4 2 3 3 3 4 Output 16 9 7 20 Note Answers to the queries from examples are on the board in the picture from the problem statement.
def R(): return map(int, input().split()) ans = [] n, q = R() d = (n*n+1)//2 for _ in range(q): x, y = R() i = ((x-1)*n+y-1)//2+1 if x % 2 != y % 2: i += d ans.append(str(i)) print("\n".join(ans))
{ "input": [ "5 4\n2 1\n4 2\n3 3\n3 4\n", "4 5\n1 1\n4 4\n4 3\n3 2\n2 4\n" ], "output": [ "16\n9\n7\n20\n", "1\n8\n16\n13\n4\n" ] }
3,563
10
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence p. For example, if n = 3, then p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence will be n β‹… n!. Let 1 ≀ i ≀ j ≀ n β‹… n! be a pair of indices. We call the sequence (p_i, p_{i+1}, ..., p_{j-1}, p_j) a subarray of p. Its length is defined as the number of its elements, i.e., j - i + 1. Its sum is the sum of all its elements, i.e., βˆ‘_{k=i}^j p_k. You are given n. Find the number of subarrays of p of length n having sum (n(n+1))/(2). Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≀ n ≀ 10^6), as described in the problem statement. Output Output a single integer β€” the number of subarrays of length n having sum (n(n+1))/(2), modulo 998244353. Examples Input 3 Output 9 Input 4 Output 56 Input 10 Output 30052700 Note In the first sample, there are 16 subarrays of length 3. In order of appearance, they are: [1, 2, 3], [2, 3, 1], [3, 1, 3], [1, 3, 2], [3, 2, 2], [2, 2, 1], [2, 1, 3], [1, 3, 2], [3, 2, 3], [2, 3, 1], [3, 1, 3], [1, 3, 1], [3, 1, 2], [1, 2, 3], [2, 3, 2], [3, 2, 1]. Their sums are 6, 6, 7, 6, 7, 5, 6, 6, 8, 6, 7, 5, 6, 6, 7, 6. As (n(n+1))/(2) = 6, the answer is 9.
n = int(input()) m = 998244353 p,p_,mul = 1,0,n def getp(): global p,p_,mul p_ = p p = (p*mul)%m mul -= 1 return (p-p_+m)%m ans = 1+sum([i*getp() for i in range(1,n)]) print(ans%m)
{ "input": [ "4\n", "10\n", "3\n" ], "output": [ " 56", " 30052700", " 9" ] }
3,564
8
You have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired. You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length t placed at some position s will cover segments s, s+1, …, s+t-1. You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap. Time is money, so you want to cut at most k continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces? Input The first line contains three integers n, m and k (1 ≀ n ≀ 10^5, n ≀ m ≀ 10^9, 1 ≀ k ≀ n) β€” the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ m) β€” the positions of the broken segments. These integers are given in increasing order, that is, b_1 < b_2 < … < b_n. Output Print the minimum total length of the pieces. Examples Input 4 100 2 20 30 75 80 Output 17 Input 5 100 3 1 2 4 60 87 Output 6 Note In the first example, you can use a piece of length 11 to cover the broken segments 20 and 30, and another piece of length 6 to cover 75 and 80, for a total length of 17. In the second example, you can use a piece of length 4 to cover broken segments 1, 2 and 4, and two pieces of length 1 to cover broken segments 60 and 87.
n, m, k = map(int, input().split()) a = [int(x) for x in input().split()] def sol(): b = [0] * (n - 1) for i in range(n - 1): b[i] = a[i + 1] - a[i] b.sort() print(sum(b[:n - k]) + k) sol()
{ "input": [ "4 100 2\n20 30 75 80\n", "5 100 3\n1 2 4 60 87\n" ], "output": [ "17", "6" ] }
3,565
9
Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≀ i ≀ n it is true that 1 ≀ p_i ≀ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≀ n, such that p_j > p_i. If there is no such j let's let's define as next_i = n + 1. In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values next_i are completely lost! If for some i the value next_i is lost, let's say that next_i = -1. You are given numbers next_1, next_2, …, next_n (maybe some of them are equal to -1). Help Vasya to find such permutation p_1, p_2, …, p_n of integers from 1 to n, that he can write it to the notebook and all numbers next_i, which are not equal to -1, will be correct. Input The first line contains one integer t β€” the number of test cases (1 ≀ t ≀ 100 000). Next 2 β‹… t lines contains the description of test cases,two lines for each. The first line contains one integer n β€” the length of the permutation, written by Vasya (1 ≀ n ≀ 500 000). The second line contains n integers next_1, next_2, …, next_n, separated by spaces (next_i = -1 or i < next_i ≀ n + 1). It is guaranteed, that the sum of n in all test cases doesn't exceed 500 000. In hacks you can only use one test case, so T = 1. Output Print T lines, in i-th of them answer to the i-th test case. If there is no such permutations p_1, p_2, …, p_n of integers from 1 to n, that Vasya could write, print the only number -1. In the other case print n different integers p_1, p_2, …, p_n, separated by spaces (1 ≀ p_i ≀ n). All defined values of next_i which are not equal to -1 should be computed correctly p_1, p_2, …, p_n using defenition given in the statement of the problem. If there exists more than one solution you can find any of them. Example Input 6 3 2 3 4 2 3 3 3 -1 -1 -1 3 3 4 -1 1 2 4 4 -1 4 5 Output 1 2 3 2 1 2 1 3 -1 1 3 2 1 4 Note In the first test case for permutation p = [1, 2, 3] Vasya should write next = [2, 3, 4], because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation. In the third test case, any permutation can be the answer because all numbers next_i are lost. In the fourth test case, there is no satisfying permutation, so the answer is -1.
import sys inp = [] inp_idx = 0 def dfs(node, adj, n): timer = n perm = [0] * (n + 1) perm[node] = timer timer -= 1 stack = [node] while stack: node = stack[-1] if adj[node]: neighbor = adj[node].pop() stack.append(neighbor) perm[neighbor] = timer timer -= 1 else: stack.pop() return perm def check(n, nxt, perm): stack = [n] for i in range(n - 1, -1, -1): while stack[-1] < perm[i]: stack.pop() if stack[-1] != perm[nxt[i]]: return False stack.append(perm[i]) return True def solve(): global inp global inp_idx global perm global timer n = inp[inp_idx] inp_idx += 1 nxt = [] for _ in range(n): nxt.append(inp[inp_idx]) inp_idx += 1 for i in range(n): nxt[i] = i + 1 if nxt[i] == -1 else nxt[i] - 1 adj = [[] for _ in range(n + 1)] for i in range(n - 1, -1, -1): adj[nxt[i]].append(i) perm = dfs(n, adj, n) print(-1) if not check(n, nxt, perm) else print(*(list(map(lambda x : x + 1, perm[:-1])))) if __name__ == '__main__': inp = [int(x) for x in sys.stdin.read().split()] t = inp[0] inp_idx = 1 for test in range(t): solve()
{ "input": [ "6\n3\n2 3 4\n2\n3 3\n3\n-1 -1 -1\n3\n3 4 -1\n1\n2\n4\n4 -1 4 5\n" ], "output": [ "1 2 3 \n2 1 \n1 2 3 \n-1\n1 \n3 1 2 4 \n" ] }
3,566
8
Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 β‹… a_2 β‹… ... a_n of its elements seemed to him not large enough. He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index i (1 ≀ i ≀ n) and do a_i := -a_i - 1. For example, he can change array [3, -1, -4, 1] to an array [-4, -1, 3, 1] after applying this operation to elements with indices i=1 and i=3. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements a_1 β‹… a_2 β‹… ... a_n which can be received using only this operation in some order. If there are multiple answers, print any of them. Input The first line contains integer n (1 ≀ n ≀ 10^{5}) β€” number of integers in the array. The second line contains n integers a_1, a_2, …, a_n (-10^{6} ≀ a_i ≀ 10^{6}) β€” elements of the array Output Print n numbers β€” elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them. Examples Input 4 2 2 2 2 Output -3 -3 -3 -3 Input 1 0 Output 0 Input 3 -3 -3 2 Output -3 -3 2
def f(L): for i in range(len(L)): if(L[i]>=0): L[i]=L[i]*(-1)-1 if(len(L)%2!=0): m=min(L) L[L.index(m)]=-L[L.index(m)]-1 return(L) n=int(input()) L=list(map(int,input().split())) print(*f(L))
{ "input": [ "1\n0\n", "4\n2 2 2 2\n", "3\n-3 -3 2\n" ], "output": [ "0", "-3 -3 -3 -3 ", "2 -3 -3\n" ] }
3,567
8
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surface. <image> Suppose that the lily grows at some point A on the lake bottom, and its stem is always a straight segment with one endpoint at point A. Also suppose that initially the flower was exactly above the point A, i.e. its stem was vertical. Can you determine the depth of the lake at point A? Input The only line contains two integers H and L (1 ≀ H < L ≀ 10^{6}). Output Print a single number β€” the depth of the lake at point A. The absolute or relative error should not exceed 10^{-6}. Formally, let your answer be A, and the jury's answer be B. Your answer is accepted if and only if \frac{|A - B|}{max{(1, |B|)}} ≀ 10^{-6}. Examples Input 1 2 Output 1.5000000000000 Input 3 5 Output 2.6666666666667
def mp(): return map(int, input().split()) h, l = mp() print((l*l - h*h) / h / 2)
{ "input": [ "3 5\n", "1 2\n" ], "output": [ "2.6666666666667\n", "1.5000000000000\n" ] }
3,568
7
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n. He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'. The prefix of string s of length l (1 ≀ l ≀ n) is a string s[1..l]. For example, for the string s="abba" there are two prefixes of the even length. The first is s[1...2]="ab" and the second s[1...4]="abba". Both of them have the same number of 'a' and 'b'. Your task is to calculate the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'. Input The first line of the input contains one even integer n (2 ≀ n ≀ 2β‹…10^{5}) β€” the length of string s. The second line of the input contains the string s of length n, which consists only of lowercase Latin letters 'a' and 'b'. Output In the first line print the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'. In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them. Examples Input 4 bbbb Output 2 abba Input 6 ababab Output 0 ababab Input 2 aa Output 1 ba Note In the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'. In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.
def f(a): cnt = 0 fliped = {'a':'b', 'b':'a'} for i in range(0, len(a), 2): if a[i] == a[i+1]: cnt += 1 a[i] = fliped[a[i]] print(cnt) print(''.join(a)) input() f(list(input()))
{ "input": [ "6\nababab\n", "4\nbbbb\n", "2\naa\n" ], "output": [ "0\nababab", "2\nabab", "1\nab\n" ] }
3,569
8
This is a harder version of the problem. In this version, n ≀ 300 000. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence. To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him. 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. The cyclical shift of the string s of length n by k (0 ≀ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())". Cyclical shifts i and j are considered different, if i β‰  j. Input The first line contains an integer n (1 ≀ n ≀ 300 000), the length of the string. The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")". Output The first line should contain a single integer β€” the largest beauty of the string, which can be achieved by swapping some two characters. The second line should contain integers l and r (1 ≀ l, r ≀ n) β€” the indices of two characters, which should be swapped in order to maximize the string's beauty. In case there are several possible swaps, print any of them. Examples Input 10 ()()())(() Output 5 8 7 Input 12 )(()(()())() Output 4 5 10 Input 6 )))(() Output 0 1 1 Note In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence. In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence. In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
n = int(input()) s = list(input()) L = 1 R = 1 def check(): calc = 0 min = 0 cntmin = 0 for ch in s: if ch == '(': calc += 1 else: calc -= 1 if min > calc: min = calc cntmin = 1 elif min == calc: cntmin += 1 return cntmin if calc == 0 else 0 best = check() for i in range(n): for j in range(i + 1, n, 1): s[i], s[j] = s[j], s[i] new = check() s[j], s[i] = s[i], s[j] if (new > best): best = new; L = 1+i; R = 1+j print(best) print(L, R)
{ "input": [ "6\n)))(()\n", "10\n()()())(()\n", "12\n)(()(()())()\n" ], "output": [ "0\n1 1", "5\n8 7", "4\n5 10" ] }
3,570
10
You play a computer game. In this game, you lead a party of m heroes, and you have to clear a dungeon with n monsters. Each monster is characterized by its power a_i. Each hero is characterized by his power p_i and endurance s_i. The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day. When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated k monsters, the hero fights with the monster k + 1). When the hero fights the monster, there are two possible outcomes: * if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends; * otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the i-th hero cannot defeat more than s_i monsters during each day), or if all monsters are defeated β€” otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends. Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times. Input The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Then the test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of monsters in the dungeon. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9), where a_i is the power of the i-th monster. The third line contains one integer m (1 ≀ m ≀ 2 β‹… 10^5) β€” the number of heroes in your party. Then m lines follow, each describing a hero. Each line contains two integers p_i and s_i (1 ≀ p_i ≀ 10^9, 1 ≀ s_i ≀ n) β€” the power and the endurance of the i-th hero. It is guaranteed that the sum of n + m over all test cases does not exceed 2 β‹… 10^5. Output For each test case print one integer β€” the minimum number of days you have to spend to defeat all of the monsters (or -1 if it is impossible). Example Input 2 6 2 3 11 14 1 8 2 3 2 100 1 5 3 5 100 2 3 2 30 5 90 1 Output 5 -1
def main(): t = int(input()) for q in range(t): n = int(input()) a = list(map(int,input().split())) a = [0] + a m = int(input()) b = [0] * (n + 1) for i in range(0,m): p,s = map(int,input().split()) b[s] = max(b[s], p) for i in range(n - 1, -1, -1): b[i] = max(b[i], b[i + 1]) ans = 0 k = 0 while k<n: q = 0 t = 0 while k + t + 1 <=n and b[t + 1] >= max(q, a[k + t + 1]): q = max(q, a[k + t + 1]) t += 1 if t == 0: ans =- 1 break k += t ans += 1 print(ans) main()
{ "input": [ "2\n6\n2 3 11 14 1 8\n2\n3 2\n100 1\n5\n3 5 100 2 3\n2\n30 5\n90 1\n" ], "output": [ "5\n-1\n" ] }
3,571
10
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation: <image> Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored: <image> The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are [similar](https://tinyurl.com/vp5m7vl). Input The first line of input will contain a single integer n (3 ≀ n ≀ 10^5) β€” the number of points. The i-th of the next n lines contains two integers x_i, y_i (|x_i|, |y_i| ≀ 10^9), denoting the coordinates of the i-th vertex. It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon. Output Output "YES" in a separate line, if P and T are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower). Examples Input 4 1 0 4 1 3 4 0 3 Output YES Input 3 100 86 50 0 150 0 Output nO Input 8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 Output YES Note The following image shows the first sample: both P and T are squares. The second sample was shown in the statements. <image>
def m(a, b): return a[0] - b[0], a[1] - b[1] n = int(input()) a = [list(map(int, input().split())) for _ in range(n)] if n%2 == 1: print('NO') else: flag = True for i in range(n//2): flag = flag and m(a[i+1], a[i]) == m(a[i + n//2], a[(i + 1 + n//2)%n]) if flag: print('YES') else: print('NO')
{ "input": [ "4\n1 0\n4 1\n3 4\n0 3\n", "8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3\n", "3\n100 86\n50 0\n150 0\n" ], "output": [ "YES\n", "YES\n", "nO\n" ] }
3,572
11
Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in other words, h hours). Vova thinks that the i-th sleeping time is good if he starts to sleep between hours l and r inclusive. Vova can control himself and before the i-th time can choose between two options: go to sleep after a_i hours or after a_i - 1 hours. Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally. Input The first line of the input contains four integers n, h, l and r (1 ≀ n ≀ 2000, 3 ≀ h ≀ 2000, 0 ≀ l ≀ r < h) β€” the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i < h), where a_i is the number of hours after which Vova goes to sleep the i-th time. Output Print one integer β€” the maximum number of good sleeping times Vova can obtain if he acts optimally. Example Input 7 24 21 23 16 17 14 20 20 11 22 Output 3 Note The maximum number of good times in the example is 3. The story starts from t=0. Then Vova goes to sleep after a_1 - 1 hours, now the time is 15. This time is not good. Then Vova goes to sleep after a_2 - 1 hours, now the time is 15 + 16 = 7. This time is also not good. Then Vova goes to sleep after a_3 hours, now the time is 7 + 14 = 21. This time is good. Then Vova goes to sleep after a_4 - 1 hours, now the time is 21 + 19 = 16. This time is not good. Then Vova goes to sleep after a_5 hours, now the time is 16 + 20 = 12. This time is not good. Then Vova goes to sleep after a_6 hours, now the time is 12 + 11 = 23. This time is good. Then Vova goes to sleep after a_7 hours, now the time is 23 + 22 = 21. This time is also good.
def put(): return map(int, input().split()) n,h,l,r = put() a = list(put()) m = h dp = [-1000000]*(m+1) dp[0] = 0 for i in range(1,n+1): tmp = [0]*(m+1) for j in range(m): t = j%h tmp[j] = 1 if (t>=l and t<=r) else 0 x = dp[(j-a[i-1]+1)%h] y = dp[(j-a[i-1])%h] tmp[j]+= max(x,y) dp = tmp print(max(dp))
{ "input": [ "7 24 21 23\n16 17 14 20 20 11 22\n" ], "output": [ "3\n" ] }
3,573
10
You are given an array a consisting of n integers (it is guaranteed that n is even, i.e. divisible by 2). All a_i does not exceed some integer k. Your task is to replace the minimum number of elements (replacement is the following operation: choose some index i from 1 to n and replace a_i with some integer in range [1; k]) to satisfy the following conditions: * after all replacements, all a_i are positive integers not greater than k; * for all i from 1 to n/2 the following equation is true: a_i + a_{n - i + 1} = x, where x should be the same for all n/2 pairs of elements. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and k (2 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 2 β‹… 10^5) β€” the length of a and the maximum possible value of some a_i correspondingly. It is guratanteed that n is even (i.e. divisible by 2). The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ k), where a_i is the i-th element of a. It is guaranteed that the sum of n (as well as the sum of k) over all test cases does not exceed 2 β‹… 10^5 (βˆ‘ n ≀ 2 β‹… 10^5, βˆ‘ k ≀ 2 β‹… 10^5). Output For each test case, print the answer β€” the minimum number of elements you have to replace in a to satisfy the conditions from the problem statement. Example Input 4 4 2 1 2 1 2 4 3 1 2 2 1 8 7 6 1 1 7 6 3 4 6 6 6 5 2 6 1 3 4 Output 0 1 4 2
def solve() : n, k = map(int, input().split()) a = [int(i) for i in input().split()] cnt = [0] * (2 * k + 2) for i in range(n // 2) : sum = a[i] + a[n - i - 1] cnt[2] += 2 cnt[sum - max(a[i], a[n - i - 1]) + 1] -= 1 cnt[sum] -= 1 cnt[sum + 1] += 1 cnt[sum + k - min(a[i], a[n - i - 1]) + 1] += 1 ans = n for i in range(2, 2 * k + 1) : cnt[i] += cnt[i - 1] ans = min(ans, cnt[i]) print(ans) t = int(input()) while t > 0: t -= 1 solve()
{ "input": [ "4\n4 2\n1 2 1 2\n4 3\n1 2 2 1\n8 7\n6 1 1 7 6 3 4 6\n6 6\n5 2 6 1 3 4\n" ], "output": [ "0\n1\n4\n2\n" ] }
3,574
11
Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers. The value of a non-empty subsequence of k elements of a is defined as βˆ‘ 2^i over all integers i β‰₯ 0 such that at least max(1, k - 2) elements of the subsequence have the i-th bit set in their binary representation (value x has the i-th bit set in its binary representation if ⌊ (x)/(2^i) βŒ‹ mod 2 is equal to 1). Recall that b is a subsequence of a, if b can be obtained by deleting some(possibly zero) elements from a. Help Ashish find the maximum value he can get by choosing some subsequence of a. Input The first line of the input consists of a single integer n (1 ≀ n ≀ 500) β€” the size of a. The next line consists of n space-separated integers β€” the elements of the array (1 ≀ a_i ≀ 10^{18}). Output Print a single integer β€” the maximum value Ashish can get by choosing some subsequence of a. Examples Input 3 2 1 3 Output 3 Input 3 3 1 4 Output 7 Input 1 1 Output 1 Input 4 7 7 1 1 Output 7 Note For the first test case, Ashish can pick the subsequence \{{2, 3}\} of size 2. The binary representation of 2 is 10 and that of 3 is 11. Since max(k - 2, 1) is equal to 1, the value of the subsequence is 2^0 + 2^1 (both 2 and 3 have 1-st bit set in their binary representation and 3 has 0-th bit set in its binary representation). Note that he could also pick the subsequence \{{3\}} or \{{2, 1, 3\}}. For the second test case, Ashish can pick the subsequence \{{3, 4\}} with value 7. For the third test case, Ashish can pick the subsequence \{{1\}} with value 1. For the fourth test case, Ashish can pick the subsequence \{{7, 7\}} with value 7.
def main(): n=int(input()) a=list(map(int,input().split())) ma=0 for i in range(n): for j in range(i,n): for k in range(j,n): ma=max(ma,a[i]|a[j]|a[k]) print(ma) main()
{ "input": [ "3\n3 1 4\n", "4\n7 7 1 1\n", "1\n1\n", "3\n2 1 3\n" ], "output": [ "7\n", "7\n", "1\n", "3\n" ] }
3,575
11
You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, 1 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2))) β€” the number of vertices and the number of edges in the graph, respectively. The next m lines describe edges of the graph. The i-th edge is described with three integers t_i, x_i and y_i (t_i ∈ [0; 1], 1 ≀ x_i, y_i ≀ n) β€” the type of the edge (t_i = 0 if the edge is undirected and t_i = 1 if the edge is directed) and vertices this edge connects (the undirected edge connects vertices x_i and y_i and directed edge is going from the vertex x_i to the vertex y_i). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair (x_i, y_i) there are no other pairs (x_i, y_i) or (y_i, x_i)). It is guaranteed that both sum n and sum m do not exceed 2 β‹… 10^5 (βˆ‘ n ≀ 2 β‹… 10^5; βˆ‘ m ≀ 2 β‹… 10^5). Output For each test case print the answer β€” "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and m lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any. Example Input 4 3 1 0 1 3 5 5 0 2 1 1 1 5 1 5 4 0 5 2 1 3 5 4 5 1 1 2 0 4 3 1 3 1 0 2 3 1 2 4 4 5 1 4 1 1 1 3 0 1 2 1 2 4 1 3 2 Output YES 3 1 YES 2 1 1 5 5 4 2 5 3 5 YES 1 2 3 4 3 1 3 2 2 4 NO Note Explanation of the second test case of the example: <image> Explanation of the third test case of the example: <image>
import bisect as bi import math as mt import collections as cc I=lambda:list(map(int,input().split())) def topo(g): indg=[0]*(n+1) for i in range(1,n+1): for j in g[i]: indg[j]+=1 st=cc.deque() for i in range(1,n+1): if indg[i]==0: st.append(i) ans=[] while st: x=st.pop() ans.append(x) for y in g[x]: indg[y]-=1 if indg[y]==0: st.append(y) return ans for tc in range(int(input())): n,m=I() g=cc.defaultdict(list) ed=[] for i in range(m): f,x,y=I() ed.append([x,y]) if f==1: g[x].append(y) top=topo(g) if len(top)<n: print("NO") else: print("YES") inn={} for i in range(n): inn[top[i]]=i for i in range(len(ed)): x,y=ed[i] if inn[x]>inn[y]: x,y=y,x print(x,y)
{ "input": [ "4\n3 1\n0 1 3\n5 5\n0 2 1\n1 1 5\n1 5 4\n0 5 2\n1 3 5\n4 5\n1 1 2\n0 4 3\n1 3 1\n0 2 3\n1 2 4\n4 5\n1 4 1\n1 1 3\n0 1 2\n1 2 4\n1 3 2\n" ], "output": [ "YES\n3 1\nYES\n2 1\n1 5\n5 4\n2 5\n3 5\nYES\n1 2\n3 4\n3 1\n3 2\n2 4\nNO\n" ] }
3,576
9
This is an interactive problem. We hid from you a permutation p of length n, consisting of the elements from 1 to n. You want to guess it. To do that, you can give us 2 different indices i and j, and we will reply with p_{i} mod p_{j} (remainder of division p_{i} by p_{j}). We have enough patience to answer at most 2 β‹… n queries, so you should fit in this constraint. Can you do it? As a reminder, 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). Input The only line of the input contains a single integer n (1 ≀ n ≀ 10^4) β€” length of the permutation. Interaction The interaction starts with reading n. Then you are allowed to make at most 2 β‹… n queries in the following way: * "? x y" (1 ≀ x, y ≀ n, x β‰  y). After each one, you should read an integer k, that equals p_x mod p_y. When you have guessed the permutation, print a single line "! " (without quotes), followed by array p and quit. 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. Exit immediately after receiving "-1" 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. Hack format In the first line output n (1 ≀ n ≀ 10^4). In the second line print the permutation of n integers p_1, p_2, …, p_n. Example Input 3 1 2 1 0 Output ? 1 2 ? 3 2 ? 1 3 ? 2 1 ! 1 3 2
import sys DEBUG = False def debug(*args): if not DEBUG: return print("\033[0;31m", end="", file=sys.stderr) print(*args, file=sys.stderr) print("\033[0m", end="", file=sys.stderr) sys.stderr.flush() def readInt(): line = input() while line == "": line = input() result = int(line) return result cache = {} def query(i, j): if (i, j) not in cache: print("? " + str(i + 1) + " " + str(j + 1), file=sys.stdout) sys.stdout.flush() if not DEBUG: x = readInt() debug("query", i, j, ":", x) else: x = REAL[i] % REAL[j] debug("query", i, j, "\t", REAL[i], "%", REAL[j], ":", x) cache[(i, j)] = x return cache[(i, j)] def answer(arr): print("! " + " ".join(str(x) for x in arr), file=sys.stdout) sys.stdout.flush() debug("ans", arr) def solve(): # Want the nth move to correspond with the nth bit. # While reconstructing we just need to know whether to go right or down, so make sure the diagonals alternate bits if DEBUG: cache.clear() N = len(REAL) debug("Testing", N, REAL) else: N = readInt() if N == 1: answer([1]) exit() ans = [-1 for i in range(N)] last = 0 for i in range(1, N): a = query(i, last) b = query(last, i) if a > b: # last is larger, so a is a[i] ans[i] = a if DEBUG: assert REAL[last] > REAL[i] else: ans[last] = b if DEBUG: assert REAL[last] < REAL[i] last = i for i in range(N): if ans[i] == -1: ans[i] = N answer(ans) assert len(cache) <= 2 * N return ans if DEBUG: import random random.seed(0) for _ in range(1000): N = 5 REAL = list(range(1, N + 1)) random.shuffle(REAL) assert solve() == REAL exit() if __name__ == "__main__": solve()
{ "input": [ "3\n\n1\n\n2\n\n1\n\n0" ], "output": [ "? 1 2\n? 2 1\n? 1 3\n? 3 1\n! 1 2 3 " ] }
3,577
7
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by 1 unit. <image> For example, if the box is at the point (1,2) and Wabbit is standing at the point (2,2), he can pull the box right by 1 unit, with the box ending up at the point (2,2) and Wabbit ending at the point (3,2). Also, Wabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly 1 unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located. Wabbit can start at any point. It takes 1 second to travel 1 unit right, left, up, or down, regardless of whether he pulls the box while moving. Determine the minimum amount of time he needs to move the box from (x_1,y_1) to (x_2,y_2). Note that the point where Wabbit ends up at does not matter. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 1000): the number of test cases. The description of the test cases follows. Each of the next t lines contains four space-separated integers x_1, y_1, x_2, y_2 (1 ≀ x_1, y_1, x_2, y_2 ≀ 10^9), describing the next test case. Output For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from (x_1,y_1) to (x_2,y_2). Example Input 2 1 2 2 2 1 1 2 2 Output 1 4 Note In the first test case, the starting and the ending points of the box are (1,2) and (2,2) respectively. This is the same as the picture in the statement. Wabbit needs only 1 second to move as shown in the picture in the statement. In the second test case, Wabbit can start at the point (2,1). He pulls the box to (2,1) while moving to (3,1). He then moves to (3,2) and then to (2,2) without pulling the box. Then, he pulls the box to (2,2) while moving to (2,3). It takes 4 seconds.
def recal(): x,y,a,b = map(int, input().split()) f = abs(x - a) g = abs(y - b) print(2*bool(f)*bool(g) + f + g) t = int(input()) while t > 0: recal() t -= 1
{ "input": [ "2\n1 2 2 2\n1 1 2 2\n" ], "output": [ "1\n4\n" ] }
3,578
7
Ridbit starts with an integer n. In one move, he can perform one of the following operations: * divide n by one of its proper divisors, or * subtract 1 from n if n is greater than 1. A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 20 itself is not. What is the minimum number of moves Ridbit is required to make to reduce n to 1? Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains a single integer n (1 ≀ n ≀ 10^9). Output For each test case, output the minimum number of moves required to reduce n to 1. Example Input 6 1 2 3 4 6 9 Output 0 1 2 2 2 3 Note For the test cases in the example, n may be reduced to 1 using the following operations in sequence 1 2 \xrightarrow{} 1 3 \xrightarrow{} 2 \xrightarrow{} 1 4 \xrightarrow{} 2 \xrightarrow{} 1 6 \xrightarrow{} 2 \xrightarrow{} 1 9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1
def solve(n): if n == 1: return 0 elif n == 2: return 1 elif n == 3: return 2 elif n % 2 != 0: return 3 else: return 2 t = int(input()) for _ in range(t): n = int(input()) print(solve(n))
{ "input": [ "6\n1\n2\n3\n4\n6\n9\n" ], "output": [ "\n0\n1\n2\n2\n2\n3\n" ] }
3,579
7
You are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x > 1) that n is divisible by x and x is odd). For example, if n=6, then there is x=3. If n=4, then such a number does not exist. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case contains one integer n (2 ≀ n ≀ 10^{14}). Please note, that the input for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language. Output For each test case, output on a separate line: * "YES" if n has an odd divisor, greater than one; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 6 2 3 4 5 998244353 1099511627776 Output NO YES NO YES YES NO
def func(n): if (n==1): return "NO" if (n%2!=0): return "YES" return func(n//2) t = int(input()) for _ in range(t): n = int(input()) print(func(n))
{ "input": [ "6\n2\n3\n4\n5\n998244353\n1099511627776\n" ], "output": [ "\nNO\nYES\nNO\nYES\nYES\nNO\n" ] }
3,580
10
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads. The Β«Two PathsΒ» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities). It is known that the profit, the Β«Two PathsΒ» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company. Input The first line contains an integer n (2 ≀ n ≀ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≀ ai, bi ≀ n). Output Output the maximum possible profit. Examples Input 4 1 2 2 3 3 4 Output 1 Input 7 1 2 1 3 1 4 1 5 1 6 1 7 Output 0 Input 6 1 2 2 3 2 4 5 4 6 4 Output 4
n = int(input()) p = [[] for i in range(n + 1)] for j in range(n - 1): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) def g(b, c): x = y = d = 0 for a in p[b]: if a != c: s, z = g(a, b) z, y, x = sorted([x, y, z]) d = max(d, s) return max(d, x + y), x + 1 print(max(g(a, b)[0] * g(b, a)[0] for a in range(n + 1) for b in p[a] if b > a))
{ "input": [ "6\n1 2\n2 3\n2 4\n5 4\n6 4\n", "7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n", "4\n1 2\n2 3\n3 4\n" ], "output": [ "4", "0", "1" ] }
3,581
7
You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly k\ \% magic essence and (100 - k)\ \% water. In one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it. A small reminder: if you pour e liters of essence and w liters of water (e + w > 0) into the cauldron, then it contains (e)/(e + w) β‹… 100\ \% (without rounding) magic essence and (w)/(e + w) β‹… 100\ \% water. Input The first line contains the single t (1 ≀ t ≀ 100) β€” the number of test cases. The first and only line of each test case contains a single integer k (1 ≀ k ≀ 100) β€” the percentage of essence in a good potion. Output For each test case, print the minimum number of steps to brew a good potion. It can be proved that it's always possible to achieve it in a finite number of steps. Example Input 3 3 100 25 Output 100 1 4 Note In the first test case, you should pour 3 liters of magic essence and 97 liters of water into the cauldron to get a potion with 3\ \% of magic essence. In the second test case, you can pour only 1 liter of essence to get a potion with 100\ \% of magic essence. In the third test case, you can pour 1 liter of magic essence and 3 liters of water.
import math def solve(k) : print (100// math.gcd(100, k)) t = int(input()) for i in range(t) : k = int(input()) solve(k)
{ "input": [ "3\n3\n100\n25\n" ], "output": [ "\n100\n1\n4\n" ] }
3,582
10
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous. Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: * climb one area up; * climb one area down; * jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon. The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" β€” first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on. The level is considered completed if the ninja manages to get out of the canyon. After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. Input The first line contains two integers n and k (1 ≀ n, k ≀ 105) β€” the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall β€” a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. Output Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). Examples Input 7 3 ---X--X -X--XX- Output YES Input 6 2 --X-X- X--XX- Output NO Note In the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon.
from collections import deque l, j = [int(i) for i in input().split(' ')] wallA = list(input()) wallB = list(input()) g = {} for i in range(l): # Each 4-tuple represents: (Visited?, Current Height, Current Water Height, Drowned?) if wallA[i] == '-': g[(1,i+1)] = (-1, 0, 0, False) if wallB[i] == '-': g[(-1,i+1)] = (-1, 0, 0, False) g[(1, 1)] = ('VISITED', 1, 0, False) q = deque([(1, 1)]) while q: c = q.popleft() up = (c[0], c[1]+1) down = (c[0], c[1]-1) jump = (c[0]*-1, c[1] + j) if g[c][1] <= g[c][2]: g[c] = (g[c][0], g[c][1], g[c][2], True) if up in g and g[up][0] == -1: q.append(up) g[up] = ('VISITED', g[c][1] + 1, g[c][2] + 1, g[c][3]) if down in g and g[down][0] == -1: q.append(down) g[down] = ('VISITED', g[c][1] - 1, g[c][2] + 1, g[c][3]) if jump in g and g[jump][0] == -1: q.append(jump) g[jump] = ('VISITED', g[c][1] + j, g[c][2] + 1, g[c][3]) def graphHasEscape(graph): for node in graph: result = graph[node] if result[0] == 'VISITED' and ((result[1] + 1 > l) or (result[1] + j > l)) and not result[3]: return True break return False if graphHasEscape(g): print('YES') else: print('NO')
{ "input": [ "6 2\n--X-X-\nX--XX-\n", "7 3\n---X--X\n-X--XX-\n" ], "output": [ "NO\n", "YES\n" ] }
3,583
11
Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most m different nucleotides, numbered from 1 to m. Special characteristics of the Martian DNA prevent some nucleotide pairs from following consecutively in this chain. For example, if the nucleotide 1 and nucleotide 2 can not follow consecutively in the Martian DNA, then the chain of nucleotides [1, 2] is not a valid chain of Martian DNA, but the chain of nucleotides [2, 1] can be a valid chain (if there is no corresponding restriction). The number of nucleotide pairs that can't follow in the DNA chain consecutively, is k. The needs of gene research required information about the quantity of correct n-long chains of the Martian DNA. Your task is to write a program that will calculate this value. Input The first line contains three space-separated integers n, m, k (1 ≀ n ≀ 1015, 1 ≀ m ≀ 52, 0 ≀ k ≀ m2). Next k lines contain two characters each, without a space between them, representing a forbidden nucleotide pair. The first character represents the first nucleotide in the forbidden pair, the second character represents the second nucleotide. The nucleotides with assigned numbers from 1 to 26 are represented by English alphabet letters from "a" to "z" (1 is an "a", 2 is a "b", ..., 26 is a "z"). Nucleotides with assigned numbers from 27 to 52 are represented by English alphabet letters from "A" to "Z" (27 is an "A", 28 is a "B", ..., 52 is a "Z"). It is guaranteed that each forbidden pair occurs at most once in the input. It is guaranteed that nucleotide's numbers in all forbidden pairs cannot be more than m. Note that order is important in nucleotide pairs. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. Output Print a single integer β€” the sought number modulo 1000000007 (109 + 7). Examples Input 3 3 2 ab ba Output 17 Input 3 3 0 Output 27 Input 2 1 1 aa Output 0 Note In the second test case all possible three-nucleotide DNAs are permitted. Each nucleotide can take one of three values, thus in total there are 27 distinct three nucleotide DNAs. In the third test sample we cannot make any DNA of two nucleotides β€” the only possible nucleotide "a" cannot occur two times consecutively.
import os from io import BytesIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline import string def main(): d = 0 class Matrix(): def __init__(self,ar): self.ar = ar def __mul__(self,other): n = d m = d p = d ans = [[0 for i in range(p)] for i in range(m)] for i in range(m): for j in range(p): for k in range(n): ans[i][j] += self[i][k] * other[k][j] ans[i][j] %= mod return Matrix(ans) def __mod__(self,other): m = len(self[0]) for i in range(len(self.ar)): for j in range(m): self[i][j] %= other return self def __getitem__(self, key): return self.ar[key] mod = 10**9 + 7 def power(number, n): res = number while(n): if n & 1: res *= number n -= 1 number *= number n >>= 1 return res n,m,k = map(int,input().split()) d = m m2 = Matrix([[1 for i in range(m)]for i in range(m)]) alth = string.ascii_letters for i in range(k): s = str(input()) temp = alth.find(s[2]) temp2 = alth.find(s[3]) m2[temp2][temp] = 0 if n == 1: print(m) elif n==2: print(m**2-k) else: ar = power(m2,n-2).ar ans = 0 for i in range(m): for j in range(m): ans += ar[i][j] ans %= mod print(ans) main()
{ "input": [ "3 3 0\n", "2 1 1\naa\n", "3 3 2\nab\nba\n" ], "output": [ "27\n", "0\n", "17\n" ] }
3,584
9
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants. All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier. On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers. Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty. Input The first line contains two integers n, k (1 ≀ n ≀ 50; 1 ≀ k ≀ <image>) β€” the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 107) β€” the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty. Output Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1 ≀ ci ≀ n) β€” the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1, i, p2, i, ..., pci, i β€” the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them. Examples Input 3 3 1 2 3 Output 1 1 1 2 2 3 2 Input 2 1 7 12 Output 1 12
from sys import stdin def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return list(stdin.readline()[:-1]) n, k = arr_inp(1) c = sorted(arr_inp(1))[::-1] for i in range(min(n, k)): print(1, c[i]) k -= 1 tem = [] for i in range(min(n - 1, k)): tem.append(c[i]) for j in range(n - 1, i, -1): print(i + 2, end=' ') print(*(tem + [c[j]])) k -= 1 if not k: exit()
{ "input": [ "2 1\n7 12\n", "3 3\n1 2 3\n" ], "output": [ "1 7 \n", "1 1 \n1 2 \n1 3 \n" ] }
3,585
10
You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad. A substring s[l...r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2...s|s| (where |s| is the length of string s) is string slsl + 1...sr. The substring s[l...r] is good, if among the letters sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear). Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] β‰  s[p...q]. Input The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer k (0 ≀ k ≀ |s|) β€” the maximum acceptable number of bad characters in a good substring. Output Print a single integer β€” the number of distinct good substrings of string s. Examples Input ababab 01000000000000000000000000 1 Output 5 Input acbacbacaa 00000000000000000000000000 2 Output 8 Note In the first example there are following good substrings: "a", "ab", "b", "ba", "bab". In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".
def index(c): return ord(c) - ord('a') class Trie: def __init__(self): self._children = {} self.mark = False def get(self, c): i = index(c) if i not in self._children: self._children[i] = Trie() return self._children[i] def solve(s, k, is_good): n = len(s) trie = Trie() res = 0 for i in range(n): bad = 0 cur = trie for j in range(i, n): if not is_good[index(s[j])]: bad += 1 if bad > k: break cur = cur.get(s[j]) if not cur.mark: res += 1 cur.mark = True return res s = input() is_good = [c == '1' for c in input()] k = int(input()) print(solve(s, k, is_good))
{ "input": [ "acbacbacaa\n00000000000000000000000000\n2\n", "ababab\n01000000000000000000000000\n1\n" ], "output": [ "8", "5" ] }
3,586
7
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≀ li ≀ ri ≀ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di. Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≀ xi ≀ yi ≀ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array. Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg. Input The first line contains integers n, m, k (1 ≀ n, m, k ≀ 105). The second line contains n integers: a1, a2, ..., an (0 ≀ ai ≀ 105) β€” the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≀ li ≀ ri ≀ n), (0 ≀ di ≀ 105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≀ xi ≀ yi ≀ m). The numbers in the lines are separated by single spaces. Output On a single line print n integers a1, a2, ..., an β€” the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 3 3 3 1 2 3 1 2 1 1 3 2 2 3 4 1 2 1 3 2 3 Output 9 18 17 Input 1 1 1 1 1 1 1 1 1 Output 2 Input 4 3 6 1 2 3 4 1 2 1 2 3 2 3 4 4 1 2 1 3 2 3 1 2 1 3 2 3 Output 5 18 31 20
def main(): n, m, k = map(int, input().split()) aa = list(map(int, input().split())) lrd = list(tuple(map(int, input().split())) for _ in range(m)) cnt = [0] * (m + 1) for _ in range(k): x, y = map(int, input().split()) cnt[x - 1] += 1 cnt[y] -= 1 delta, c = [0] * (n + 1), 0 for (l, r, d), dc in zip(lrd, cnt): c += dc d *= c delta[l - 1] += d delta[r] -= d da = 0 for i, a, d in zip(range(n), aa, delta): da += d aa[i] = a + da print(" ".join(map(str, aa))) if __name__ == '__main__': main()
{ "input": [ "3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3\n", "1 1 1\n1\n1 1 1\n1 1\n", "4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3\n" ], "output": [ "9 18 17 \n", "2 \n", "5 18 31 20 \n" ] }
3,587
7
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift. In order to pass through a guardpost, one needs to bribe both guards. The shop has an unlimited amount of juice and chocolate of any price starting with 1. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend exactly n rubles on it. Help him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that! Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the money Dima wants to spend. Then follow four lines describing the guardposts. Each line contains four integers a, b, c, d (1 ≀ a, b, c, d ≀ 105) β€” the minimum price of the chocolate and the minimum price of the juice for the first guard and the minimum price of the chocolate and the minimum price of the juice for the second guard, correspondingly. Output In a single line of the output print three space-separated integers: the number of the guardpost, the cost of the first present and the cost of the second present. If there is no guardpost Dima can sneak Inna through at such conditions, print -1 in a single line. The guardposts are numbered from 1 to 4 according to the order given in the input. If there are multiple solutions, you can print any of them. Examples Input 10 5 6 5 6 6 6 7 7 5 8 6 6 9 9 9 9 Output 1 5 5 Input 10 6 6 6 6 7 7 7 7 4 4 4 4 8 8 8 8 Output 3 4 6 Input 5 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 Output -1 Note Explanation of the first example. The only way to spend 10 rubles to buy the gifts that won't be less than the minimum prices is to buy two 5 ruble chocolates to both guards from the first guardpost. Explanation of the second example. Dima needs 12 rubles for the first guardpost, 14 for the second one, 16 for the fourth one. So the only guardpost we can sneak through is the third one. So, Dima can buy 4 ruble chocolate for the first guard and 6 ruble juice of the second guard.
def solve(): n = int(input()) for i in range(1, 5): a, b, c, d = map(int, input().split()) if min(a, b) + min(c, d) <= n: print(i, min(a, b), n - min(a, b)) exit() print(-1) if __name__ == "__main__": solve()
{ "input": [ "10\n6 6 6 6\n7 7 7 7\n4 4 4 4\n8 8 8 8\n", "10\n5 6 5 6\n6 6 7 7\n5 8 6 6\n9 9 9 9\n", "5\n3 3 3 3\n3 3 3 3\n3 3 3 3\n3 3 3 3\n" ], "output": [ "3 4 6\n", "1 5 5\n", "-1\n" ] }
3,588
11
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty. Suppose Ciel and Jiro play optimally, what is the score of the game? Input The first line contain an integer n (1 ≀ n ≀ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≀ si ≀ 100) β€” the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≀ ck ≀ 1000) β€” the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile. Output Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally. Examples Input 2 1 100 2 1 10 Output 101 10 Input 1 9 2 8 6 5 9 4 7 1 3 Output 30 15 Input 3 3 1 3 2 3 5 4 6 2 8 7 Output 18 18 Input 3 3 1000 1000 1000 6 1000 1000 1000 1000 1000 1000 5 1000 1000 1000 1000 1000 Output 7000 7000 Note In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10. In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.
import re def main(): n=eval(input()) a=[] s=[] s.append(0) s.append(0) while n: n-=1 temp=re.split(' ',input()) k=eval(temp[0]) for i in range(k>>1): s[0]+=eval(temp[i+1]) if k&1: a.append(eval(temp[(k+1)>>1])) for i in range((k+1)>>1,k): s[1]+=eval(temp[i+1]) a.sort(reverse=True) k=0 for i in a: s[k]+=i k^=1 print(s[0],s[1]) main()
{ "input": [ "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000\n", "2\n1 100\n2 1 10\n", "3\n3 1 3 2\n3 5 4 6\n2 8 7\n", "1\n9 2 8 6 5 9 4 7 1 3\n" ], "output": [ "7000 7000\n", "101 10\n", "18 18\n", "30 15\n" ] }
3,589
9
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed. Help the child to find out, what is the minimum total energy he should spend to remove all n parts. Input The first line contains two integers n and m (1 ≀ n ≀ 1000; 0 ≀ m ≀ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≀ vi ≀ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≀ xi, yi ≀ n; xi β‰  yi). Consider all the parts are numbered from 1 to n. Output Output the minimum total energy the child should spend to remove all n parts of the toy. Examples Input 4 3 10 20 30 40 1 4 1 2 2 3 Output 40 Input 4 4 100 100 100 100 1 2 2 3 2 4 3 4 Output 400 Input 7 10 40 10 20 10 20 80 40 1 5 4 7 4 5 5 2 5 7 6 4 1 6 1 3 4 3 1 4 Output 160 Note One of the optimal sequence of actions in the first sample is: * First, remove part 3, cost of the action is 20. * Then, remove part 2, cost of the action is 10. * Next, remove part 4, cost of the action is 10. * At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum. In the second sample, the child will spend 400 no matter in what order he will remove the parts.
def mlt(): return map(int, input().split()) x, y = mlt() s = [0] + list(mlt()) res = 0 for n in range(y): a, b = mlt() res += min(s[a], s[b]) print(res)
{ "input": [ "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4\n", "4 3\n10 20 30 40\n1 4\n1 2\n2 3\n", "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4\n" ], "output": [ "400", "40", "160" ] }
3,590
10
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≀ ai < bi ≀ n) and ci(1 ≀ ci ≀ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β‰  j, (ai, bi, ci) β‰  (aj, bj, cj). The next line contains a integer- q(1 ≀ q ≀ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≀ ui, vi ≀ n). It is guaranteed that ui β‰  vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
f = lambda: map(int, input().split()) n, m = f() p = [list(range(n + 1)) for x in range(m + 1)] def g(c, x): if x != p[c][x]: p[c][x] = g(c, p[c][x]) return p[c][x] for i in range(m): a, b, c = f() p[c][g(c, a)] = g(c, b) for j in range(int(input())): a, b = f() print(sum(g(i, a) == g(i, b) for i in range(m + 1)))
{ "input": [ "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4\n", "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4\n" ], "output": [ "2\n1\n0\n", "1\n1\n1\n1\n2\n" ] }
3,591
9
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it: * inc(lf, rg, v) β€” this operation increases each element on the segment [lf, rg] (inclusively) by v; * rmq(lf, rg) β€” this operation returns minimal value on the segment [lf, rg] (inclusively). Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1. Write program to process given sequence of operations. Input The first line contains integer n (1 ≀ n ≀ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≀ ai ≀ 106), ai are integer. The third line contains integer m (0 ≀ m ≀ 200000), m β€” the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≀ lf, rg ≀ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≀ lf, rg ≀ n - 1; - 106 ≀ v ≀ 106) β€” inc operation. Output For each rmq operation write result for it. 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 4 1 2 3 4 4 3 0 3 0 -1 0 1 2 1 Output 1 0 0
import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n=int(input()) a=list(map(int,input().split())) class st: def __init__(self, size): N = 1 h = 0 while N < size: N <<= 1 h += 1 self.N = N self.h = h self.t = [float('inf')] * (2 * N) self.d = [0] * N def apply(self, p, value): self.t[p] += value if (p < self.N): self.d[p] += value def build(self, p): t = self.t d = self.d while p > 1: p >>= 1 t[p] = min(t[p<<1], t[p<<1|1]) + d[p] def rebuild(self): t = self.t for p in reversed(range(1, self.N)): t[p] = min(t[p<<1], t[p<<1|1]) def push(self, p): d = self.d for s in range(self.h, 0, -1): i = p >> s if d[i] != 0: self.apply(i<<1, d[i]) self.apply(i<<1|1, d[i]) d[i] = 0 def inc(self, l, r, value): if l >= r: return l += self.N r += self.N l0, r0 = l, r while l < r: if l & 1: self.apply(l, value) l += 1 if r & 1: r -= 1 self.apply(r, value) l >>= 1 r >>= 1 self.build(l0) self.build(r0 - 1) def query(self, l, r): if l >= r: return float('inf') t = self.t l += self.N r += self.N self.push(l) self.push(r - 1) res = float('inf') while l < r: if l & 1: res = min(res, t[l]) l += 1 if r & 1: r -= 1 res = min(t[r], res) l >>= 1 r >>= 1 return res se=st(n) N=se.N for i in range(n): se.t[i+N]=a[i] se.rebuild() q=int(input()) for i in range(q): b=list(map(int,input().split())) if len(b)==2: l=b[0] r=b[1] if l>r: print(min(se.query(l,n),se.query(0,r+1))) else:print(se.query(l,r+1)) else: l=b[0] r=b[1] v=b[2] if l>r: se.inc(0,r+1,v) se.inc(l,n,v) else:se.inc(l,r+1,v)
{ "input": [ "4\n1 2 3 4\n4\n3 0\n3 0 -1\n0 1\n2 1\n" ], "output": [ "1\n0\n0\n" ] }
3,592
10
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard. Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules. Input The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≀ x1, y1, x2, y2, x3, y3 ≀ 100), where xi and yi determine the length and width of the logo of the i-th company respectively. Output If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: * the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, * the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, * the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement. Examples Input 5 1 2 5 5 2 Output 5 AAAAA BBBBB BBBBB CCCCC CCCCC Input 4 4 2 6 4 2 Output 6 BBBBBB BBBBBB AAAACC AAAACC AAAACC AAAACC
def chnge(last,cap,ini=(0,0)): for i in range(ini[1],last[1]): fin[i][ini[0]:last[0]] = [cap]*(last[0]-ini[0]) x1,y1,x2,y2,x3,y3 = map(int,input().split()) a = (max(x1,y1),[x1,y1],"A") b = (max(x2,y2),[x2,y2],"B") c = (max(x3,y3),[x3,y3],"C") m = max(a[0],b[0],c[0]) fin = [["*" for i in range(m)] for j in range(m)] if (x1*y1 + x2*y2 + x3*y3)!=m**2: print(-1) else: l = sorted([a]+[b]+[c],reverse = True) l[0][1].sort(reverse=True) chnge(l[0][1],l[0][2]) ini=[0,l[0][1][1]] last = l[1][1] if m in [ini[0]+last[0],ini[1]+last[1]] and (ini[0]+last[0]+ini[1]+last[1])<=2*m: last = [ini[0]+last[0],ini[1]+last[1]] else: last = [ini[0] + last[1], ini[1] + last[0]] chnge(last,l[1][2],ini) chr = l[2][2] print(m) for i in fin: print("".join(i).replace("*",chr))
{ "input": [ "4 4 2 6 4 2\n", "5 1 2 5 5 2\n" ], "output": [ "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC\n", "5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC\n" ] }
3,593
9
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either: 1. Remove a single cow from a chosen non-empty pile. 2. Choose a pile of cows with even size 2Β·x (x > 0), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way. Input The first line of the input contains two space-separated integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109). The second line contains n integers, a1, a2, ... an (1 ≀ ai ≀ 109) describing the initial state of the game. Output Output the name of the winning player, either "Kevin" or "Nicky" (without quotes). Examples Input 2 1 3 4 Output Kevin Input 1 2 3 Output Nicky Note In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
from functools import reduce def gao(x,y): if x==1: return 1 if x==2: return (~y&1)*2 if x==3: return y&1 if x&1: return 0 if ~y&1: return 1 l=len(bin(x))-bin(x).rfind('1')-1 if x>>l==3: l+=1 return 2-l%2 n,k=map(int,input().split()) s=reduce(lambda x,y:x^gao(y,k),map(int,[0]+input().split())) if s: print('Kevin') else: print('Nicky')
{ "input": [ "1 2\n3\n", "2 1\n3 4\n" ], "output": [ "Nicky\n", "Kevin\n" ] }
3,594
7
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
def f(t): return t.count('U') == t.count('D') and t.count('L') == t.count('R') n, s = int(input()), input() print(sum(f(s[i:j]) for i in range(n) for j in range(i + 1, n + 1)))
{ "input": [ "6\nURLLDR\n", "4\nDLUU\n", "7\nRLRLRLR\n" ], "output": [ "2", "0", "12" ] }
3,595
8
Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image>
def main(): n, a, b, c, d = map(int, input().split()) l = sorted((a + b, a + c, b + d, c + d)) print(n * max(n + l[0] - l[3], 0)) if __name__ == '__main__': main()
{ "input": [ "3 3 1 2 3\n", "2 1 1 1 2\n" ], "output": [ "6", "2" ] }
3,596
9
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
def vacations(n, d, a): prev = 3 res = 0 for i in a: if (i == prev and prev != 3): i = 0 elif (i == 3 and prev != 3): i -= prev if i == 0: res += 1 prev = i return res n = input() d = input() a = list(map(int, d.split(' '))) print(vacations(n, d, a))
{ "input": [ "4\n1 3 2 0\n", "7\n1 3 3 2 1 2 3\n", "2\n2 2\n" ], "output": [ "2\n", "0\n", "1\n" ] }
3,597
11
There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints.
#!/usr/bin/env python3 import itertools # Initialize look-up tables element_to_value = { 'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na':11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18, 'K':19, 'Ca':20, 'Sc':21, 'Ti':22, 'V':23, 'Cr':24, 'Mn':25, 'Fe':26, 'Co':27, 'Ni':28, 'Cu':29, 'Zn':30, 'Ga':31, 'Ge':32, 'As':33, 'Se':34, 'Br':35, 'Kr':36, 'Rb':37, 'Sr':38, 'Y':39, 'Zr':40, 'Nb':41, 'Mo':42, 'Tc':43, 'Ru':44, 'Rh':45, 'Pd':46, 'Ag':47, 'Cd':48, 'In':49, 'Sn':50, 'Sb':51, 'Te':52, 'I':53, 'Xe':54, 'Cs':55, 'Ba':56, 'La':57, 'Ce':58, 'Pr':59, 'Nd':60, 'Pm':61, 'Sm':62, 'Eu':63, 'Gd':64, 'Tb':65, 'Dy':66, 'Ho':67, 'Er':68, 'Tm':69, 'Yb':70, 'Lu':71, 'Hf':72, 'Ta':73, 'W':74, 'Re':75, 'Os':76, 'Ir':77, 'Pt':78, 'Au':79, 'Hg':80, 'Tl':81, 'Pb':82, 'Bi':83, 'Po':84, 'At':85, 'Rn':86, 'Fr':87, 'Ra':88, 'Ac':89, 'Th':90, 'Pa':91, 'U':92, 'Np':93, 'Pu':94, 'Am':95, 'Cm':96, 'Bk':97, 'Cf':98, 'Es':99, 'Fm':100 } value_to_element = dict() for (element, value) in element_to_value.items(): value_to_element[value] = element # Read inputs (n,k) = map(int,input().split()) products_start_str = input().split() products_end_str = input().split() # Translate elements to their values products_start = [element_to_value[elem] for elem in products_start_str] products_end = [element_to_value[elem] for elem in products_end_str] # Filter out duplicates; keep track of ingredient values and their number products_start.sort() ingredient_value = [] ingredient_count = [] for (key, lst) in itertools.groupby(products_start): ingredient_value.append(key) ingredient_count.append(len(list(lst))) nr_ingredients = len(ingredient_value) # Figure out the options for constructing the final products construction_options = [[] for i in range(k)] for combination in itertools.product(*[range(l+1) for l in ingredient_count]): value = sum(combination[i]*ingredient_value[i] for i in range(nr_ingredients)) if (value in products_end): for i in range(k): if products_end[i] == value: construction_options[i].append(combination) # Do a depth-first search on the construction options for a possible solution solution = [None for i in range(k)] def find_solution(used = [0 for i in range(nr_ingredients)], next = 0): if (next == k): return all(used[i] == ingredient_count[i] for i in range(nr_ingredients)) else: for option in construction_options[next]: usage = [used[i]+option[i] for i in range(nr_ingredients)] if all(used[i] <= ingredient_count[i] for i in range(nr_ingredients)): possible = find_solution(usage, next+1) if (possible): solution[next] = option return True return False possible = find_solution() # Print the answer if not possible: print("NO") exit() def combination_to_recipe(combination): recipe = [] for i in range(nr_ingredients): for j in range(combination[i]): recipe.append(value_to_element[ingredient_value[i]]) return recipe print("YES") for i in range(k): recipe = combination_to_recipe(solution[i]) print("%s->%s" % ("+".join(recipe),products_end_str[i]))
{ "input": [ "2 2\nBk Fm\nCf Es\n", "2 1\nH H\nHe\n", "10 3\nMn Co Li Mg C P F Zn Sc K\nSn Pt Y\n" ], "output": [ "NO\n", "YES\nH+H->He\n", "YES\nMn+C+K->Sn\nCo+Mg+F+Zn->Pt\nLi+P+Sc->Y\n" ] }
3,598
8
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
R = lambda: map(int, input().split()) n, m, w = R() ws = list(R()) bs = list(R()) anc = [-1] * n def get(x): if anc[x] < 0: return x anc[x] = get(anc[x]) return anc[x] def join(x1, x2): x1, x2 = get(x1), get(x2) if x1 != x2: anc[x1] = x2 for i in range(m): x1, x2 = R() join(x1 - 1, x2 - 1) gps = [list() for i in range(n)] for i in range(n): gps[get(i)].append(i) gps = [x for x in gps if x] dp = [[0] * (w + 1) for i in range(len(gps) + 1)] for i in range(len(gps)): tw = sum(ws[x] for x in gps[i]) tb = sum(bs[x] for x in gps[i]) for j in range(w + 1): dp[i][j] = max(tb + dp[i - 1][j - tw] if tw <= j else 0, dp[i - 1][j]) for k in gps[i]: dp[i][j] = max(dp[i][j], (dp[i - 1][j - ws[k]] + bs[k] if ws[k] <= j else 0)) print(dp[len(gps) - 1][w])
{ "input": [ "3 1 5\n3 2 5\n2 4 2\n1 2\n", "4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3\n" ], "output": [ "6\n", "7\n" ] }
3,599
7
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list.
def main(): print(('home', 'contest')[int(input()) & 1]) if __name__ == '__main__': main()
{ "input": [ "3\nSVO\nSVO-&gt;HKT\nHKT-&gt;SVO\nSVO-&gt;RAP\n", "4\nSVO\nSVO-&gt;CDG\nLHR-&gt;SVO\nSVO-&gt;LHR\nCDG-&gt;SVO\n" ], "output": [ "contest\n", "home\n" ] }