index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
300
8
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems β€” the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string. 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. String x = x1x2... xp is lexicographically smaller than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there exists such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The string characters are compared by their ASCII codes. Input The first line contains integer n (1 ≀ n ≀ 30) β€” the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive. Output Print a string, consisting of lowercase English letters β€” the lexicographically minimum shortest original title. Examples Input 5 threehorses goodsubstrings secret primematrix beautifulyear Output j Input 4 aa bdefghijklmn opqrstuvwxyz c Output ab Note In the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j. In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title.
n=int(input()) alph="abcdefghijklmnopqrstuvwxyz" ch="" for x in range(n): ch+=" "+input() def f(): ch1="" j=0 for k in range(26): for i in range(26): if ch1+alph[i] not in ch: print(ch1+alph[i]) return ch1=alph[j] j+=1 f()
{ "input": [ "4\naa\nbdefghijklmn\nopqrstuvwxyz\nc\n", "5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear\n" ], "output": [ "ab\n", "j\n" ] }
301
7
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero ( < 0). 2. The product of all numbers in the second set is greater than zero ( > 0). 3. The product of all numbers in the third set is equal to zero. 4. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. Input The first line of the input contains integer n (3 ≀ n ≀ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≀ 103) β€” the array elements. Output In the first line print integer n1 (n1 > 0) β€” the number of elements in the first set. Then print n1 numbers β€” the elements that got to the first set. In the next line print integer n2 (n2 > 0) β€” the number of elements in the second set. Then print n2 numbers β€” the elements that got to the second set. In the next line print integer n3 (n3 > 0) β€” the number of elements in the third set. Then print n3 numbers β€” the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. Examples Input 3 -1 2 0 Output 1 -1 1 2 1 0 Input 4 -1 -2 -3 0 Output 1 -1 2 -3 -2 1 0
def main(): n = int(input()) a = set(map(int, input().split())) print(1, min(a)) a -= {min(a)} if max(a) > 0: s = {max(a)} a -= s else: s = {min(a)} a -= s s.add(min(a)) a -= {min(a)} print(len(s), ' '.join(map(str, s))) print(len(a), ' '.join(map(str, a))) if __name__ == '__main__': main()
{ "input": [ "4\n-1 -2 -3 0\n", "3\n-1 2 0\n" ], "output": [ "1 -1\n2 -3 -2\n1 0\n", "1 -1\n1 2\n1 0\n" ] }
302
7
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. Input The first line contains a single integer β€” n (1 ≀ n ≀ 5Β·105). Each of the next n lines contains an integer si β€” the size of the i-th kangaroo (1 ≀ si ≀ 105). Output Output a single integer β€” the optimal number of visible kangaroos. Examples Input 8 2 5 7 6 9 8 4 2 Output 5 Input 8 9 1 6 2 6 5 8 3 Output 5
import sys def sol(a,n): a.sort() i = 0 j = n//2 ans = n while i < n//2 and j < n: if 2*a[i] <= a[j]: ans-=1 i+=1 j+=1 else: j+=1 return ans n = int(input()) a = [int(i) for i in sys.stdin] print(sol(a,n))
{ "input": [ "8\n2\n5\n7\n6\n9\n8\n4\n2\n", "8\n9\n1\n6\n2\n6\n5\n8\n3\n" ], "output": [ "5\n", "5\n" ] }
303
8
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be? See notes for definition of a tandem repeat. Input The first line contains s (1 ≀ |s| ≀ 200). This string contains only small English letters. The second line contains number k (1 ≀ k ≀ 200) β€” the number of the added characters. Output Print a single number β€” the maximum length of the tandem repeat that could have occurred in the new string. Examples Input aaba 2 Output 6 Input aaabbbb 2 Output 6 Input abracadabra 10 Output 20 Note A tandem repeat of length 2n is string s, where for any position i (1 ≀ i ≀ n) the following condition fulfills: si = si + n. In the first sample Kolya could obtain a string aabaab, in the second β€” aaabbbbbb, in the third β€” abracadabrabracadabra.
def max_len(s): N = len(s) for L in range(N // 2, 0, -1): for i in range(N - 2 * L + 1): if all(ch2 in ch1 + '_' for ch1, ch2 in zip(s[i:i+L], s[i+L:i+2*L])): return 2 * L print(max_len(input() + '_' * int(input())))
{ "input": [ "aaabbbb\n2\n", "aaba\n2\n", "abracadabra\n10\n" ], "output": [ "6\n", "6\n", "20\n" ] }
304
9
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more. Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist. Input The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition). Output If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes). Examples Input 3 3 cba Output NO Input 3 4 cba Output cbd Input 4 4 abcd Output abda Note String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1. The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one. A palindrome is a string that reads the same forward or reversed.
def trans(c): return chr(ord(c) + 1) n, p = list(map(int, input().split())) s = list(input()) s[n-1] = trans(s[n-1]) i = n - 1 while i >= 0 and i < n: if ord(s[i]) >= ord('a') + p: s[i] = 'a' i -= 1 s[i] = trans(s[i]) elif i > 0 and s[i] == s[i-1] or i > 1 and s[i] == s[i-2]: s[i] = trans(s[i]) else: i += 1 else: print("NO" if i < 0 else "".join(s)) # Made By Mostafa_Khaled
{ "input": [ "3 4\ncba\n", "3 3\ncba\n", "4 4\nabcd\n" ], "output": [ "cbd\n", "NO\n", "abda\n" ] }
305
8
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one. For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls. Input The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill. Output Print a single number β€” the required maximum possible number of pairs. Examples Input 4 1 4 6 2 5 5 1 5 7 9 Output 3 Input 4 1 2 3 4 4 10 11 12 13 Output 0 Input 5 1 1 1 1 1 3 1 2 3 Output 2
def I(): return(sorted(list(map(int,input().split())))) n=I()[0] b=I() m=I()[0] g=I() i,j,k=[0]*3 while i<n and j<m: if abs(b[i]-g[j])<2:k+=1;i+=1;j+=1 elif b[i]<g[j]:i+=1 else:j+=1 print(k)
{ "input": [ "4\n1 2 3 4\n4\n10 11 12 13\n", "4\n1 4 6 2\n5\n5 1 5 7 9\n", "5\n1 1 1 1 1\n3\n1 2 3\n" ], "output": [ "0\n", "3\n", "2\n" ] }
306
7
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally. Input The first line contains four integers n1, n2, k1, k2. All numbers in the input are from 1 to 50. This problem doesn't have subproblems. You will get 3 points for the correct submission. Output Output "First" if the first player wins and "Second" otherwise. Examples Input 2 2 1 2 Output Second Input 2 1 1 1 Output First Note Consider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.
def mod(): n,m,k,s=list(map(int,input().split(" "))) if n>m: print("First") else: print("Second") mod()
{ "input": [ "2 1 1 1\n", "2 2 1 2\n" ], "output": [ "First\n", "Second\n" ] }
307
8
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 β€” are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers. Input The first line contains a single integer n (1 ≀ n ≀ 106). Output In the first line print a single integer k β€” the minimum number of numbers in the representation of number n as a sum of quasibinary numbers. In the second line print k numbers β€” the elements of the sum. All these numbers should be quasibinary according to the definition above, their sum should equal n. Do not have to print the leading zeroes in the numbers. The order of numbers doesn't matter. If there are multiple possible representations, you are allowed to print any of them. Examples Input 9 Output 9 1 1 1 1 1 1 1 1 1 Input 32 Output 3 10 11 11
def qBinary(n): a = list(str(n)) a = list(map(int,a)) b = [0]*max(a) for i in range(len(a)): j = 0 while(a[i] > 0): b[j] += 10**(len(a)-i-1) j += 1 a[i] -= 1 print(len(b)) for i in b: print(i,end = ' ') n = int(input()) qBinary(n)
{ "input": [ "32\n", "9\n" ], "output": [ "3\n11 11 10\n", "9\n1 1 1 1 1 1 1 1 1\n" ] }
308
11
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem. A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit. More formally, if a game designer selected cells having coordinates (x1, y1) and (x2, y2), where x1 ≀ x2 and y1 ≀ y2, then all cells having center coordinates (x, y) such that x1 ≀ x ≀ x2 and y1 ≀ y ≀ y2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x2 - x1 is divisible by 2. Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map. Help him implement counting of these units before painting. <image> Input The only line of input contains four integers x1, y1, x2, y2 ( - 109 ≀ x1 ≀ x2 ≀ 109, - 109 ≀ y1 ≀ y2 ≀ 109) β€” the coordinates of the centers of two cells. Output Output one integer β€” the number of cells to be filled. Examples Input 1 1 5 5 Output 13
def main(): x1, y1, x2, y2 = map(int, input().split()) print((y2 - y1 + 2) // 2 * (x2 - x1 + 1) - (x2 - x1) // 2) if __name__ == '__main__': main()
{ "input": [ "1 1 5 5\n" ], "output": [ "13" ] }
309
8
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti. Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time. The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them β€” those with biggest ti. Your task is to handle queries of two types: * "1 id" β€” Friend id becomes online. It's guaranteed that he wasn't online before. * "2 id" β€” Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type? Input The first line contains three integers n, k and q (1 ≀ n, q ≀ 150 000, 1 ≀ k ≀ min(6, n)) β€” the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1 ≀ typei ≀ 2, 1 ≀ idi ≀ n) β€” the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty. Output For each query of the second type print one line with the answer β€” "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise. Examples Input 4 2 8 300 950 500 200 1 3 2 4 2 3 1 1 1 2 2 1 2 2 2 3 Output NO YES NO YES YES Input 6 3 9 50 20 51 17 99 24 1 3 1 4 1 5 1 2 2 4 2 2 1 1 2 4 2 3 Output NO YES NO YES Note In the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries: 1. "1 3" β€” Friend 3 becomes online. 2. "2 4" β€” We should check if friend 4 is displayed. He isn't even online and thus we print "NO". 3. "2 3" β€” We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES". 4. "1 1" β€” Friend 1 becomes online. The system now displays both friend 1 and friend 3. 5. "1 2" β€” Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed 6. "2 1" β€” Print "NO". 7. "2 2" β€” Print "YES". 8. "2 3" β€” Print "YES".
def p1(): n,k,q = [int(i) for i in input().split()] l = [int(i) for i in input().split()] s = [] for i in range(q): a,b = [int(i) for i in input().split()] if a == 1: s.append(l[b-1]) s.sort() if len(s) > k: s.remove(s[0]) if a == 2: if l[b-1] in s: print('YES') else: print('NO') p1()
{ "input": [ "6 3 9\n50 20 51 17 99 24\n1 3\n1 4\n1 5\n1 2\n2 4\n2 2\n1 1\n2 4\n2 3\n", "4 2 8\n300 950 500 200\n1 3\n2 4\n2 3\n1 1\n1 2\n2 1\n2 2\n2 3\n" ], "output": [ "NO\nYES\nNO\nYES\n", "NO\nYES\nNO\nYES\nYES\n" ] }
310
10
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3. Limak is going to build a tower. First, he asks you to tell him a positive integer X β€” the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X. Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X. Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≀ m that results this number of blocks. Input The only line of the input contains one integer m (1 ≀ m ≀ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive. Output Print two integers β€” the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks. Examples Input 48 Output 9 42 Input 6 Output 6 6 Note In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42. In more detail, after choosing X = 42 the process of building a tower is: * Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15. * The second added block has side 2, so the remaining volume is 15 - 8 = 7. * Finally, Limak adds 7 blocks with side 1, one by one. So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7Β·13 = 27 + 8 + 7 = 42.
def g(m, n, s): if not m: return n, s k = int(m ** (1 / 3)) x, y = k ** 3, (k - 1) ** 3 return max(g(m - x, n + 1, s + x), g(x - y - 1, n + 1, s + y)) print(*g(int(input()), 0, 0))
{ "input": [ "6\n", "48\n" ], "output": [ "6 6\n", "9 42\n" ] }
311
9
And while Mishka is enjoying her trip... Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend. Once walking with his friend, John gave Chris the following problem: At the infinite horizontal road of width w, bounded by lines y = 0 and y = w, there is a bus moving, presented as a convex polygon of n vertices. The bus moves continuously with a constant speed of v in a straight Ox line in direction of decreasing x coordinates, thus in time only x coordinates of its points are changing. Formally, after time t each of x coordinates of its points will be decreased by vt. There is a pedestrian in the point (0, 0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0, 0) and (0, w) with any speed not exceeding u. Thus the pedestrian can move only in a straight line Oy in any direction with any speed not exceeding u and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly. Please look at the sample note picture for better understanding. We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus). You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0, w) and not to be hit by the bus. Input The first line of the input contains four integers n, w, v, u (3 ≀ n ≀ 10 000, 1 ≀ w ≀ 109, 1 ≀ v, u ≀ 1000) β€” the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively. The next n lines describes polygon vertices in counter-clockwise order. i-th of them contains pair of integers xi and yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ w) β€” coordinates of i-th polygon point. It is guaranteed that the polygon is non-degenerate. Output Print the single real t β€” the time the pedestrian needs to croos the road and not to be hit by the bus. The answer is considered correct if its relative or absolute error doesn't exceed 10 - 6. Example Input 5 5 1 2 1 2 3 1 4 3 3 4 1 4 Output 5.0000000000 Note Following image describes initial position in the first sample case: <image>
import sys input = sys.stdin.readline def solve(): n, w, v, u = map(int, input().split()) mx = int(1e13) Mx = int(-1e13) for i in range(n): x, y = map(int, input().split()) xx = x * u - v * y mx = min(mx, xx) Mx = max(Mx, xx) if mx >= 0 or Mx <= 0: print(w/u) else: print((Mx+w*v)/(v*u)) solve()
{ "input": [ "5 5 1 2\n1 2\n3 1\n4 3\n3 4\n1 4\n" ], "output": [ "5.0000000000\n" ] }
312
9
Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLM NOPQRSTUVWXYZ We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself. A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself). You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print "Impossible" (without the quotes). Input The only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s. Output Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print "Impossible". Examples Input ABCDEFGHIJKLMNOPQRSGTUVWXYZ Output YXWVUTGHIJKLM ZABCDEFSRQPON Input BUVTYZFQSNRIWOXXGJLKACPEMDH Output Impossible
def main(): l, d = [], {} for i, c in enumerate(input()): if c in d: u, v = d[c], i else: d[c] = i l.append(c) if v - u == 1: print("Impossible") return l *= 2 w = (u + v + 1) // 2 print(''.join(l[w:w + 13])) print(''.join(l[w + 25:w + 12:-1])) if __name__ == '__main__': main()
{ "input": [ "BUVTYZFQSNRIWOXXGJLKACPEMDH\n", "ABCDEFGHIJKLMNOPQRSGTUVWXYZ\n" ], "output": [ "Impossible\n", "ABCDEFGHIJKLM\nZYXWVUTSRQPON\n" ] }
313
9
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id β€” integer from 1 to n. It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti β€” the moment in seconds in which the task will come, ki β€” the number of servers needed to perform it, and di β€” the time needed to perform this task in seconds. All ti are distinct. To perform the i-th task you need ki servers which are unoccupied in the second ti. After the servers begin to perform the task, each of them will be busy over the next di seconds. Thus, they will be busy in seconds ti, ti + 1, ..., ti + di - 1. For performing the task, ki servers with the smallest ids will be chosen from all the unoccupied servers. If in the second ti there are not enough unoccupied servers, the task is ignored. Write the program that determines which tasks will be performed and which will be ignored. Input The first line contains two positive integers n and q (1 ≀ n ≀ 100, 1 ≀ q ≀ 105) β€” the number of servers and the number of tasks. Next q lines contains three integers each, the i-th line contains integers ti, ki and di (1 ≀ ti ≀ 106, 1 ≀ ki ≀ n, 1 ≀ di ≀ 1000) β€” the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds. Output Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1. Examples Input 4 3 1 3 2 2 2 1 3 4 3 Output 6 -1 10 Input 3 2 3 2 3 5 1 2 Output 3 3 Input 8 6 1 3 20 4 2 1 6 5 5 10 1 1 15 3 6 21 8 8 Output 6 9 30 -1 15 36 Note In the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10). In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.
import math import sys def solve(n, q): servers = [0] * n res = [None]*q for j, line in enumerate(sys.stdin): t, k, d = map(int, line.split()) S, m = k, k logs = servers[:] for i, s in enumerate(servers): if s <= t: servers[i] = t + d S += i m -= 1 if m == 0: res[j] = S break else: res[j] = -1 servers = logs[:] return res n, q = map(int, input().split()) print('\n'.join(map(str, solve(n, q))))
{ "input": [ "8 6\n1 3 20\n4 2 1\n6 5 5\n10 1 1\n15 3 6\n21 8 8\n", "4 3\n1 3 2\n2 2 1\n3 4 3\n", "3 2\n3 2 3\n5 1 2\n" ], "output": [ "6\n9\n30\n-1\n15\n36\n", "6\n-1\n10\n", "3\n3\n" ] }
314
9
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter. For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows : Initially, the company name is ???. Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}. Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}. Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}. In the end, the company name is oio. Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally? A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s β‰  t) if si < ti where i is the smallest index such that si β‰  ti. (so sj = tj for all j < i) Input The first line of input contains a string s of length n (1 ≀ n ≀ 3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. Output The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. Examples Input tinkoff zscoder Output fzfsirk Input xxxxxx xxxxxx Output xxxxxx Input ioi imo Output ioi Note One way to play optimally in the first sample is as follows : * Initially, the company name is ???????. * Oleg replaces the first question mark with 'f'. The company name becomes f??????. * Igor replaces the second question mark with 'z'. The company name becomes fz?????. * Oleg replaces the third question mark with 'f'. The company name becomes fzf????. * Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. * Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. * Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. * Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk. For the second sample, no matter how they play, the company name will always be xxxxxx.
def main(): from collections import deque import sys input = sys.stdin.readline s = list(input())[:-1] t = list(input())[:-1] n = len(s) s.sort() t.sort(reverse=True) s = deque(s[:(n + 1) // 2]) t = deque(t[:n // 2]) f = 0 al, ar = "", "" for i in range(n): if i % 2: if s and s[0] >= t[0]: f = 1 if f: ar += t.pop() else: al += t.popleft() else: if t and s[0] >= t[0]: f = 1 if f: ar += s.pop() else: al += s.popleft() print(al + ar[::-1]) if __name__ == '__main__': main()
{ "input": [ "xxxxxx\nxxxxxx\n", "tinkoff\nzscoder\n", "ioi\nimo\n" ], "output": [ "xxxxxx\n", "fzfsirk\n", "ioi\n" ] }
315
8
Karen has just arrived at school, and she has a math test today! <image> The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition. Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa. The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test. Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row? Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7. Input The first line of input contains a single integer n (1 ≀ n ≀ 200000), the number of numbers written on the first row. The next line contains n integers. Specifically, the i-th one among these is ai (1 ≀ ai ≀ 109), the i-th number on the first row. Output Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7. Examples Input 5 3 6 9 12 15 Output 36 Input 4 3 7 5 2 Output 1000000006 Note In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15. Karen performs the operations as follows: <image> The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output. In the second test case, the numbers written on the first row are 3, 7, 5 and 2. Karen performs the operations as follows: <image> The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.
from sys import exit n = int(input()) a = [int(i) for i in input().split()] if n == 1: print(a[0]) exit(0) mod = 1000000007 f = [0] * (n + 1) f[0] = 1 for i in range(1, n + 1): f[i] = (f[i-1] * i) % mod def f_pow(a, k): if k == 0: return 1 if k % 2 == 1: return f_pow(a, k - 1) * a % mod else: return f_pow(a * a % mod, k // 2) % mod def c(n, k): d = f[k] * f[n - k] % mod return f[n] * f_pow(d, mod - 2) % mod oper = 1 while not (oper and n % 2 == 0): for i in range(n - 1): a[i] = a[i] + oper * a[i + 1] oper *= -1 n -= 1 oper *= 1 if (n//2 % 2) != 0 else -1 sm1 = 0 sm2 = 0 for i in range(n): if i % 2 == 0: sm1 = (sm1 + c(n // 2 - 1, i // 2) * a[i]) % mod else: sm2 = (sm2 + c(n // 2 - 1, i // 2) * a[i]) % mod print((sm1 + oper * sm2) % mod)
{ "input": [ "4\n3 7 5 2\n", "5\n3 6 9 12 15\n" ], "output": [ "\n1000000006\n", "\n36\n" ] }
316
8
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a Β«goodΒ» subset of edges of the graph or say, that it doesn't exist. Subset is called Β«goodΒ», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≀ n ≀ 3Β·105, n - 1 ≀ m ≀ 3Β·105) β€” number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≀ di ≀ 1) β€” numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) β€” edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k β€” number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
# https://codeforces.com/problemset/problem/840/B # TLE import sys input=sys.stdin.readline n, m = map(int, input().split()) d = list(map(int, input().split())) g={} def push(g, u, v, i): if u not in g: g[u]=[] if v not in g: g[v]=[] g[u].append([v, i+1]) g[v].append([u, i+1]) for i in range(m): u, v = map(int, input().split()) push(g, u-1, v-1, i) def solve(d, g): pos = [] S = 0 for i, x in enumerate(d): if x==-1: pos.append(i) else: S+=x if S%2==1: if len(pos)==0: return False, None d[pos[0]]=1 for x in pos[1:]: d[x]=0 else: for x in pos: d[x]=0 root=0 S = [root] edge = [-1] used = [0]*n used[root]=1 p=[None]*n i=0 while i<len(S): u=S[i] if u in g: for v, edge_ in g[u]: if v==p[u] or used[v]==1: continue p[v]=u used[v]=1 S.append(v) edge.append(edge_) i+=1 ans=[] r=[0]*n for v, edge_ in zip(S[1:][::-1], edge[1:][::-1]): if r[v]^d[v]==1: u=p[v] r[u]=1-r[u] ans.append(str(edge_)) return True, ans flg, ans =solve(d, g) if flg==False: print(-1) else: print(len(ans)) print('\n'.join(ans))
{ "input": [ "3 3\n0 -1 1\n1 2\n2 3\n1 3\n", "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4\n", "1 0\n1\n", "2 1\n1 1\n1 2\n" ], "output": [ "1\n2\n", "0\n", "-1\n", "1\n1\n" ] }
317
9
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website. Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic. Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests. Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only. The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command. Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: * all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples; * all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests. Input The first line contains single integer n (1 ≀ n ≀ 105) β€” the number of files with tests. n lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the i-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct. Output In the first line print the minimum number of lines in Vladimir's script file. After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" β€” is a string of digits and small English letters with length from 1 to 6. Examples Input 5 01 0 2 1 2extra 0 3 1 99 0 Output 4 move 3 1 move 01 5 move 2extra 4 move 99 3 Input 2 1 0 2 1 Output 3 move 1 3 move 2 1 move 3 2 Input 5 1 0 11 1 111 0 1111 1 11111 0 Output 5 move 1 5 move 11 1 move 1111 2 move 111 4 move 11111 3
import random def genTemp(): sl = "" firstTime = True while firstTime or sl in pre or sl in post: sl = "" firstTime = False for i in range(6): sl += chr(random.randint(ord("a"), ord("z"))) return sl n = int(input()) e = 0 pre = set() post = set() for i in range(n): name, tp = input().split() if tp == "1": e += 1 pre.add(name) else: post.add(name) temp = genTemp() preAns = {str(x) for x in range(1, e + 1)} postAns = {str(x) for x in range(e + 1, n + 1)} preMissing = preAns - pre postMissing = postAns - post preToChange = pre - preAns postToChange = post - postAns preFree = preMissing - postToChange postFree = postMissing - preToChange preWrong = preToChange & postMissing postWrong = postToChange & preMissing ans = [] while preToChange or postToChange: if not postFree and not preFree: if preToChange: x = preToChange.pop() preWrong.discard(x) ans.append(("move", x, temp)) preToChange.add(temp) #postMissing.discard(x) if x in postAns: postFree.add(x) else: x = postToChange.pop() ans.append(("move", x, temp)) postWrong.discard(x) postToChange.add(temp) #preMissing.discard(x) if x in postAns: preFree.add(x) elif preFree: if preWrong: x = preWrong.pop() preToChange.discard(x) else: x = preToChange.pop() y = preFree.pop() ans.append(("move", x, y)) preMissing.discard(y) if x in postAns: postFree.add(x) else: if postWrong: x = postWrong.pop() postToChange.discard(x) else: x = postToChange.pop() y = postFree.pop() ans.append(("move", x, y)) postMissing.discard(y) if x in preAns: preFree.add(x) print(len(ans)) for tup in ans: print(*tup)
{ "input": [ "5\n01 0\n2 1\n2extra 0\n3 1\n99 0\n", "2\n1 0\n2 1\n", "5\n1 0\n11 1\n111 0\n1111 1\n11111 0\n" ], "output": [ "4\nmove 3 1\nmove 01 3\nmove 2extra 4\nmove 99 5\n", "3\nmove 1 3\nmove 2 1\nmove 3 2\n", "5\nmove 1 3\nmove 11 1\nmove 111 4\nmove 1111 2\nmove 11111 5\n" ] }
318
8
Absent-minded Masha got set of n cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x. To make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number. The number can't contain leading zeros. It's not required to use all cubes to build a number. Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations. Input In first line integer n is given (1 ≀ n ≀ 3) β€” the number of cubes, Masha got for her birthday. Each of next n lines contains 6 integers aij (0 ≀ aij ≀ 9) β€” number on j-th face of i-th cube. Output Print single integer β€” maximum number x such Masha can make any integers from 1 to x using her cubes or 0 if Masha can't make even 1. Examples Input 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 Output 87 Input 3 0 1 3 5 6 8 1 2 4 5 7 8 2 3 4 6 7 9 Output 98 Note In the first test case, Masha can build all numbers from 1 to 87, but she can't make 88 because there are no two cubes with digit 8.
n=int(input()) def find(x,d=[]): if x==0 and d!=[]: return True l=x%10 i=-1 a=False for lis in s: i+=1 if l in lis and i not in d: a=max(a,find(x//10,d+[i])) return a s=[list(map(int,input().split())) for x in range(n)] e=1 while find(e): e+=1 print(int(e-1 if find(1) else 0))
{ "input": [ "3\n0 1 3 5 6 8\n1 2 4 5 7 8\n2 3 4 6 7 9\n", "3\n0 1 2 3 4 5\n6 7 8 9 0 1\n2 3 4 5 6 7\n" ], "output": [ "98\n", "87\n" ] }
319
8
An African crossword is a rectangular table n Γ— m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded. To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously. When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem. You are suggested to solve an African crossword and print the word encrypted there. Input The first line contains two integers n and m (1 ≀ n, m ≀ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid. Output Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter. Examples Input 3 3 cba bcd cbc Output abcd Input 5 5 fcofd ooedo afaoa rdcdf eofsf Output codeforces
def column(matrix, i): return [row[i] for row in matrix] n, m = map(int, input().split()) mat = [] for _ in range(n): mat.append([char for char in input()]) ans = "" # print(mat) for i in range(n): for j in range(m): # print(mat[:][j], mat[:][j].count(mat[i][j])) if mat[i][:].count(mat[i][j])>1 or column(mat, j).count(mat[i][j])>1: pass else: ans+=mat[i][j] # print(i, j, mat[i][j]) print(ans)
{ "input": [ "3 3\ncba\nbcd\ncbc\n", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf\n" ], "output": [ "abcd\n", "codeforces\n" ] }
320
11
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers β€” saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that: * Each pencil belongs to exactly one box; * Each non-empty box has at least k pencils in it; * If pencils i and j belong to the same box, then |ai - aj| ≀ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| ≀ d and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO". Input The first line contains three integer numbers n, k and d (1 ≀ k ≀ n ≀ 5Β·105, 0 ≀ d ≀ 109) β€” the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” saturation of color of each pencil. Output Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO". Examples Input 6 3 10 7 2 7 7 4 2 Output YES Input 6 2 3 4 5 3 13 4 10 Output YES Input 3 2 5 10 16 22 Output NO Note In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10. In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.
def main(): import sys from bisect import bisect_left input = sys.stdin.readline N, K, D = map(int, input().split()) A = list(map(int, input().split())) A.sort() part = [0] * (N+2) part[0] = 1 part[1] = -1 for i, a in enumerate(A): part[i] += part[i-1] if part[i]: j = bisect_left(A, a+D+1) if j >= i+K: part[i+K] += 1 part[j+1] -= 1 part[N] += part[N-1] if part[N]: print('YES') else: print('NO') #print(A) #print(part) if __name__ == '__main__': main()
{ "input": [ "6 3 10\n7 2 7 7 4 2\n", "3 2 5\n10 16 22\n", "6 2 3\n4 5 3 13 4 10\n" ], "output": [ "YES\n", "NO\n", "YES\n" ] }
321
9
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every k ∈ [1..n], calculate the number of points with integer coordinates such that the number of segments that cover these points equals k. A segment with endpoints l_i and r_i covers point x if and only if l_i ≀ x ≀ r_i. Input The first line of the input contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. The next n lines contain segments. The i-th line contains a pair of integers l_i, r_i (0 ≀ l_i ≀ r_i ≀ 10^{18}) β€” the endpoints of the i-th segment. Output Print n space separated integers cnt_1, cnt_2, ..., cnt_n, where cnt_i is equal to the number of points such that the number of segments that cover these points equals to i. Examples Input 3 0 3 1 3 3 8 Output 6 2 1 Input 3 1 3 2 4 5 7 Output 5 2 0 Note The picture describing the first example: <image> Points with coordinates [0, 4, 5, 6, 7, 8] are covered by one segment, points [1, 2] are covered by two segments and point [3] is covered by three segments. The picture describing the second example: <image> Points [1, 4, 5, 6, 7] are covered by one segment, points [2, 3] are covered by two segments and there are no points covered by three segments.
def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) from collections import Counter n = ii() a1 = [tuple(mi()) for i in range(n)] a = [] for l, r in a1: a.append((l, 0)) a.append((r, 1)) c = Counter(a) b = [(k[0], k[1], v) for k, v in c.items()] b.sort() ans = [0] * (n + 1) p = -1 cnt = 0 for x, y, z in b: if y == 0: ans[cnt] += x - p - 1 cnt += z ans[cnt] += 1 else: if x != p: ans[cnt] += x - p cnt -= z p = x print(*ans[1:])
{ "input": [ "3\n0 3\n1 3\n3 8\n", "3\n1 3\n2 4\n5 7\n" ], "output": [ "6 2 1\n", "5 2 0\n" ] }
322
10
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees! Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset. To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed 1. Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found [here.](https://en.wikipedia.org/wiki/Binary_search_tree) Input The first line contains the number of vertices n (2 ≀ n ≀ 700). The second line features n distinct integers a_i (2 ≀ a_i ≀ 10^9) β€” the values of vertices in ascending order. Output If it is possible to reassemble the binary search tree, such that the greatest common divisor of any two vertices connected by the edge is greater than 1, print "Yes" (quotes for clarity). Otherwise, print "No" (quotes for clarity). Examples Input 6 3 6 9 18 36 108 Output Yes Input 2 7 17 Output No Input 9 4 8 10 12 15 18 33 44 81 Output Yes Note The picture below illustrates one of the possible trees for the first example. <image> The picture below illustrates one of the possible trees for the third example. <image>
from math import gcd import random,time,sys input=sys.stdin.buffer.readline def main(): n=int(input()) a=list(map(int,input().split())) #a=[2*random.randint(1,10**9) for i in range(n)] start=time.time() a+=[0] GCD=[0 for i in range(n+1)] for i in range(n+1): for j in range(n+1): if gcd(a[i],a[j])>1: GCD[i]+=1<<j check1=[1<<j for j in range(n+1)] check2=[1<<j for j in range(n+1)] for i in range(n): check1[0]|=int(bool(check1[0]&check2[i]&GCD[i+1]))*(1<<(i+1)) for j in range(1,n-i): check1[j]|=int(bool(check1[j]&check2[i+j]&GCD[j+i+1]))*(1<<(i+j+1)) check2[j+i]|=int(bool(check1[j]&check2[i+j]&GCD[j-1]))*(1<<(j-1)) ans=bool(check1[0]&check2[n-1]) print("Yes" if ans else "No") #print(time.time()-start) if __name__=="__main__": main()
{ "input": [ "9\n4 8 10 12 15 18 33 44 81\n", "6\n3 6 9 18 36 108\n", "2\n7 17\n" ], "output": [ "Yes\n", "Yes\n", "No\n" ] }
323
12
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed. Ivan asked you to find initial placement of exactly n knights such that in the end there will be at least ⌊ \frac{n^{2}}{10} βŒ‹ knights. Input The only line of input contains one integer n (1 ≀ n ≀ 10^{3}) β€” number of knights in the initial placement. Output Print n lines. Each line should contain 2 numbers x_{i} and y_{i} (-10^{9} ≀ x_{i}, y_{i} ≀ 10^{9}) β€” coordinates of i-th knight. For all i β‰  j, (x_{i}, y_{i}) β‰  (x_{j}, y_{j}) should hold. In other words, all knights should be in different cells. It is guaranteed that the solution exists. Examples Input 4 Output 1 1 3 1 1 5 4 4 Input 7 Output 2 1 1 2 4 1 5 2 2 6 5 7 6 6 Note Let's look at second example: <image> Green zeroes are initial knights. Cell (3, 3) is under attack of 4 knights in cells (1, 2), (2, 1), (4, 1) and (5, 2), therefore Ivan will place a knight in this cell. Cell (4, 5) is initially attacked by only 3 knights in cells (2, 6), (5, 7) and (6, 6). But new knight in cell (3, 3) also attacks cell (4, 5), now it is attacked by 4 knights and Ivan will place another knight in this cell. There are no more free cells which are attacked by 4 or more knights, so the process stops. There are 9 knights in the end, which is not less than ⌊ \frac{7^{2}}{10} βŒ‹ = 4.
gcd = lambda a, b: gcd(b, a % b) if b else a def main(): n = int(input()) if n == 1: print(0, 0) return x = 2 * n // 3 if 2 * n % 2: x += 1 s = 0 for i in range(x): print(i, 0) s += 1 for j in range(1, x, 2): print(j, 3) s += 1 while n - s: s += 1 i += 1 print(i, 0) main()
{ "input": [ "7\n", "4\n" ], "output": [ "0 0\n1 0\n1 3\n2 0\n3 0\n3 3\n4 0\n", "0 0\n1 0\n1 3\n2 0\n" ] }
324
8
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: * b: 2 * c: 3, 10 * d: 4, 8 * e: 6 * f: 7 * z: 1, 5, 9 * Lists of positions of letters a, g, h, ..., y are empty. This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky. Find the lexicographically minimal lucky string whose length equals n. Input The single line contains a positive integer n (1 ≀ n ≀ 105) β€” the length of the sought string. Output Print on the single line the lexicographically minimal lucky string whose length equals n. Examples Input 5 Output abcda Input 3 Output abc Note The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj.
def main(): n = int(input()) s = ['a', 'b', 'c', 'd'] * n return ''.join(s)[:n] print(main())
{ "input": [ "3\n", "5\n" ], "output": [ "abc", "abcda" ] }
325
11
There are n students and m clubs in a college. The clubs are numbered from 1 to m. Each student has a potential p_i and is a member of the club with index c_i. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next d days. There is a coding competition every day in the technical fest. Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming d days. Thus, every day the director chooses such team, that the team strength is maximized. The mex of the multiset S is the smallest non-negative integer that is not present in S. For example, the mex of the \{0, 1, 1, 2, 4, 5, 9\} is 3, the mex of \{1, 2, 3\} is 0 and the mex of βˆ… (empty set) is 0. Input The first line contains two integers n and m (1 ≀ m ≀ n ≀ 5000), the number of students and the number of clubs in college. The second line contains n integers p_1, p_2, …, p_n (0 ≀ p_i < 5000), where p_i is the potential of the i-th student. The third line contains n integers c_1, c_2, …, c_n (1 ≀ c_i ≀ m), which means that i-th student is initially a member of the club with index c_i. The fourth line contains an integer d (1 ≀ d ≀ n), number of days for which the director wants to know the maximum possible strength of the team. Each of the next d lines contains an integer k_i (1 ≀ k_i ≀ n), which means that k_i-th student lefts their club on the i-th day. It is guaranteed, that the k_i-th student has not left their club earlier. Output For each of the d days, print the maximum possible strength of the team on that day. Examples Input 5 3 0 1 2 2 0 1 2 2 3 2 5 3 2 4 5 1 Output 3 1 1 1 0 Input 5 3 0 1 2 2 1 1 3 2 3 2 5 4 2 3 5 1 Output 3 2 2 1 0 Input 5 5 0 1 2 4 5 1 2 3 4 5 4 2 3 5 4 Output 1 1 1 1 Note Consider the first example: On the first day, student 3 leaves their club. Now, the remaining students are 1, 2, 4 and 5. We can select students 1, 2 and 4 to get maximum possible strength, which is 3. Note, that we can't select students 1, 2 and 5, as students 2 and 5 belong to the same club. Also, we can't select students 1, 3 and 4, since student 3 has left their club. On the second day, student 2 leaves their club. Now, the remaining students are 1, 4 and 5. We can select students 1, 4 and 5 to get maximum possible strength, which is 1. On the third day, the remaining students are 1 and 5. We can select students 1 and 5 to get maximum possible strength, which is 1. On the fourth day, the remaining student is 1. We can select student 1 to get maximum possible strength, which is 1. On the fifth day, no club has students and so the maximum possible strength is 0.
n, m = map(int, input().split()) p = list(map(int, input().split())) c = list(map(int, input().split())) d = int(input()) k = [] for i in range(d): k.append(int(input())) vis = [False for i in range(m+1)] match = [-1 for i in range(m+1)] def dfs(u: int) -> bool: for v in e[u]: if not vis[v]: vis[v] = True if match[v] == -1 or dfs(match[v]): match[v] = u return True return False e = [[] for i in range(5005)] for i in range(n): if i + 1 not in k: e[p[i]].append(c[i]) mex = 0 ans = [] for i in range(d - 1, -1, -1): while True: vis = [False for j in range(m+1)] if not dfs(mex): break mex += 1 ans.append(mex) e[p[k[i]-1]].append(c[k[i]-1]) for i in reversed(ans): print(i)
{ "input": [ "5 5\n0 1 2 4 5\n1 2 3 4 5\n4\n2\n3\n5\n4\n", "5 3\n0 1 2 2 0\n1 2 2 3 2\n5\n3\n2\n4\n5\n1\n", "5 3\n0 1 2 2 1\n1 3 2 3 2\n5\n4\n2\n3\n5\n1\n" ], "output": [ "1\n1\n1\n1\n", "3\n1\n1\n1\n0\n", "3\n2\n2\n1\n0\n" ] }
326
11
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1. You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y. Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c. Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≀ i ≀ n), that x_i < y_i, and for any j (1 ≀ j < i) x_j = y_j. Input The first line of the input contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in a, b and c. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≀ a_i < n), where a_i is the i-th element of a. The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≀ b_i < n), where b_i is the i-th element of b. Output Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n. Examples Input 4 0 1 2 1 3 2 1 1 Output 1 0 0 2 Input 7 2 5 1 5 3 4 3 2 4 3 5 6 5 1 Output 0 0 0 1 0 2 4
import collections def solve(n, a, b): c = collections.Counter(b) nex = list(range(1, n)) + [0] res = [] for x in a: v = (n - x) % n while c[v] == 0: if c[nex[v]] == 0: nex[v] = nex[nex[v]] v = nex[v] c[v] -= 1 res.append((x + v) % n) return ' '.join(map(str, res)) n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(n, a, b))
{ "input": [ "4\n0 1 2 1\n3 2 1 1\n", "7\n2 5 1 5 3 4 3\n2 4 3 5 6 5 1\n" ], "output": [ "1 0 0 2 ", "0 0 0 1 0 2 4 " ] }
327
8
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representing a number that does not exceed b. Here a and b are some given constants, s1 and s2 are chosen by the players. The strings are allowed to contain leading zeroes. If a number obtained by the concatenation (joining together) of strings s1 and s2 is divisible by mod, then the second player wins. Otherwise the first player wins. You are given numbers a, b, mod. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move. Input The first line contains three integers a, b, mod (0 ≀ a, b ≀ 109, 1 ≀ mod ≀ 107). Output If the first player wins, print "1" and the lexicographically minimum string s1 he has to write to win. If the second player wins, print the single number "2". Examples Input 1 10 7 Output 2 Input 4 0 9 Output 1 000000001 Note The lexical comparison of strings is performed by the < operator in modern programming languages. String x is lexicographically less than string y if exists such i (1 ≀ i ≀ 9), that xi < yi, and for any j (1 ≀ j < i) xj = yj. These strings always have length 9.
import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) a,b,mod = mints() z = (10**9)%mod c = 0 for i in range(min(a+1,mod)): if c != 0 and mod-c > b: s = str(i) s = '0'*(9-len(s))+s print(1, s) exit(0) c += z if c >= mod: c -= mod print(2)
{ "input": [ "4 0 9\n", "1 10 7\n" ], "output": [ "1 000000001\n", "2\n" ] }
328
9
You are given a graph with 3 β‹… n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T β‰₯ 1 β€” the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 β‹… n is the number of vertices, and m is the number of edges in the graph (1 ≀ n ≀ 10^{5}, 0 ≀ m ≀ 5 β‹… 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ 3 β‹… n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 β‹… 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers β€” the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers β€” the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
from sys import stdin input = stdin.readline def solve_graph(): n,m = map(int, input().split()) included = [False] + ([True]*(3*n)) matching =[] for i in range(1,m+1): e1, e2 = map(int, input().split()) if included[e1] and included[e2]: matching.append(i) included[e1] = False included[e2] = False if len(matching) >= n: print("Matching") print(*matching[:n]) return intset = [x for (x,b) in enumerate(included) if b] print("IndSet") print(*(list(intset)[:n])) t = int(input()) for _ in range(t): solve_graph()
{ "input": [ "4\n1 2\n1 3\n1 2\n1 2\n1 3\n1 2\n2 5\n1 2\n3 1\n1 4\n5 1\n1 6\n2 15\n1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 5\n4 6\n5 6\n" ], "output": [ "Matching\n1 \nMatching\n1 \nIndSet\n3 4 \nMatching\n1 10 \n" ] }
329
8
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i β‰  0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≀ r) such that a_l β‹… a_{l + 1} ... a_{r - 1} β‹… a_r is negative; 2. the number of pairs of indices (l, r) (l ≀ r) such that a_l β‹… a_{l + 1} ... a_{r - 1} β‹… a_r is positive; Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^{5}) β€” the number of elements in the sequence. The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}; a_i β‰  0) β€” the elements of the sequence. Output Print two integers β€” the number of subsegments with negative product and the number of subsegments with positive product, respectively. Examples Input 5 5 -3 3 -1 1 Output 8 7 Input 10 4 2 -4 3 1 2 -4 3 2 3 Output 28 27 Input 5 -1 -2 -3 -4 -5 Output 9 6
n = int(input()) def m(x): return -1 if int(x) < 0 else 1 l = list(map(m, input().split())) pos = 1 neg = 0 t = 1 for x in l: t *= x if t < 0: neg += 1 else: pos += 1 print(neg * pos, neg * (neg - 1) // 2 + (pos * (pos - 1) // 2))
{ "input": [ "10\n4 2 -4 3 1 2 -4 3 2 3\n", "5\n-1 -2 -3 -4 -5\n", "5\n5 -3 3 -1 1\n" ], "output": [ "28 27\n", "9 6\n", "8 7\n" ] }
330
10
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1. A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not. Here are some examples of good strings: * t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5); * t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4); * t = AAAAA (all letters belong to palindrome t_1 ... t_5); You are given a string s of length n, consisting of only letters A and B. You have to calculate the number of good substrings of string s. Input The first line contains one integer n (1 ≀ n ≀ 3 β‹… 10^5) β€” the length of the string s. The second line contains the string s, consisting of letters A and B. Output Print one integer β€” the number of good substrings of string s. Examples Input 5 AABBB Output 6 Input 3 AAA Output 3 Input 7 AAABABB Output 15 Note In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5. In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
def comp(a): if a=="A": return "B" else: return "A" n=int(input()) s=input() ans=(n*(n-1))//2 groups=[0] prev=s[0] for i in range(1,n): if s[i]!=prev: groups.append(i) prev=s[i] for i in range(0,len(groups)-2): ans -= (groups[i+2]-groups[i]-1) if len(groups)>1: ans -= (n-groups[-2]-1) print (ans)
{ "input": [ "5\nAABBB\n", "3\nAAA\n", "7\nAAABABB\n" ], "output": [ "6\n", "3\n", "15\n" ] }
331
11
There are n students at your university. The programming skill of the i-th student is a_i. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has 2 β‹… 10^5 students ready for the finals! Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of k students with programming skills a[i_1], a[i_2], ..., a[i_k], then the diversity of this team is max_{j=1}^{k} a[i_j] - min_{j=1}^{k} a[i_j]). The total diversity is the sum of diversities of all teams formed. Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. Input The first line of the input contains one integer n (3 ≀ n ≀ 2 β‹… 10^5) β€” the number of students. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9), where a_i is the programming skill of the i-th student. Output In the first line print two integers res and k β€” the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print n integers t_1, t_2, ..., t_n (1 ≀ t_i ≀ k), where t_i is the number of team to which the i-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. Examples Input 5 1 1 3 4 2 Output 3 1 1 1 1 1 1 Input 6 1 5 12 13 2 15 Output 7 2 2 2 1 1 2 1 Input 10 1 2 5 129 185 581 1041 1909 1580 8150 Output 7486 3 3 3 3 2 2 2 2 1 1 1 Note In the first example, there is only one team with skills [1, 1, 2, 3, 4] so the answer is 3. It can be shown that you cannot achieve a better answer. In the second example, there are two teams with skills [1, 2, 5] and [12, 13, 15] so the answer is 4 + 3 = 7. In the third example, there are three teams with skills [1, 2, 5], [129, 185, 581, 1041] and [1580, 1909, 8150] so the answer is 4 + 912 + 6570 = 7486.
import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int,minp().split()) def solve(): n = mint() a = [0]*n b = [0]*n j = 0 for i in mints(): a[j] = (i, j) j += 1 a.sort() dp = [(2000000005,0)]*(n+1) dp[3] = (a[2][0] - a[0][0], 3) if n > 3: dp[4] = (a[3][0] - a[0][0], 4) if n > 4: dp[5] = (a[4][0] - a[0][0], 5) for i in range(6,n+1): dp[i] = min(dp[i], (dp[i-3][0]+a[i-1][0] - a[i-3][0], 3)) dp[i] = min(dp[i], (dp[i-4][0]+a[i-1][0] - a[i-4][0], 4)) dp[i] = min(dp[i], (dp[i-5][0]+a[i-1][0] - a[i-5][0], 5)) m = n ans = [0]*n z = 0 while m != 0: r = dp[m] #print(r) z += 1 for i in range(m-r[1], m): ans[a[i][1]] = z m -= r[1] print(dp[n][0], z) print(*ans) solve()
{ "input": [ "5\n1 1 3 4 2\n", "6\n1 5 12 13 2 15\n", "10\n1 2 5 129 185 581 1041 1909 1580 8150\n" ], "output": [ "3 1\n1 1 1 1 1 ", "7 2\n2 2 1 1 2 1\n", "7486 3\n3 3 3 2 2 2 2 1 1 1\n" ] }
332
11
Calculate the number of ways to place n rooks on n Γ— n chessboard so that both following conditions are met: * each empty cell is under attack; * exactly k pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture: <image> One of the ways to place the rooks for n = 3 and k = 2 Two ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way. The answer might be large, so print it modulo 998244353. Input The only line of the input contains two integers n and k (1 ≀ n ≀ 200000; 0 ≀ k ≀ (n(n - 1))/(2)). Output Print one integer β€” the number of ways to place the rooks, taken modulo 998244353. Examples Input 3 2 Output 6 Input 3 3 Output 0 Input 4 0 Output 24 Input 1337 42 Output 807905441
n,k=map(int,input().split()) if k>=n:print(0) else: m=998244353 L=[1] for i in range(1,n+1): L.append((L[-1]*i)%m) def comb(n,k): return (L[n]*pow((L[n-k]*L[k]),m-2,m))%m c=0 for i in range(n-k): c+=((-1)**i*pow(n-k-i,n,m)*comb(n-k,n-k-i))%m c*=2 c%=m c*=comb(n,n-k) c%=m if k==0:print(L[n]) else:print(c)
{ "input": [ "4 0\n", "3 2\n", "1337 42\n", "3 3\n" ], "output": [ "24\n", "6\n", "807905441\n", "0\n" ] }
333
9
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≀ t≀ 10^4) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≀ n≀ 10^5) β€” the number of vertices. Each of the next n-1 lines contains two integers x, y (1≀ x,y≀ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≀ x_1, y_1 ≀ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≀ x_2, y_2 ≀ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n = mint() e = [[] for i in range(n+1)] for i in range(n-1): x, y = mints() e[x].append(y) e[y].append(x) q = [None]*(n+1) d = [None]*(n+1) q[0] = (1,-1) qr = 1 ql = 0 while ql < qr: x, p = q[ql] ql += 1 for v in e[x]: if v != p: q[qr] = (v, x) qr += 1 cen = None best_com = int(1e9) for i in range(qr-1, -1, -1): x, p = q[i] c = 1 com = 0 for v in e[x]: if v != p: c += d[v] com = max(com, d[v]) com = max(com, n-c) d[x] = c if com < best_com: best_com = com cen = [(x,p)] elif com == best_com: cen.append((x,p)) if len(cen) == 1: print(1, e[1][0]) print(1, e[1][0]) else: x, p = cen[0] x1, p1 = cen[1] for v in e[x1]: if x != v: print(x1, v) print(x, v) return for i in range(mint()): solve()
{ "input": [ "2\n5\n1 2\n1 3\n2 4\n2 5\n6\n1 2\n1 3\n1 4\n2 5\n2 6\n" ], "output": [ "1 2\n1 2\n2 5\n1 5\n" ] }
334
10
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation. * Choose 2 ≀ k ≀ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation. You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations. Examples of operation: The following are three examples of valid operations (on three decks with different sizes). * If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6]. * If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3]. * If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1]. Input The first line of the input contains one integer n (1≀ n≀ 52) β€” the number of cards in the deck. The second line contains n integers c_1, c_2, ..., c_n β€” the cards in the deck. The first card is c_1, the second is c_2 and so on. It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i. Output On the first line, print the number q of operations you perform (it must hold 0≀ q≀ n). Then, print q lines, each describing one operation. To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|. It must hold 2≀ k≀ n, and |D_i|β‰₯ 1 for all i=1,...,k, and |D_1|+|D_2|+β‹…β‹…β‹… + |D_k| = n. It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them. Examples Input 4 3 1 2 4 Output 2 3 1 2 1 2 1 3 Input 6 6 5 4 3 2 1 Output 1 6 1 1 1 1 1 1 Input 1 1 Output 0 Note Explanation of the first testcase: Initially the deck is [3 1 2 4]. * The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3]. * The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4]. Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1]. * The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6].
n = int(input()) def sf(a, d): s = [0] for di in d: s.append(s[-1] + di) rv = [] for i in range(len(d) - 1, -1, -1): rv += a[s[i]:s[i+1]] return rv c = list(map(int, input().split())) ans = [] while True: for i in range(n): if c[i] != i+1: break else: break for k in range(i, n): if c[k] + 1 != c[k+1]: break s = c[i] for j in range(k+1, n): if c[j] == s-1: break t = [i, k - i + 1, j - k, n - (i + k - i + 1 + j - k)] t = list(filter(lambda x: x != 0, t)) ans.append(t) c = sf(c, ans[-1]) #print(ans[-1]) #print(c) print(len(ans)) for a in ans: print(len(a), *a)
{ "input": [ "1\n1\n", "6\n6 5 4 3 2 1\n", "4\n3 1 2 4\n" ], "output": [ "0\n", "4\n3 1 1 4\n3 1 1 4\n3 1 1 4\n3 2 2 2\n", "2\n3 1 2 1\n2 1 3\n" ] }
335
10
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs. The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a. More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≀ i≀ j+k-1}a_i$$$ For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2]. A permutation of length m is an array consisting of m distinct integers from 1 to m 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 (m=3 but there is 4 in the array). A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≀ k≀ n if CodeCook users will be happy after a k-compression of this array or not. Input The first line contains a single integer t (1≀ t≀ 10^4) β€” the number of test cases. The first line of the description of each test case contains a single integer n (1≀ n≀ 3β‹… 10^5) β€” the length of the array. The second line of the description of each test case contains n integers a_1,…,a_n (1≀ a_i≀ n) β€” the elements of the array. It is guaranteed, that the sum of n for all test cases does not exceed 3β‹… 10^5. Output For each test case, print a binary string of length n. The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise. Example Input 5 5 1 5 3 4 2 4 1 3 2 1 5 1 3 3 3 2 10 1 2 3 4 5 6 7 8 9 10 3 3 3 2 Output 10111 0001 00111 1111111111 000 Note In the first test case, a=[1, 5, 3, 4, 2]. * The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation. * The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice. * The 3-compression of a is [1, 3, 2] and it is a permutation. * The 4-compression of a is [1, 2] and it is a permutation. * The 5-compression of a is [1] and it is a permutation.
from sys import stdin input=stdin.readline def rating(arr): arr=list(map(lambda s:s-1,lst)) cnt=[0]*len(arr) ans=[0]*len(arr) for i in arr: cnt[i]+=1 ans[0] = 0 if cnt.count(0) > 0 else 1 ans[-1] = int(cnt[0] > 0) l=0 r=len(arr)-1 for i in range(1,len(arr)): j=i-1 if cnt[j]==1 and cnt[i]: if arr[l]==j : l+=1 elif arr[r]==j: r-=1 else: break ans[len(arr)-i-1]=1 else: break return "".join(list(map(str,ans))) for i in range(int(input())): a=input() lst=list(map(int,input().strip().split())) print(rating(lst))
{ "input": [ "5\n5\n1 5 3 4 2\n4\n1 3 2 1\n5\n1 3 3 3 2\n10\n1 2 3 4 5 6 7 8 9 10\n3\n3 3 2\n" ], "output": [ "\n10111\n0001\n00111\n1111111111\n000\n" ] }
336
8
Positive integer x is called divisor of positive integer y, if y is divisible by x without remainder. For example, 1 is a divisor of 7 and 3 is not divisor of 8. We gave you an integer d and asked you to find the smallest positive integer a, such that * a has at least 4 divisors; * difference between any two divisors of a is at least d. Input The first line contains a single integer t (1 ≀ t ≀ 3000) β€” the number of test cases. The first line of each test case contains a single integer d (1 ≀ d ≀ 10000). Output For each test case print one integer a β€” the answer for this test case. Example Input 2 1 2 Output 6 15 Note In the first test case, integer 6 have following divisors: [1, 2, 3, 6]. There are 4 of them and the difference between any two of them is at least 1. There is no smaller integer with at least 4 divisors. In the second test case, integer 15 have following divisors: [1, 3, 5, 15]. There are 4 of them and the difference between any two of them is at least 2. The answer 12 is INVALID because divisors are [1, 2, 3, 4, 6, 12]. And the difference between, for example, divisors 2 and 3 is less than d=2.
def isprime(n): for i in range(2,int(n**0.5//1)+1): if(n%i==0): return 0 return 1 t=int(input()) for i in range(t): d=int(input()) a=d+1 while(not isprime(a)): a+=1 b=a+d while(not isprime(b)): b=b+1 print(a*b)
{ "input": [ "2\n1\n2\n" ], "output": [ "\n6\n15\n" ] }
337
10
<image> William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others. For each William's friend i it is known whether he likes currency j. There are m currencies in total. It is also known that a trader may not like more than p currencies. Because friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least ⌈ n/2 βŒ‰ friends (rounded up) who like each currency in this subset. Input The first line contains three integers n, m and p (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ p ≀ m ≀ 60, 1 ≀ p ≀ 15), which is the number of trader friends, the number of currencies, the maximum number of currencies each friend can like. Each of the next n lines contain m characters. The j-th character of i-th line is 1 if friend i likes the currency j and 0 otherwise. It is guaranteed that the number of ones in each line does not exceed p. Output Print a string of length m, which defines the subset of currencies of the maximum size, which are liked by at least half of all friends. Currencies belonging to this subset must be signified by the character 1. If there are multiple answers, print any. Examples Input 3 4 3 1000 0110 1001 Output 1000 Input 5 5 4 11001 10101 10010 01110 11011 Output 10001 Note In the first sample test case only the first currency is liked by at least ⌈ 3/2 βŒ‰ = 2 friends, therefore it's easy to demonstrate that a better answer cannot be found. In the second sample test case the answer includes 2 currencies and will be liked by friends 1, 2, and 5. For this test case there are other currencies that are liked by at least half of the friends, but using them we cannot achieve a larger subset size.
import random import sys from sys import stdin def popcnt(x): ret = 0 while x > 0: ret += x % 2 x //= 2 return ret n,m,p = map(int,stdin.readline().split()) s = [stdin.readline()[:-1] for i in range(n)] ans = 0 anslis = ["0"] * m for loop in range(8): v = random.randint(0,n-1) vbits = [] for i in range(m): if s[v][i] == "1": vbits.append(i) dp = [0] * (2**len(vbits)) vbits.reverse() for i in range(n): now = 0 for j in vbits: now *= 2 if s[i][j] == "1": now += 1 dp[now] += 1 vbits.reverse() #print (v,dp) for j in range(len(vbits)): for i in range(len(dp)): if i & 2**j == 0: dp[i] += dp[i | 2**j] #print (v,dp) for i in range(len(dp)): if dp[i] >= (n+1)//2: pc = popcnt(i) if ans < pc: #print ("change!") ans = pc anslis = [0] * m for j in range(len(vbits)): if 2**j & i > 0: anslis[vbits[j]] = 1 print ("".join(map(str,anslis)))
{ "input": [ "3 4 3\n1000\n0110\n1001\n", "5 5 4\n11001\n10101\n10010\n01110\n11011\n" ], "output": [ "\n1000\n", "\n10001\n" ] }
338
9
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair. Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa". Input The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair. Output Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters. Examples Input ababa 1 ab Output 2 Input codeforces 2 do cs Output 1 Note In the first sample you should remove two letters b. In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
def f(a,bad): i=0 retain=0 while i<len(a): c={} while i<len(a)-1 and (a[i+1]==a[i]or a[i+1]==bad.get(a[i],None)): c[a[i]]=c.get(a[i],0)+1 i+=1 c[a[i]] = c.get(a[i], 0) + 1 retain+=max(c.items(),key=lambda s:s[1])[1] i+=1 return len(a)-retain a=list(input()) n=int(input()) bad={} for i in range(n): l=list(input()) bad[l[0]]=l[1] bad[l[1]]=l[0] print(f(a,bad))
{ "input": [ "ababa\n1\nab\n", "codeforces\n2\ndo\ncs\n" ], "output": [ "2", "1\n" ] }
339
10
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help. A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≀ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c. Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps. Help the Beaver to write a program that will encrypt messages in the described manner. Input The first input line contains three integers n, m and c, separated by single spaces. The second input line contains n integers ai (0 ≀ ai < c), separated by single spaces β€” the original message. The third input line contains m integers bi (0 ≀ bi < c), separated by single spaces β€” the encryption key. The input limitations for getting 30 points are: * 1 ≀ m ≀ n ≀ 103 * 1 ≀ c ≀ 103 The input limitations for getting 100 points are: * 1 ≀ m ≀ n ≀ 105 * 1 ≀ c ≀ 103 Output Print n space-separated integers β€” the result of encrypting the original message. Examples Input 4 3 2 1 1 1 1 1 1 1 Output 0 1 1 0 Input 3 1 5 1 2 3 4 Output 0 1 2 Note In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
def solve(n , m , c , a , b): for i in range(n - m + 1): for j in range(m): a[i + j] = (a[i+j]+b[j])%c a = map(str , a) return " ".join(a) n , m , c = map(int , input().split()) a = list(map(int , input().split())) b = list(map(int , input().split())) print(solve(n , m , c , a , b))
{ "input": [ "3 1 5\n1 2 3\n4\n", "4 3 2\n1 1 1 1\n1 1 1\n" ], "output": [ "0 1 2 \n", "0 1 1 0 \n" ] }
340
12
You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format. The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description). Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m. Input The first line of the input contains two space-separated integers n and m (1 ≀ n, m ≀ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5Β·106 (in particular, this means that the length of some line does not exceed 5Β·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty. Output If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) β€” the first moment of time when the number of warnings for the last n seconds got no less than m. Examples Input 60 3 2012-03-16 16:15:25: Disk size is 2012-03-16 16:15:25: Network failute 2012-03-16 16:16:29: Cant write varlog 2012-03-16 16:16:42: Unable to start process 2012-03-16 16:16:43: Disk size is too small 2012-03-16 16:16:53: Timeout detected Output 2012-03-16 16:16:43 Input 1 2 2012-03-16 23:59:59:Disk size 2012-03-17 00:00:00: Network 2012-03-17 00:00:01:Cant write varlog Output -1 Input 2 2 2012-03-16 23:59:59:Disk size is too sm 2012-03-17 00:00:00:Network failute dete 2012-03-17 00:00:01:Cant write varlogmysq Output 2012-03-17 00:00:00
import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisect from datetime import datetime def main(): n, m = map(int, input().split()) n -= 1 timestamps = [] while True: s = "" try: s = input() except: print(-1) exit(0) d = datetime.strptime(s[0:19], "%Y-%m-%d %H:%M:%S") timestamps.append(int(d.timestamp())) idx = bisect.bisect_left(timestamps, timestamps[-1] - n) if len(timestamps) - idx == m: print(s[0:19]) exit(0) if __name__ == "__main__": main()
{ "input": [ "60 3\n2012-03-16 16:15:25: Disk size is\n2012-03-16 16:15:25: Network failute\n2012-03-16 16:16:29: Cant write varlog\n2012-03-16 16:16:42: Unable to start process\n2012-03-16 16:16:43: Disk size is too small\n2012-03-16 16:16:53: Timeout detected\n", "2 2\n2012-03-16 23:59:59:Disk size is too sm\n2012-03-17 00:00:00:Network failute dete\n2012-03-17 00:00:01:Cant write varlogmysq\n", "1 2\n2012-03-16 23:59:59:Disk size\n2012-03-17 00:00:00: Network\n2012-03-17 00:00:01:Cant write varlog\n" ], "output": [ "2012-03-16 16:16:43\n", "2012-03-17 00:00:00\n", "-1\n" ] }
341
10
Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed.
def f(arr): arr=[None]+arr dp=[0]*(len(arr)) for i in range(1,len(arr)): j=int(arr[i]) for k in range(int(j),0,-1): dp[j]=max(dp[j],1+dp[k]) return len(arr)-max(dp)-1 a,b=map(int,input().strip().split()) lst=[] for i in range(a): x,y=map(float,input().strip().split()) lst.append(x) print(f(lst))
{ "input": [ "3 3\n1 5.0\n2 5.5\n3 6.0\n", "6 3\n1 14.284235\n2 17.921382\n1 20.328172\n3 20.842331\n1 25.790145\n1 27.204125\n", "3 2\n2 1\n1 2.0\n1 3.100\n" ], "output": [ "0\n", "2\n", "1\n" ] }
342
7
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire. <image> Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots. Input The first line of the input contains an integer n, (1 ≀ n ≀ 100). The next line contains a list of space-separated integers a1, a2, ..., an, (0 ≀ ai ≀ 100). The third line contains an integer m, (0 ≀ m ≀ 100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1 ≀ xi ≀ n, 1 ≀ yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment. Output On the i-th line of the output print the number of birds on the i-th wire. Examples Input 5 10 10 10 10 10 5 2 5 3 13 2 12 1 13 4 6 Output 0 12 5 0 16 Input 3 2 4 1 1 2 2 Output 3 0 3
"""609C""" # import math def main(): n = int(input()) a = list(map(int,input().split())) m = int(input()) for i in range(m): x,y = map(int,input().split()) x = x-1 if x-1>=0: a[x-1] += y-1 if x+1<n: a[x+1] += a[x]-y a[x]=0 for i in range(len(a)): print(a[i]) main()
{ "input": [ "5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6\n", "3\n2 4 1\n1\n2 2\n" ], "output": [ "0\n12\n5\n0\n16\n", "3\n0\n3\n" ] }
343
10
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact). Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive integer powers (that is, x2, x3, ...) at the next turns. For instance, if the number 9 is chosen at the first turn, one cannot choose 9 or 81 later, while it is still allowed to choose 3 or 27. The one who cannot make a move loses. Who wins if both Vasya and Petya play optimally? Input Input contains single integer n (1 ≀ n ≀ 109). Output Print the name of the winner β€” "Vasya" or "Petya" (without quotes). Examples Input 1 Output Vasya Input 2 Output Petya Input 8 Output Petya Note In the first sample Vasya will choose 1 and win immediately. In the second sample no matter which number Vasya chooses during his first turn, Petya can choose the remaining number and win.
import math, collections mod = 10**9+7 def isPower(n): if (n <= 1): return True for x in range(2, (int)(math.sqrt(n)) + 1): p = x while (p <= n): p = p * x if (p == n): return True return False n = int(input()) arr = [0,1,2,1,4,3,2,1,5,6,2,1,8,7,5,9,8,7,3,4,7,4,2,1,10,9,3,6,11,12] ans = arr[int(math.log(n, 2))] s = int(math.log(n, 2)) for i in range(3, int(n**0.5)+1): if not isPower(i): ans^=arr[int(math.log(n, i))] s+=int(math.log(n, i)) ans^=((n-s)%2) print("Vasya" if ans else "Petya")
{ "input": [ "8\n", "1\n", "2\n" ], "output": [ "Petya\n", "Vasya\n", "Petya\n" ] }
344
7
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≀ n ≀ 100, 0 ≀ k ≀ 9). The i-th of the following n lines contains integer ai without leading zeroes (1 ≀ ai ≀ 109). Output Print a single integer β€” the number of k-good numbers in a. Examples Input 10 6 1234560 1234560 1234560 1234560 1234560 1234560 1234560 1234560 1234560 1234560 Output 10 Input 2 1 1 10 Output 1
def main(): n,k=map(int,input().split()) ans=0 kset=set(map(str,range(k+1))) for i in range(n): if kset<=set(input()): ans+=1 print(ans) if __name__=='__main__': main()
{ "input": [ "2 1\n1\n10\n", "10 6\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n" ], "output": [ "1\n", "10\n" ] }
345
9
Salve, mi amice. Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus. Rp: I Aqua Fortis I Aqua Regia II Amalgama VII Minium IV Vitriol Misce in vitro et Γ¦stus, et nil admirari. Festina lente, et nulla tenaci invia est via. Fac et spera, Vale, Nicolas Flamel Input The first line of input contains several space-separated integers ai (0 ≀ ai ≀ 100). Output Print a single integer. Examples Input 2 4 6 8 10 Output 1
def main(): a = list(map(int, input().split())) assert(len(a) == 5) z = [1, 1, 2, 7, 4] ans = min(x // y for x, y in zip(a, z)) print(ans) main()
{ "input": [ "2 4 6 8 10\n" ], "output": [ "1\n" ] }
346
10
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
def main(): n, m = map(int, input().split()) n += 1 cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)] def root(x): if x != cluster[x]: cluster[x] = x = root(cluster[x]) return x for _ in range(m): a, b = map(int, input().split()) ab[a].append(b) dest[b] += 1 cluster[root(a)] = root(b) pool = [a for a, f in enumerate(dest) if not f] for a in pool: for b in ab[a]: dest[b] -= 1 if not dest[b]: pool.append(b) ab = [True] * n for a, f in enumerate(dest): if f: ab[root(a)] = False print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, ab))) if __name__ == '__main__': from sys import setrecursionlimit setrecursionlimit(100500) main()
{ "input": [ "4 6\n1 2\n1 4\n2 3\n2 4\n3 2\n3 4\n", "4 5\n1 2\n1 3\n1 4\n2 3\n2 4\n" ], "output": [ "4", "3" ] }
347
11
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007. Input The first line of input will contain two integers n, m (3 ≀ n ≀ 100 000, 0 ≀ m ≀ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≀ ai, bi ≀ n, ai β‰  bi, <image>). Each pair of people will be described no more than once. Output Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007. Examples Input 3 0 Output 4 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 0 Output 1 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 1 Output 0 Note In the first sample, the four ways are to: * Make everyone love each other * Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
class DSU(object): def __init__(self, n): self.father = list(range(n)) self.size = n def union(self, x, s): x = self.find(x) s = self.find(s) if x == s: return self.father[s] = x self.size -= 1 def find(self, x): xf = self.father[x] if xf != x: self.father[x] = self.find(xf) return self.father[x] def is_invalid(a, b, ds): return ds.find(a) == ds.find(b) n, k = map(int, input().split()) ds = DSU(n * 2) for i in range(k): first, second, color = map(int, input().split()) first -= 1 second -= 1 if color == 0: if is_invalid(first, second, ds): print(0) exit() ds.union(first, second + n) ds.union(first + n, second) else: if is_invalid(first, second + n, ds): print(0) exit() ds.union(first, second) ds.union(first + n, second + n) sum = 1 for i in range(ds.size // 2 - 1): sum = (sum * 2) % (10 ** 9 + 7) print(sum)
{ "input": [ "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 0\n", "3 0\n", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 1\n" ], "output": [ "1", "4", "0" ] }
348
10
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type β€” if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! Input The first line of the input contains three space-separated numbers, n, m and k (1 ≀ m ≀ n ≀ 18, 0 ≀ k ≀ n * (n - 1)) β€” the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≀ ai ≀ 109) β€” the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≀ xi, yi ≀ n, 0 ≀ ci ≀ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≀ i < j ≀ k), that xi = xj and yi = yj. Output In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. Examples Input 2 2 1 1 1 2 1 1 Output 3 Input 4 3 2 1 2 3 4 2 1 5 3 4 2 Output 12 Note In the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule. In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.
import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def output(*args): sys.stdout.buffer.write( ('\n'.join(map(str, args)) + '\n').encode('utf-8') ) def main(): n, m, k = map(int, input().split()) a = list(map(float, input().split())) add = [[0] * n for _ in range(n + 1)] for xi, yi, ci in (map(int, input().split()) for _ in range(k)): add[xi - 1][yi - 1] = float(ci) minf = float('-inf') dp = [[minf] * (2**n) for _ in range(n + 1)] dp[n][0] = 0.0 for bitset in range(2**n): if bin(bitset).count('1') >= m: continue for i in range(n + 1): if dp[i][bitset] == minf: continue for j in range(n): if (1 << j) & bitset: continue dp[j][bitset | (1 << j)] = max( dp[j][bitset | (1 << j)], dp[i][bitset] + a[j] + add[i][j] ) print(int(max(max(_dp) for _dp in dp) + 1e-7)) if __name__ == '__main__': main()
{ "input": [ "2 2 1\n1 1\n2 1 1\n", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2\n" ], "output": [ "3", "12" ] }
349
9
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network β€” for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety β€” in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≀ n ≀ 400, 0 ≀ m ≀ n(n - 1) / 2) β€” the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≀ u, v ≀ n, u β‰  v). You may assume that there is at most one railway connecting any two towns. Output Output one integer β€” the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
def BFS(start): queue = [start] visited = [False] * n visited[start] = True dists = [0] * n while len(queue): current = queue.pop(0) for i in graph[current]: if not visited[i]: queue.append(i) visited[i] = True dists[i] = dists[current] + 1 return dists[n - 1] n, m = map(int, input().split()) graph = [[] for i in range(n)] for i in range(m): u, v = map(int, input().split()) graph[u - 1].append(v - 1) graph[v - 1].append(u - 1) if n - 1 in graph[0]: for i in range(n): graph[i] = [j for j in range(n) if j not in graph[i] and j != i] answer = BFS(0) print(-1 if answer == 0 else answer)
{ "input": [ "5 5\n4 2\n3 5\n4 5\n5 1\n1 2\n", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n", "4 2\n1 3\n3 4\n" ], "output": [ "3\n", "-1\n", "2\n" ] }
350
7
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated. Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (c < b) rubles back, but you cannot return plastic bottles. Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help. Input First line of the input contains a single integer n (1 ≀ n ≀ 1018) β€” the number of rubles Kolya has at the beginning. Then follow three lines containing integers a, b and c (1 ≀ a ≀ 1018, 1 ≀ c < b ≀ 1018) β€” the cost of one plastic liter bottle, the cost of one glass liter bottle and the money one can get back by returning an empty glass bottle, respectively. Output Print the only integer β€” maximum number of liters of kefir, that Kolya can drink. Examples Input 10 11 9 8 Output 2 Input 10 5 6 1 Output 2 Note In the first sample, Kolya can buy one glass bottle, then return it and buy one more glass bottle. Thus he will drink 2 liters of kefir. In the second sample, Kolya can buy two plastic bottle and get two liters of kefir, or he can buy one liter glass bottle, then return it and buy one plastic bottle. In both cases he will drink two liters of kefir.
def f(n, a, b, c): if a<=b-c: return n//a ans=0 while n>=b: t=max((n-b)//(b-c), 1) n-=(b-c)*t ans+=t return ans+n//a import sys print(f(*map(int, sys.stdin.read().split())))
{ "input": [ "10\n11\n9\n8\n", "10\n5\n6\n1\n" ], "output": [ "2\n", " 2\n" ] }
351
9
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti. For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant. There are <image> non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. Input The first line of the input contains a single integer n (1 ≀ n ≀ 5000) β€” the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ n) where ti is the color of the i-th ball. Output Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. Examples Input 4 1 2 1 2 Output 7 3 0 0 Input 3 1 1 1 Output 6 0 0 Note In the first sample, color 2 is dominant in three intervals: * An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. * An interval [4, 4] contains one ball, with color 2 again. * An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them.
def main(): n = int(input()) a = [int(i) for i in input().strip().split()] res = [0] * n for st in range(n): cnt = [0] * n x = 0 y = 0 for ed in range(st, n): cnt[a[ed] - 1] += 1 if (cnt[a[ed] - 1] > x) or (cnt[a[ed] - 1] == x and a[ed] - 1 < y): x = cnt[a[ed] - 1] y = a[ed] - 1 res[y] += 1 print(" ".join(map(str, res))) if __name__ == "__main__": main()
{ "input": [ "3\n1 1 1\n", "4\n1 2 1 2\n" ], "output": [ "6 0 0\n", "7 3 0 0\n" ] }
352
8
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in. For example, consider the case when the mother has 5 flowers, and their moods are equal to 1, - 2, 1, 3, - 4. Suppose the mother suggested subarrays (1, - 2), (3, - 4), (1, 3), (1, - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then: * the first flower adds 1Β·1 = 1 to the girl's happiness, because he is in one of chosen subarrays, * the second flower adds ( - 2)Β·1 = - 2, because he is in one of chosen subarrays, * the third flower adds 1Β·2 = 2, because he is in two of chosen subarrays, * the fourth flower adds 3Β·2 = 6, because he is in two of chosen subarrays, * the fifth flower adds ( - 4)Β·0 = 0, because he is in no chosen subarrays. Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this! Alyona can choose any number of the subarrays, even 0 or all suggested by her mother. Input The first line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moods β€” n integers a1, a2, ..., an ( - 100 ≀ ai ≀ 100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≀ li ≀ ri ≀ n) denoting the subarray a[li], a[li + 1], ..., a[ri]. Each subarray can encounter more than once. Output Print single integer β€” the maximum possible value added to the Alyona's happiness. Examples Input 5 4 1 -2 1 3 -4 1 2 4 5 3 4 1 4 Output 7 Input 4 3 1 2 3 4 1 3 2 4 1 1 Output 16 Input 2 2 -1 -2 1 1 1 2 Output 0 Note The first example is the situation described in the statements. In the second example Alyona should choose all subarrays. The third example has answer 0 because Alyona can choose none of the subarrays.
def cin(): return list(map(int,input().split())) n,m=cin() A=cin() s=0 for i in range(m): a,b=cin() B=sum(A[a-1:b]) s+=max(0,B) print(s)
{ "input": [ "4 3\n1 2 3 4\n1 3\n2 4\n1 1\n", "5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4\n", "2 2\n-1 -2\n1 1\n1 2\n" ], "output": [ "16\n", "7\n", "0\n" ] }
353
7
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist. Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1, 2, ..., z. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute. Input The only string contains three integers β€” n, m and z (1 ≀ n, m, z ≀ 104). Output Print single integer β€” the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls. Examples Input 1 1 10 Output 10 Input 1 2 5 Output 2 Input 2 3 9 Output 1 Note Taymyr is a place in the north of Russia. In the first test the artists come each minute, as well as the calls, so we need to kill all of them. In the second test we need to kill artists which come on the second and the fourth minutes. In the third test β€” only the artist which comes on the sixth minute.
from math import gcd def I(): return map(int, input().split()) n, m, z = I() print(z//(n*m//gcd(n, m)))
{ "input": [ "1 1 10\n", "2 3 9\n", "1 2 5\n" ], "output": [ "10\n", "1\n", "2\n" ] }
354
7
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1). During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ( + ) instead of division button (Γ·) and got sum of numerator and denominator that was equal to n instead of the expected decimal notation. Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction <image> such that sum of its numerator and denominator equals n. Help Petya deal with this problem. Input In the only line of input there is an integer n (3 ≀ n ≀ 1000), the sum of numerator and denominator of the fraction. Output Output two space-separated positive integers a and b, numerator and denominator of the maximum possible proper irreducible fraction satisfying the given sum. Examples Input 3 Output 1 2 Input 4 Output 1 3 Input 12 Output 5 7
def gdc(a,b): if b ==0: return a return gdc(b,a%b) n = int(input()) a = n//2 b=n-a while gdc(a,b)!=1: a=a-1 b=b+1 print(a, b)
{ "input": [ "12\n", "4\n", "3\n" ], "output": [ "5 7\n", "1 3\n", "1 2\n" ] }
355
7
Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point m on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport. Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds. <image> Determine if Pig can visit the friend using teleports only, or he should use his car. Input The first line contains two integers n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 100) β€” the number of teleports and the location of the friend's house. The next n lines contain information about teleports. The i-th of these lines contains two integers ai and bi (0 ≀ ai ≀ bi ≀ m), where ai is the location of the i-th teleport, and bi is its limit. It is guaranteed that ai β‰₯ ai - 1 for every i (2 ≀ i ≀ n). Output Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input 3 5 0 2 2 4 3 5 Output YES Input 3 7 0 4 2 5 6 7 Output NO Note The first example is shown on the picture below: <image> Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives. The second example is shown on the picture below: <image> You can see that there is no path from Pig's house to his friend's house that uses only teleports.
def fn(n): a=0 for i in range(int(n[0])): t=input().split(' ') if int(t[0])<=a : a=max(a,int(t[1])) if a>=int(n[1]): return 'YES' else: return 'NO' print(fn(input().split(' ')))
{ "input": [ "3 5\n0 2\n2 4\n3 5\n", "3 7\n0 4\n2 5\n6 7\n" ], "output": [ "YES\n", "NO\n" ] }
356
9
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value. Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi. Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day. Input The first line contains a single positive integer n (1 ≀ n ≀ 105) β€” the number of days. The second line contains n space-separated integers m1, m2, ..., mn (0 ≀ mi < i) β€” the number of marks strictly above the water on each day. Output Output one single integer β€” the minimum possible sum of the number of marks strictly below the water level among all days. Examples Input 6 0 1 0 3 0 2 Output 6 Input 5 0 1 2 1 2 Output 1 Input 5 0 1 1 2 2 Output 0 Note In the first example, the following figure shows an optimal case. <image> Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6. In the second example, the following figure shows an optimal case. <image>
# python3 def readline(): return map(int, input().split()) def main(): n = int(input()) m = tuple(readline()) md = [None] * n prev = 0 for i in range(n): prev = md[i] = max(prev, m[i]) prev = 0 for i in range(n - 1, -1, -1): prev -= 1 prev = md[i] = max(prev, md[i]) print(sum(md) - sum(m)) main()
{ "input": [ "5\n0 1 1 2 2\n", "6\n0 1 0 3 0 2\n", "5\n0 1 2 1 2\n" ], "output": [ "0\n", "6\n", "1\n" ] }
357
11
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard). <image> Input The first line of input contains a single integer N (1 ≀ N ≀ 100) β€” the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct. Output Output a single number. Examples Input 9 brie soft camembert soft feta soft goat soft muenster soft asiago hard cheddar hard gouda hard swiss hard Output 3 Input 6 parmesan hard emmental hard edam hard colby hard gruyere hard asiago hard Output 4
def main(): n = int(input()) b, w = 0, 0 for x in range(n): s = input().split()[1] if s == 'soft': b += 1 else: w += 1 for x in range(1, 100): a = x ** 2 a1 = a // 2 a2 = a - a1 if max(b, w) <= a2 and min(b, w) <= a1: print(x) return main()
{ "input": [ "6\nparmesan hard\nemmental hard\nedam hard\ncolby hard\ngruyere hard\nasiago hard\n", "9\nbrie soft\ncamembert soft\nfeta soft\ngoat soft\nmuenster soft\nasiago hard\ncheddar hard\ngouda hard\nswiss hard\n" ], "output": [ "4\n", "3\n" ] }
358
8
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently. To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice. Input The first line contains integer n β€” the number of cups on the royal table (1 ≀ n ≀ 1000). Next n lines contain volumes of juice in each cup β€” non-negative integers, not exceeding 104. Output If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes). Examples Input 5 270 250 250 230 250 Output 20 ml. from cup #4 to cup #1. Input 5 250 250 250 250 250 Output Exemplary pages. Input 5 270 250 249 230 250 Output Unrecoverable configuration.
def s(): n = int(input()) a = [int(input()) for _ in range(n)] mi = min(enumerate(a),key = lambda x:x[1]) ma = max(enumerate(a),key = lambda x:x[1]) p = sum(a) if p%n != 0: return 'Unrecoverable configuration.' if mi[1] == ma[1]: return 'Exemplary pages.' if a.count(mi[1]) > 1 or a.count(ma[1]) > 1: return 'Unrecoverable configuration.' return '{} ml. from cup #{} to cup #{}.'.format((ma[1]-mi[1])//2,mi[0]+1,ma[0]+1) print(s())
{ "input": [ "5\n250\n250\n250\n250\n250\n", "5\n270\n250\n250\n230\n250\n", "5\n270\n250\n249\n230\n250\n" ], "output": [ "Exemplary pages.\n", "20 ml. from cup #4 to cup #1.\n", "Unrecoverable configuration.\n" ] }
359
7
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. There are n winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words. What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one? The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists. Input The first line contains one integer n (1 ≀ n ≀ 100) β€” the number of T-shirts. The i-th of the next n lines contains a_i β€” the size of the i-th T-shirt of the list for the previous year. The i-th of the next n lines contains b_i β€” the size of the i-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list b from the list a. Output Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0. Examples Input 3 XS XS M XL S XS Output 2 Input 2 XXXL XXL XXL XXXS Output 1 Input 2 M XS XS M Output 0 Note In the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L". In the second example Ksenia should replace "L" in "XXXL" with "S". In the third example lists are equal.
while True: try: def read(): n = int(input()) p = list() for i in range(n): p.append(input()) for i in range(n): n = input() if n in p: p.remove(n) print(len(p)) if __name__ =="__main__": read() except EOFError: break
{ "input": [ "2\nM\nXS\nXS\nM\n", "3\nXS\nXS\nM\nXL\nS\nXS\n", "2\nXXXL\nXXL\nXXL\nXXXS\n" ], "output": [ "0\n", "2\n", "1\n" ] }
360
8
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers. For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbitrary integer greater than 1, such that it divides at least one element in each pair. WCD may not exist for some lists. For example, if the list looks like [(12, 15), (25, 18), (10, 24)], then their WCD can be equal to 2, 3, 5 or 6 (each of these numbers is strictly greater than 1 and divides at least one number in each pair). You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently. Input The first line contains a single integer n (1 ≀ n ≀ 150 000) β€” the number of pairs. Each of the next n lines contains two integer values a_i, b_i (2 ≀ a_i, b_i ≀ 2 β‹… 10^9). Output Print a single integer β€” the WCD of the set of pairs. If there are multiple possible answers, output any; if there is no answer, print -1. Examples Input 3 17 18 15 24 12 15 Output 6 Input 2 10 16 7 17 Output -1 Input 5 90 108 45 105 75 40 165 175 33 30 Output 5 Note In the first example the answer is 6 since it divides 18 from the first pair, 24 from the second and 12 from the third ones. Note that other valid answers will also be accepted. In the second example there are no integers greater than 1 satisfying the conditions. In the third example one of the possible answers is 5. Note that, for example, 15 is also allowed, but it's not necessary to maximize the output.
n = int(input()) a,b = [0]*n,[0]*n g = 0 def gcd(a,b): return a if b == 0 else gcd(b,a%b) for i in range(n): (a[i],b[i]) = map(int,input().split()) g = gcd(g,a[i]*b[i]) for i in range(n): if gcd(g,a[i]) > 1: g = gcd(g,a[i]) else: g = gcd(g,b[i]) print(g if g > 1 else -1)
{ "input": [ "2\n10 16\n7 17\n", "3\n17 18\n15 24\n12 15\n", "5\n90 108\n45 105\n75 40\n165 175\n33 30\n" ], "output": [ "-1\n", "2\n", "3\n" ] }
361
10
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: a_{1} ≀ a_{2}, a_{n} ≀ a_{n-1} and a_{i} ≀ max(a_{i-1}, a_{i+1}) for all i from 2 to n-1. Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from 1 to 200. Since the number of ways can be big, print it modulo 998244353. Input First line of input contains one integer n (2 ≀ n ≀ 10^{5}) β€” size of the array. Second line of input contains n integers a_{i} β€” elements of array. Either a_{i} = -1 or 1 ≀ a_{i} ≀ 200. a_{i} = -1 means that i-th element can't be read. Output Print number of ways to restore the array modulo 998244353. Examples Input 3 1 -1 2 Output 1 Input 2 -1 -1 Output 200 Note In the first example, only possible value of a_{2} is 2. In the second example, a_{1} = a_{2} so there are 200 different values because all restored elements should be integers between 1 and 200.
from math import trunc MX = 201 MOD = 998244353 MODF = MOD * 1.0 quickmod = lambda x: x - MODF * trunc(x / MODF) def main(): n = int(input()) a = map(int, input().split()) dp0 = [1.0] * MX dp1 = [0.0] * MX for x in a: pomdp0 = [0.0] * MX pomdp1 = [0.0] * MX if x == -1: for val in range(1, MX): pomdp0[val] = quickmod( pomdp0[val - 1] + dp1[val - 1] + dp0[val - 1]) pomdp1[val] = quickmod( pomdp1[val - 1] + dp1[MX - 1] - dp1[val - 1] + dp0[val] - dp0[val - 1]) else: pomdp0[x] = quickmod(dp1[x - 1] + dp0[x - 1]) pomdp1[x] = quickmod(dp1[MX - 1] - dp1[x - 1] + dp0[x] - dp0[x - 1]) for val in range(x + 1, MX): pomdp0[val] = pomdp0[val - 1] pomdp1[val] = pomdp1[val - 1] dp0, dp1 = pomdp0, pomdp1 print(int(dp1[MX - 1] if n > 1 else dp0[MX - 1]) % MOD) if __name__ == "__main__": main()
{ "input": [ "3\n1 -1 2\n", "2\n-1 -1\n" ], "output": [ "1\n", "200\n" ] }
362
9
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. * Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. * If you walked over at least one black edge during this process, then the sequence is good. <image> Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3]. There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7. Input The first line contains two integers n and k (2 ≀ n ≀ 10^5, 2 ≀ k ≀ 100), the size of the tree and the length of the vertex sequence. Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 ≀ u_i, v_i ≀ n, x_i ∈ \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge). Output Print the number of good sequences modulo 10^9 + 7. Examples Input 4 4 1 2 1 2 3 1 3 4 1 Output 252 Input 4 6 1 2 0 1 3 0 1 4 0 Output 0 Input 3 5 1 2 1 2 3 0 Output 210 Note In the first example, all sequences (4^4) of length 4 except the following are good: * [1, 1, 1, 1] * [2, 2, 2, 2] * [3, 3, 3, 3] * [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
import collections as cc I=lambda:list(map(int,input().split())) n,k=I() mod=10**9+7 parent=[i for i in range(n+1)] def find(x): global count count+=1 while parent[x]!=x: x=parent[x] return x def union(x,y): a=find(x) b=find(y) if a!=b: parent[a]=parent[b]=min(a,b) count=0 tf=0 for i in range(n-1): a,b,c=I() if not c: tf=1 union(a,b) temp=[find(i) for i in range(1,n+1)] tem=cc.Counter(temp) ans=pow(n,k,mod) for i in tem: ans-=((tem[i]**k)%mod) ans%=mod print(ans)
{ "input": [ "4 4\n1 2 1\n2 3 1\n3 4 1\n", "4 6\n1 2 0\n1 3 0\n1 4 0\n", "3 5\n1 2 1\n2 3 0\n" ], "output": [ " 252\n", " 0\n", " 210\n" ] }
363
9
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it). For example, for the sequence [1, 2, 4, 3, 2] the answer is 4 (you take 1 and the sequence becomes [2, 4, 3, 2], then you take the rightmost element 2 and the sequence becomes [2, 4, 3], then you take 3 and the sequence becomes [2, 4] and then you take 4 and the sequence becomes [2], the obtained increasing sequence is [1, 2, 3, 4]). Input The first line of the input contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 2 β‹… 10^5), where a_i is the i-th element of a. Output In the first line of the output print k β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string s of length k, where the j-th character of this string s_j should be 'L' if you take the leftmost element during the j-th move and 'R' otherwise. If there are multiple answers, you can print any. Examples Input 5 1 2 4 3 2 Output 4 LRRR Input 7 1 3 5 6 5 4 2 Output 6 LRLRRR Input 3 2 2 2 Output 1 R Input 4 1 2 4 3 Output 4 LLRR Note The first example is described in the problem statement.
def fun(array): ans='' count=0 l,r=0,n-1 last=-1 while l<=r: if min(array[l],array[r])<=last: break if array[l]<array[r]: last=array[l] ans+='L' l+=1 count+=1 elif array[l]>array[r]: last=array[r] ans+='R' r-=1 count+=1 else: break ans_1=ans last_1=last l_1=l while l_1<=r and array[l_1]>last_1: ans_1+='L' last_1=array[l_1] l_1+=1 ans_2=ans last_2=last r_2=r while r_2>=l and array[r_2]>last_2: ans_2+='R' last_2=array[r_2] r_2-=1 if len(ans_1)>len(ans_2): ans=ans_1 else: ans=ans_2 print(len(ans)) print(ans) n=int(input()) array=list(map(int,input().split( ))) fun(array)
{ "input": [ "7\n1 3 5 6 5 4 2\n", "5\n1 2 4 3 2\n", "4\n1 2 4 3\n", "3\n2 2 2\n" ], "output": [ "6\nLRLRRR", "4\nLRRR", "4\nLLRR\n", "1\nR" ] }
364
7
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K βŒ‰ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≀ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K βŒ‰ is the smallest integer such that K ≀ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≀ n ≀ 4 β‹… 10^{5}, 1 ≀ I ≀ 10^{8}) β€” the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≀ a_{i} ≀ 10^{9}) β€” the array denoting the sound file. Output Print a single integer β€” the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s.
def solve(): n,i = map(int, input().split()) ns = sorted([*map(int, input().split())]) k = 1<<(i*8//n) lis = [] for i in range(n-1): if ns[i]!=ns[i+1]: lis.append(i+1) lis.append(n) print(0 if len(lis) <= k else n-max(lis[i+k]-lis[i] for i in range(len(lis)-k))) solve()
{ "input": [ "6 1\n2 1 2 3 4 3\n", "6 1\n1 1 2 2 3 3\n", "6 2\n2 1 2 3 4 3\n" ], "output": [ "2\n", "2\n", "0\n" ] }
365
8
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point x = 0 is where these parts meet. The right part of the corridor is filled with n monsters β€” for each monster, its initial coordinate x_i is given (and since all monsters are in the right part, every x_i is positive). The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to 0), it gets instantly killed by a trap. The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point c. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be y, then: * if c = y, then the monster is killed; * if y < c, then the monster is pushed r units to the left, so its current coordinate becomes y - r; * if y > c, then the monster is pushed r units to the right, so its current coordinate becomes y + r. Ivan is going to kill the monsters as follows: choose some integer point d and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on. What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally. You have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The first line of each query contains two integers n and r (1 ≀ n, r ≀ 10^5) β€” the number of enemies and the distance that the enemies are thrown away from the epicenter of the explosion. The second line of each query contains n integers x_i (1 ≀ x_i ≀ 10^5) β€” the initial positions of the monsters. It is guaranteed that sum of all n over all queries does not exceed 10^5. Output For each query print one integer β€” the minimum number of shots from the Phoenix Rod required to kill all monsters. Example Input 2 3 2 1 3 5 4 1 5 2 3 5 Output 2 2 Note In the first test case, Ivan acts as follows: * choose the point 3, the first monster dies from a crusher trap at the point -1, the second monster dies from the explosion, the third monster is pushed to the point 7; * choose the point 7, the third monster dies from the explosion. In the second test case, Ivan acts as follows: * choose the point 5, the first and fourth monsters die from the explosion, the second monster is pushed to the point 1, the third monster is pushed to the point 2; * choose the point 2, the first monster dies from a crusher trap at the point 0, the second monster dies from the explosion.
import sys I = sys.stdin.readline pr = sys.stdout.write srt=sorted lst=list st=set def main(): for _ in range(int(I())): n,r=map(int,I().split()) ar=srt(lst(st(map(int,I().split())))) pre=0 i=len(ar)-1;c=0 while i>=0: if ar[i]<=pre:break else:c+=1;pre+=r i-=1 pr(str(c)) pr('\n') main()
{ "input": [ "2\n3 2\n1 3 5\n4 1\n5 2 3 5\n" ], "output": [ "2\n2\n" ] }
366
9
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed n. You are standing at 0 and want to reach n+1 somehow. If you are standing at the position x, you can jump to any position in the range [x + 1; x + d]. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if d=1, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells 0 and n+1 belong to wooden platforms. You want to know if it is possible to reach n+1 from 0 if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms. Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping). For example, if n=7, m=3, d=2 and c = [1, 2, 1], then one of the ways to reach 8 from 0 is follow: <image> The first example: n=7. Input The first line of the input contains three integers n, m and d (1 ≀ n, m, d ≀ 1000, m ≀ n) β€” the width of the river, the number of platforms and the maximum distance of your jump, correspondingly. The second line of the input contains m integers c_1, c_2, ..., c_m (1 ≀ c_i ≀ n, βˆ‘_{i=1}^{m} c_i ≀ n), where c_i is the length of the i-th platform. Output If it is impossible to reach n+1 from 0, print NO in the first line. Otherwise, print YES in the first line and the array a of length n in the second line β€” the sequence of river cells (excluding cell 0 and cell n + 1). If the cell i does not belong to any platform, a_i should be 0. Otherwise, it should be equal to the index of the platform (1-indexed, platforms are numbered from 1 to m in order of input) to which the cell i belongs. Note that all a_i equal to 1 should form a contiguous subsegment of the array a of length c_1, all a_i equal to 2 should form a contiguous subsegment of the array a of length c_2, ..., all a_i equal to m should form a contiguous subsegment of the array a of length c_m. The leftmost position of 2 in a should be greater than the rightmost position of 1, the leftmost position of 3 in a should be greater than the rightmost position of 2, ..., the leftmost position of m in a should be greater than the rightmost position of m-1. See example outputs for better understanding. Examples Input 7 3 2 1 2 1 Output YES 0 1 0 2 2 0 3 Input 10 1 11 1 Output YES 0 0 0 0 0 0 0 0 0 1 Input 10 1 5 2 Output YES 0 0 0 0 1 1 0 0 0 0 Note Consider the first example: the answer is [0, 1, 0, 2, 2, 0, 3]. The sequence of jumps you perform is 0 β†’ 2 β†’ 4 β†’ 5 β†’ 7 β†’ 8. Consider the second example: it does not matter how to place the platform because you always can jump from 0 to 11. Consider the third example: the answer is [0, 0, 0, 0, 1, 1, 0, 0, 0, 0]. The sequence of jumps you perform is 0 β†’ 5 β†’ 6 β†’ 11.
def f(n,m,d,a): b=[0]*m pos=0 for i in range(m): # print(b) b[i]=pos+d pos=pos+d+a[i]-1 # print(b) if b[-1]+a[-1]-1+d<n+1: print("NO") return [] pos=n+1 c=[0]*n for i in range(m-1,-1,-1): if b[i]+a[i]-1>=pos: b[i]=pos-a[i] pos=b[i] for j in range(b[i],b[i]+a[i]): c[j-1]=i+1 print("YES") return c n,m,d=map(int,input().strip().split()) l=list(map(int,input().strip().split())) print(*f(n,m,d,l))
{ "input": [ "7 3 2\n1 2 1\n", "10 1 5\n2\n", "10 1 11\n1\n" ], "output": [ "YES\n0 1 0 2 2 0 3\n", "YES\n0 0 0 0 1 1 0 0 0 0\n", "YES\n0 0 0 0 0 0 0 0 0 1\n" ] }
367
9
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second. If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be: <image> Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible. Determine how much each tap should be opened so that Bob was pleased with the result in the end. Input You are given five integers t1, t2, x1, x2 and t0 (1 ≀ t1 ≀ t0 ≀ t2 ≀ 106, 1 ≀ x1, x2 ≀ 106). Output Print two space-separated integers y1 and y2 (0 ≀ y1 ≀ x1, 0 ≀ y2 ≀ x2). Examples Input 10 70 100 100 25 Output 99 33 Input 300 500 1000 1000 300 Output 1000 0 Input 143 456 110 117 273 Output 76 54 Note In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
import math def gcd(a,b): if(b==0): return a return gcd(b,a%b) l=input().split() t1=int(l[0]) t2=int(l[1]) x1=int(l[2]) x2=int(l[3]) t0=int(l[4]) num1=t2-t0 num2=t0-t1 if(t1==t2): print(x1,x2) quit() if(num1==0): print(0,x2) quit() if(num2==0): print(x1,0) quit() z=num2/num1 maxa=10**18 ans=(0,0) for i in range(1,x1+1): ok=z*i if(ok>x2): break num1=i num2=math.ceil(ok) if(maxa==((num2/num1)-z) and num2+num1>ans[0]+ans[1]): ans=(num1,num2) elif(maxa>((num2/num1)-z)): ans=(num1,num2) maxa=((num2/num1-z)) if(ans==(0,0)): ans=(0,x2) print(ans[0],ans[1])
{ "input": [ "300 500 1000 1000 300\n", "10 70 100 100 25\n", "143 456 110 117 273\n" ], "output": [ "1000 0\n", "99 33\n", "76 54\n" ] }
368
8
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said: β€”Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes. β€”No problem! β€” said Bob and immediately gave her an answer. Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict. Input The first line contains one integer n (0 ≀ n ≀ 109) without leading zeroes. The second lines contains one integer m (0 ≀ m ≀ 109) β€” Bob's answer, possibly with leading zeroes. Output Print OK if Bob's answer is correct and WRONG_ANSWER otherwise. Examples Input 3310 1033 Output OK Input 4 5 Output WRONG_ANSWER
def main(): s = input() if s != "0": l = sorted(c for c in s if c != '0') l[0] += '0' * s.count('0') s = ''.join(l) print(("OK", "WRONG_ANSWER")[s != input()]) if __name__ == '__main__': main()
{ "input": [ "3310\n1033\n", "4\n5\n" ], "output": [ "OK\n", "WRONG_ANSWER\n" ] }
369
10
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one β€” xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute $$$ (a_1 + a_2) βŠ• (a_1 + a_3) βŠ• … βŠ• (a_1 + a_n) \\\ βŠ• (a_2 + a_3) βŠ• … βŠ• (a_2 + a_n) \\\ … \\\ βŠ• (a_{n-1} + a_n) \\\ $$$ Here x βŠ• y is a bitwise XOR operation (i.e. x ^ y in many modern programming languages). You can read about it in Wikipedia: <https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation>. Input The first line contains a single integer n (2 ≀ n ≀ 400 000) β€” the number of integers in the array. The second line contains integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^7). Output Print a single integer β€” xor of all pairwise sums of integers in the given array. Examples Input 2 1 2 Output 3 Input 3 1 2 3 Output 2 Note In the first sample case there is only one sum 1 + 2 = 3. In the second sample case there are three sums: 1 + 2 = 3, 1 + 3 = 4, 2 + 3 = 5. In binary they are represented as 011_2 βŠ• 100_2 βŠ• 101_2 = 010_2, thus the answer is 2. βŠ• is the bitwise xor operation. To define x βŠ• y, consider binary representations of integers x and y. We put the i-th bit of the result to be 1 when exactly one of the i-th bits of x and y is 1. Otherwise, the i-th bit of the result is put to be 0. For example, 0101_2 βŠ• 0011_2 = 0110_2.
import sys from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def main(): n = int(input()) a = sorted(map(int, input().split())) ans = 0 for d in range(25, -1, -1): bit = 1 << d cnt = 0 j = k = l = n - 1 for i, x in enumerate(a): j, k, l = max(j, i), max(k, i), max(l, i) while i < j and a[j] >= bit - x: j -= 1 while j < k and a[k] >= 2 * bit - x: k -= 1 while k < l and a[l] >= 3 * bit - x: l -= 1 cnt += k - j + n - 1 - l if cnt & 1: ans += bit for i in range(n): a[i] &= ~bit a.sort() print(ans) if __name__ == '__main__': main()
{ "input": [ "3\n1 2 3\n", "2\n1 2\n" ], "output": [ "2\n", "3\n" ] }
370
9
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≀ x ≀ r_i, and ((x mod a) mod b) β‰  ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z. For example, 5 mod 3 = 2, 7 mod 8 = 7, 9 mod 4 = 1, 9 mod 9 = 0. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then the test cases follow. The first line of each test case contains three integers a, b and q (1 ≀ a, b ≀ 200; 1 ≀ q ≀ 500). Then q lines follow, each containing two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 10^{18}) for the corresponding query. Output For each test case, print q integers β€” the answers to the queries of this test case in the order they appear. Example Input 2 4 6 5 1 1 1 3 1 5 1 7 1 9 7 10 2 7 8 100 200 Output 0 0 0 2 4 0 91
import math a = 0 b = 0 p = 0 def get(x): k = x // p return (x-(k*max(a, b)+min(max(a, b), (x % p+1)))) for _ in range(int(input())): a, b, q = map(int, input().split()) p = math.gcd(a, b) p = a * b // p for k in range(q): l, r = map(int, input().split()) print(get(r) - get(l-1), end=' ') print(" ")
{ "input": [ "2\n4 6 5\n1 1\n1 3\n1 5\n1 7\n1 9\n7 10 2\n7 8\n100 200\n" ], "output": [ "0\n0\n0\n2\n4\n0\n91\n" ] }
371
9
Given an array a of length n, find another array, b, of length n such that: * for each i (1 ≀ i ≀ n) MEX(\\{b_1, b_2, …, b_i\})=a_i. The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this. Input The first line contains an integer n (1 ≀ n ≀ 10^5) β€” the length of the array a. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ i) β€” the elements of the array a. It's guaranteed that a_i ≀ a_{i+1} for 1≀ i < n. Output If there's no such array, print a single line containing -1. Otherwise, print a single line containing n integers b_1, b_2, …, b_n (0 ≀ b_i ≀ 10^6) If there are multiple answers, print any. Examples Input 3 1 2 3 Output 0 1 2 Input 4 0 0 0 2 Output 1 3 4 0 Input 3 1 1 3 Output 0 2 1 Note In the second test case, other answers like [1,1,1,0], for example, are valid.
from sys import stdin,stderr def rl(): return [int(w) for w in stdin.readline().split()] n, = rl() a = rl() a_set = set(a) free = 0 prev = 0 b = [] for cur in a: if cur != prev: b.append(prev) if free == prev: free += 1 prev = cur else: while free in a_set: free += 1 b.append(free) free += 1 print(*b)
{ "input": [ "3\n1 2 3\n", "3\n1 1 3\n", "4\n0 0 0 2\n" ], "output": [ "0 1 2\n", "0 2 1\n", "1 3 4 0\n" ] }
372
10
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player. More formally: if the current score of the player is x and the chosen element is y, his new score will be x βŠ• y. Here βŠ• denotes [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Note that after a move element y is removed from a. * The game ends when the array is empty. At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw. If both players play optimally find out whether Koa will win, lose or draw the game. Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains the integer n (1 ≀ n ≀ 10^5) β€” the length of a. The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 10^9) β€” elements of a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print: * WIN if Koa will win the game. * LOSE if Koa will lose the game. * DRAW if the game ends in a draw. Examples Input 3 3 1 2 2 3 2 2 3 5 0 0 0 2 2 Output WIN LOSE DRAW Input 4 5 4 1 5 1 3 4 1 0 1 6 1 0 2 5 4 Output WIN WIN DRAW WIN Note In testcase 1 of the first sample we have: a = [1, 2, 2]. Here Koa chooses 1, other player has to choose 2, Koa chooses another 2. Score for Koa is 1 βŠ• 2 = 3 and score for other player is 2 so Koa wins.
def solve(): n = int(input()) lst = list(map(int,input().split())) k = 1 while k < 10**9: k *= 2 num = 0 while k and num % 2 == 0: num = 0 for i in lst: if i % (k * 2) // k == 1: num += 1 k //= 2 if k == 0 and num % 2 == 0: print("DRAW") return 0 if (num % 4 == 1) or (n % 2 == 0): print("WIN") else: print("LOSE") for i in range(int(input())): solve()
{ "input": [ "4\n5\n4 1 5 1 3\n4\n1 0 1 6\n1\n0\n2\n5 4\n", "3\n3\n1 2 2\n3\n2 2 3\n5\n0 0 0 2 2\n" ], "output": [ "WIN\nWIN\nDRAW\nWIN\n", "WIN\nLOSE\nDRAW\n" ] }
373
7
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * mex(\{1,4,0,2,2,1\})=3 * mex(\{3,3,2,1,3,0,0\})=4 * mex(βˆ…)=0 (mex for empty set) The set is splitted into two subsets A and B if for any integer number x the number of occurrences of x into this set is equal to the sum of the number of occurrences of x into A and the number of occurrences of x into B. Input The input consists of multiple test cases. The first line contains an integer t (1≀ t≀ 100) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (1≀ n≀ 100) β€” the size of the set. The second line of each testcase contains n integers a_1,a_2,... a_n (0≀ a_i≀ 100) β€” the numbers in the set. Output For each test case, print the maximum value of mex(A)+mex(B). Example Input 4 6 0 2 1 5 0 1 3 0 1 2 4 0 2 0 1 6 1 2 3 4 5 6 Output 5 3 4 0 Note In the first test case, A=\left\{0,1,2\right\},B=\left\{0,1,5\right\} is a possible choice. In the second test case, A=\left\{0,1,2\right\},B=βˆ… is a possible choice. In the third test case, A=\left\{0,1,2\right\},B=\left\{0\right\} is a possible choice. In the fourth test case, A=\left\{1,3,5\right\},B=\left\{2,4,6\right\} is a possible choice.
t = int(input()) def mex(setter): a = set(range(0, 101)) return min(a - setter) for i in range(t): n = int(input()) a = list(map(int,input().split())) A = set(a) B = set() for elem in a: if a.count(elem) > 1: B.add(elem) minimum = mex(A)+mex(B) print(minimum)
{ "input": [ "4\n6\n0 2 1 5 0 1\n3\n0 1 2\n4\n0 2 0 1\n6\n1 2 3 4 5 6\n" ], "output": [ "5\n3\n4\n0\n" ] }
374
8
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 point. If you win the very first game of the tournament you get 1 point (since there is not a "previous game"). The outcomes of the n games are represented by a string s of length n: the i-th character of s is W if you have won the i-th game, while it is L if you have lost the i-th game. After the tournament, you notice a bug on the website that allows you to change the outcome of at most k of your games (meaning that at most k times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug. Compute the maximum score you can get by cheating in the optimal way. Input Each test contains multiple test cases. The first line contains an integer t (1≀ t ≀ 20,000) β€” the number of test cases. The description of the test cases follows. The first line of each testcase contains two integers n, k (1≀ n≀ 100,000, 0≀ k≀ n) – the number of games played and the number of outcomes that you can change. The second line contains a string s of length n containing only the characters W and L. If you have won the i-th game then s_i= W, if you have lost the i-th game then s_i= L. It is guaranteed that the sum of n over all testcases does not exceed 200,000. Output For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way. Example Input 8 5 2 WLWLL 6 5 LLLWWL 7 1 LWLWLWL 15 5 WWWLLLWWWLLLWWW 40 7 LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL 1 0 L 1 1 L 6 1 WLLWLW Output 7 11 6 26 46 0 1 6 Note Explanation of the first testcase. Before changing any outcome, the score is 2. Indeed, you won the first game, so you got 1 point, and you won also the third, so you got another 1 point (and not 2 because you lost the second game). An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is 7=1+2+2+2: 1 point for the first game and 2 points for the second, third and fourth game. Explanation of the second testcase. Before changing any outcome, the score is 3. Indeed, you won the fourth game, so you got 1 point, and you won also the fifth game, so you got 2 more points (since you won also the previous game). An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is 11 = 1+2+2+2+2+2: 1 point for the first game and 2 points for all the other games.
def solve(): n,k=map(int,input().split()) #print(n,k) l=sorted(map(len,input().strip('L').split('W'))) z=len(l)+k while l and l[0]<=k: k-=l.pop(0) ans=2*min(n,z-1)-len(l) if ans<=0: ans=1 print(ans-1) t=int(input()) for _ in range(0,t): solve()
{ "input": [ "8\n5 2\nWLWLL\n6 5\nLLLWWL\n7 1\nLWLWLWL\n15 5\nWWWLLLWWWLLLWWW\n40 7\nLLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL\n1 0\nL\n1 1\nL\n6 1\nWLLWLW\n" ], "output": [ "7\n11\n6\n26\n46\n0\n1\n6\n" ] }
375
8
You have n distinct points (x_1, y_1),…,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls. In one operation, you can select a ball i to charge it. Once charged, all balls with Manhattan distance at most k from ball i move to the position of ball i. Many balls may have the same coordinate after an operation. More formally, for all balls j such that |x_i - x_j| + |y_i - y_j| ≀ k, we assign x_j:=x_i and y_j:=y_i. <image> An example of an operation. After charging the ball in the center, two other balls move to its position. On the right side, the red dot in the center is the common position of those balls. Your task is to find the minimum number of operations to move all balls to the same position, or report that this is impossible. Input The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. The first line of each test case contains two integers n, k (2 ≀ n ≀ 100, 0 ≀ k ≀ 10^6) β€” the number of balls and the attract power of all balls, respectively. The following n lines describe the balls' coordinates. The i-th of these lines contains two integers x_i, y_i (0 ≀ x_i, y_i ≀ 10^5) β€” the coordinates of the i-th ball. It is guaranteed that all points are distinct. Output For each test case print a single integer β€” the minimum number of operations to move all balls to the same position, or -1 if it is impossible. Example Input 3 3 2 0 0 3 3 1 1 3 3 6 7 8 8 6 9 4 1 0 0 0 1 0 2 0 3 Output -1 1 -1 Note In the first test case, there are three balls at (0, 0), (3, 3), and (1, 1) and the attract power is 2. It is possible to move two balls together with one operation, but not all three balls together with any number of operations. In the second test case, there are three balls at (6, 7), (8, 8), and (6, 9) and the attract power is 3. If we charge any ball, the other two will move to the same position, so we only require one operation. In the third test case, there are four balls at (0, 0), (0, 1), (0, 2), and (0, 3), and the attract power is 1. We can show that it is impossible to move all balls to the same position with a sequence of operations.
def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def solve(n, k, p): for i in range(n): if all(dist(p[i], p[j]) <= k for j in range(n)): return 1 return -1 tests = int(input()) for test in range(tests): n, k = map(int, input().split()) p = [list(map(int, input().split())) for i in range(n)] print(solve(n, k, p))
{ "input": [ "3\n3 2\n0 0\n3 3\n1 1\n3 3\n6 7\n8 8\n6 9\n4 1\n0 0\n0 1\n0 2\n0 3\n" ], "output": [ "\n-1\n1\n-1\n" ] }
376
8
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" β€” you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots. Today Petya is watching a shocking blockbuster about the Martians called "R2:D2". What can "R2:D2" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are 24 hours and each hour has 60 minutes). The time is written as "a:b", where the string a stands for the number of hours (from 0 to 23 inclusive), and string b stands for the number of minutes (from 0 to 59 inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written. Your task is to print the radixes of all numeral system which can contain the time "a:b". Input The first line contains a single string as "a:b" (without the quotes). There a is a non-empty string, consisting of numbers and uppercase Latin letters. String a shows the number of hours. String b is a non-empty string that consists of numbers and uppercase Latin letters. String b shows the number of minutes. The lengths of strings a and b are from 1 to 5 characters, inclusive. Please note that strings a and b can have leading zeroes that do not influence the result in any way (for example, string "008:1" in decimal notation denotes correctly written time). We consider characters 0, 1, ..., 9 as denoting the corresponding digits of the number's representation in some numeral system, and characters A, B, ..., Z correspond to numbers 10, 11, ..., 35. Output Print the radixes of the numeral systems that can represent the time "a:b" in the increasing order. Separate the numbers with spaces or line breaks. If there is no numeral system that can represent time "a:b", print the single integer 0. If there are infinitely many numeral systems that can represent the time "a:b", print the single integer -1. Note that on Mars any positional numeral systems with positive radix strictly larger than one are possible. Examples Input 11:20 Output 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Input 2A:13 Output 0 Input 000B:00001 Output -1 Note Let's consider the first sample. String "11:20" can be perceived, for example, as time 4:6, represented in the ternary numeral system or as time 17:32 in hexadecimal system. Let's consider the second sample test. String "2A:13" can't be perceived as correct time in any notation. For example, let's take the base-11 numeral notation. There the given string represents time 32:14 that isn't a correct time. Let's consider the third sample. String "000B:00001" can be perceived as a correct time in the infinite number of numeral systems. If you need an example, you can take any numeral system with radix no less than 12.
def s(): a = [[ord(i)-48 if ord(i) < 60 else ord(i)-55 for i in i]for i in input().split(':')] r = [i for i in range(max(max(a[0]),max(a[1]))+1,61) if sum(list(i**l[0]*l[1] for l in enumerate(reversed(a[0]))))<24 and sum(list(i**l[0]*l[1] for l in enumerate(reversed(a[1]))))<60] if len(r) == 0: print(0) elif r[-1] == 60: print(-1) else: print(*r) s()
{ "input": [ "2A:13\n", "11:20\n", "000B:00001\n" ], "output": [ "0", "3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ", "-1" ] }
377
8
<image> While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, …, a_n to -a_1, -a_2, …, -a_n. For some unknown reason, the number of service variables is always an even number. William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed 5 000 and after every operation no variable can have an absolute value greater than 10^{18}. William can perform actions of two types for two chosen variables with indices i and j, where i < j: 1. Perform assignment a_i = a_i + a_j 2. Perform assignment a_j = a_j - a_i William wants you to develop a strategy that will get all the internal variables to the desired values. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 20). Description of the test cases follows. The first line of each test case contains a single even integer n (2 ≀ n ≀ 10^3), which is the number of internal variables. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9), which are initial values of internal variables. Output For each test case print the answer in the following format: The first line of output must contain the total number of actions k, which the strategy will perform. Note that you do not have to minimize k. The inequality k ≀ 5 000 must be satisfied. Each of the next k lines must contain actions formatted as "type i j", where "type" is equal to "1" if the strategy needs to perform an assignment of the first type and "2" if the strategy needs to perform an assignment of the second type. Note that i < j should hold. We can show that an answer always exists. Example Input 2 4 1 1 1 1 4 4 3 1 2 Output 8 2 1 2 2 1 2 2 1 3 2 1 3 2 1 4 2 1 4 1 1 2 1 1 2 8 2 1 4 1 2 4 1 2 4 1 2 4 1 3 4 1 1 2 1 1 2 1 1 4 Note For the first sample test case one possible sequence of operations is as follows: 1. "2 1 2". Values of variables after performing the operation: [1, 0, 1, 1] 2. "2 1 2". Values of variables after performing the operation: [1, -1, 1, 1] 3. "2 1 3". Values of variables after performing the operation: [1, -1, 0, 1] 4. "2 1 3". Values of variables after performing the operation: [1, -1, -1, 1] 5. "2 1 4". Values of variables after performing the operation: [1, -1, -1, 0] 6. "2 1 4". Values of variables after performing the operation: [1, -1, -1, -1] 7. "1 1 2". Values of variables after performing the operation: [0, -1, -1, -1] 8. "1 1 2". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows: 1. "2 1 4". Values of variables after performing the operation: [4, 3, 1, -2] 2. "1 2 4". Values of variables after performing the operation: [4, 1, 1, -2] 3. "1 2 4". Values of variables after performing the operation: [4, -1, 1, -2] 4. "1 2 4". Values of variables after performing the operation: [4, -3, 1, -2] 5. "1 3 4". Values of variables after performing the operation: [4, -3, -1, -2] 6. "1 1 2". Values of variables after performing the operation: [1, -3, -1, -2] 7. "1 1 2". Values of variables after performing the operation: [-2, -3, -1, -2] 8. "1 1 4". Values of variables after performing the operation: [-4, -3, -1, -2]
def solve(n: int) -> None: arr = [2, 1, 2, 2, 1, 2] print(3 * n) for i in range(1, n + 1, 2): for j in arr: print(j, i, i + 1) t = int(input()) for _ in range(t): n = int(input()) input() solve(n)
{ "input": [ "2\n4\n1 1 1 1\n4\n4 3 1 2\n" ], "output": [ "\n8\n2 1 2\n2 1 2\n2 1 3\n2 1 3\n2 1 4\n2 1 4\n1 1 2\n1 1 2\n8\n2 1 4\n1 2 4\n1 2 4\n1 2 4\n1 3 4\n1 1 2\n1 1 2\n1 1 4\n" ] }
378
7
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number β€” the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously). Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him. Input The first line contains the single integer n (1 ≀ n ≀ 1000) β€” the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers β€” they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000. Output Print the single number β€” the number of amazing performances the coder has had during his whole history of participating in the contests. Examples Input 5 100 50 200 150 200 Output 2 Input 10 4664 6496 5814 7010 5762 5736 6944 4850 3698 7242 Output 4 Note In the first sample the performances number 2 and 3 are amazing. In the second sample the performances number 2, 4, 9 and 10 are amazing.
def fun(lst): s=l=lst[0] a=0 for i in lst[1:]: if i<s: s=i a+=1 if i>l: l=i a+=1 return a n=int(input()) lst=list(map(int,input().split())) print(fun(lst))
{ "input": [ "10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242\n", "5\n100 50 200 150 200\n" ], "output": [ "4\n", "2\n" ] }
379
9
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings. More formally, for each invited person the following conditions should be fulfilled: * all his friends should also be invited to the party; * the party shouldn't have any people he dislikes; * all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 ≀ i < p) are friends. Help the Beaver find the maximum number of acquaintances he can invite. Input The first line of input contains an integer n β€” the number of the Beaver's acquaintances. The second line contains an integer k <image> β€” the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi <image> β€” indices of people who form the i-th pair of friends. The next line contains an integer m <image> β€” the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once <image>. In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: * 2 ≀ n ≀ 14 The input limitations for getting 100 points are: * 2 ≀ n ≀ 2000 Output Output a single number β€” the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. Examples Input 9 8 1 2 1 3 2 3 4 5 6 7 7 8 8 9 9 6 2 1 6 7 9 Output 3 Note Let's have a look at the example. <image> Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
from sys import setrecursionlimit setrecursionlimit(10 ** 9) def dfs(g, col, st): global used used[st] = col for w in g[st]: if used[w] is False: dfs(g, col, w) n = int(input()) k = int(input()) g = [] used = [False] * n for i in range(n): g.append([]) for i in range(k): x, y = map(int, input().split()) g[x - 1].append(y - 1) g[y - 1].append(x - 1) cur = 0 for i in range(n): if used[i] is False: dfs(g, cur, i) cur += 1 k = int(input()) lst = [0] * n for i in range(k): x, y = map(int, input().split()) x -= 1 y -= 1 if used[x] == used[y]: lst[used[x]] = -1 for i in range(n): if lst[used[i]] != -1: lst[used[i]] += 1 print(max(0, max(lst)))
{ "input": [ "9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9\n" ], "output": [ "3" ] }
380
8
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.
f = lambda: [q != '-' for q in input()] n, k = map(int, input().split()) t = [(0, 0, f(), f())] def g(d, s, a, b): if d > n - 1: print('YES') exit() if not (a[d] or s > d): a[d] = 1 t.append((d, s, a, b)) while t: d, s, a, b = t.pop() g(d + 1, s + 1, a, b) g(d - 1, s + 1, a, b) g(d + k, s + 1, b, a) print('NO')
{ "input": [ "7 3\n---X--X\n-X--XX-\n", "6 2\n--X-X-\nX--XX-\n" ], "output": [ "YES\n", "NO\n" ] }
381
9
The Little Elephant has got a problem β€” somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements. Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself. Input The first line contains a single integer n (2 ≀ n ≀ 105) β€” the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, β€” array a. Note that the elements of the array are not necessarily distinct numbers. Output In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise. Examples Input 2 1 2 Output YES Input 3 3 2 1 Output YES Input 4 4 3 2 1 Output NO Note In the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES". In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES". In the third sample we can't sort the array in more than one swap operation, so the answer is "NO".
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 [str(x) for x in stdin.readline().split()] from sys import stdin n, a = int(input()), arr_inp(1) a1, c, ix = sorted(a.copy()), 0, 0 for i in range(n): if a[i] != a1[i]: if c == 0: c += 1 ix = i elif c > 2: exit(print('NO')) else: if a1[ix] == a[i]: c += 1 else: exit(print('NO')) print('YES')
{ "input": [ "3\n3 2 1\n", "4\n4 3 2 1\n", "2\n1 2\n" ], "output": [ "YES", "NO", "YES" ] }
382
8
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time. Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages. Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: 1. thread x is not updated (it has no new messages); 2. the list order 1, 2, ..., n changes to a1, a2, ..., an. Input The first line of input contains an integer n, the number of threads (1 ≀ n ≀ 105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1 ≀ ai ≀ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct. Output Output a single integer β€” the number of threads that surely contain a new message. Examples Input 5 5 2 1 3 4 Output 2 Input 3 1 2 3 Output 0 Input 4 4 3 2 1 Output 3 Note In the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages. In the second test case, there may be no new messages at all, since the thread order hasn't changed. In the third test case, only thread 1 can contain no new messages.
def main(): n = int(input()) aa = list(map(int, input().split())) m = aa[-1] for i in range(n - 2, -2, -1): a = aa[i] if m < a: break m = a print(i + 1) if __name__ == '__main__': main()
{ "input": [ "5\n5 2 1 3 4\n", "4\n4 3 2 1\n", "3\n1 2 3\n" ], "output": [ "2\n", "3\n", "0\n" ] }
383
8
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph() build a graph G with n vertices and 0 edges repeat swapped = false for i = 1 to n - 1 inclusive do: if a[i] > a[i + 1] then add an undirected edge in G between a[i] and a[i + 1] swap( a[i], a[i + 1] ) swapped = true end if end for until not swapped /* repeat the algorithm as long as swapped value is true. */ end procedure For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph. Input The first line of the input contains an integer n (2 ≀ n ≀ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n). Output Output a single integer β€” the answer to the problem. Examples Input 3 3 1 2 Output 2 Note Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
from bisect import bisect_right def answer(n,A): ans=[A[0]] for i in range(1,n): if ans[-1]<A[i]: ans.append(A[i]) else: index=bisect_right(ans,A[i]) ans[index]=A[i] return len(ans) n=int(input()) arr=list(map(int,input().split())) print(answer(n,arr))
{ "input": [ "3\n3 1 2\n" ], "output": [ "2\n" ] }
384
9
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 1 3 2\n3 5 4 6\n2 8 7\n", "2\n1 100\n2 1 10\n", "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000\n", "1\n9 2 8 6 5 9 4 7 1 3\n" ], "output": [ "18 18\n", "101 10\n", "7000 7000\n", "30 15\n" ] }
385
7
Two teams meet in The Game World Championship. Some scientists consider this game to be the most intellectually challenging game in the world. You are given two strings describing the teams' actions in the final battle. Figure out who became the champion. Input The input contains two strings of equal length (between 2 and 20 characters, inclusive). Each line describes the actions of one team. Output Output "TEAM 1 WINS" if the first team won, "TEAM 2 WINS" if the second team won, and "TIE" if there was a tie. Examples Input []()[]8&lt; 8&lt;[]()8&lt; Output TEAM 2 WINS Input 8&lt;8&lt;() []8&lt;[] Output TIE
def get(c): return "8[(".index(c) def win(d, e): return (get(d) + 1) % 3 == get(e) a = input() b = input() x = 0 y = 0 for i in range(0, len(a), 2): x += win(a[i], b[i]) y += win(b[i], a[i]) if x > y: print('TEAM 1 WINS') elif x < y: print('TEAM 2 WINS') else: print('TIE')
{ "input": [ "[]()[]8&lt;\n8&lt;[]()8&lt;\n", "8&lt;8&lt;()\n[]8&lt;[]\n" ], "output": [ "TEAM 2 WINS", "TEAM 1 WINS" ] }
386
8
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. <image> The park can be represented as a rectangular n Γ— m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time. Om Nom isn't yet sure where to start his walk from but he definitely wants: * to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); * to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries. Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell. Input The first line contains three integers n, m, k (2 ≀ n, m ≀ 2000; 0 ≀ k ≀ m(n - 1)). Each of the next n lines contains m characters β€” the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down). It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders. Output Print m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right. Examples Input 3 3 4 ... R.L R.U Output 0 2 2 Input 2 2 2 .. RL Output 1 1 Input 2 2 2 .. LR Output 0 0 Input 3 4 8 .... RRLL UUUU Output 1 3 3 1 Input 2 2 2 .. UU Output 0 0 Note Consider the first sample. The notes below show how the spider arrangement changes on the field over time: ... ... ..U ... R.L -> .*U -> L.R -> ... R.U .R. ..R ... Character "*" represents a cell that contains two spiders at the same time. * If Om Nom starts from the first cell of the first row, he won't see any spiders. * If he starts from the second cell, he will see two spiders at time 1. * If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2.
def ans(): n, m, k = map(int, input().split()) a = list([] for i in range(n)) s = [0]*m for i in range(n): a[i] = input() for i in range(1,n): for j in range(m): if i < m-j and a[i][j+i] == 'L': s[j]+=1 if i <= j and a[i][j-i] == 'R': s[j]+=1 if i+i < n and a[i+i][j] == 'U': s[j]+=1 print(*s) ans()
{ "input": [ "2 2 2\n..\nRL\n", "3 3 4\n...\nR.L\nR.U\n", "2 2 2\n..\nUU\n", "3 4 8\n....\nRRLL\nUUUU\n", "2 2 2\n..\nLR\n" ], "output": [ "1 1 ", "0 2 2 ", "0 0 ", "1 3 3 1 ", "0 0 " ] }
387
9
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days. Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity. Input The first line of input contains three space-separated integers n, k, d (1 ≀ n, d ≀ 1000; 1 ≀ k ≀ 109). Output If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k. Examples Input 3 2 2 Output 1 1 2 1 2 1 Input 3 2 1 Output -1 Note Note that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.
def f(t): i = -1 t[i] += 1 while t[i] > k: t[i] = 1 i -= 1 t[i] += 1 return list(map(str, t)) n, k, d = map(int, input().split()) if k ** d < n: print(-1) else: t = [1] * d t[-1] = 0 s = [f(t) for i in range(n)] print('\n'.join([' '.join(t) for t in zip(*s)]))
{ "input": [ "3 2 2\n", "3 2 1\n" ], "output": [ "1 2 1\n1 1 2\n", "-1\n" ] }
388
8
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l). Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≀ i ≀ j ≀ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler. Input The first line contains four positive space-separated integers n, l, x, y (2 ≀ n ≀ 105, 2 ≀ l ≀ 109, 1 ≀ x < y ≀ l) β€” the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin. Output In the first line print a single non-negative integer v β€” the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1, p2, ..., pv (0 ≀ pi ≀ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them. Examples Input 3 250 185 230 0 185 250 Output 1 230 Input 4 250 185 230 0 20 185 250 Output 0 Input 2 300 185 230 0 300 Output 2 185 230 Note In the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark. In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks. In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills.
n, l, x, y = map(int, input().split()) s = set(map(int, input().split())) def f(d): return any(i + d in s for i in s) def g(): for i in s: if i + x + y in s: return i + x return 0 def h(): for i in s: if i + y - x in s: if i - x >= 0: return i - x if i + y <= l: return i + y return 0 def e(d): print(1) print(d) if f(x): if f(y): print(0) else: e(y) elif f(y): e(x) else: z = g() if z: e(z) else: z = h() if z: e(z) else: print(2) print(x, y)
{ "input": [ "3 250 185 230\n0 185 250\n", "2 300 185 230\n0 300\n", "4 250 185 230\n0 20 185 250\n" ], "output": [ "1\n230\n", "2\n185 230\n", "0\n" ] }
389
8
Mr. Kitayuta has just bought an undirected graph consisting of 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 ≀ 100, 1 ≀ m ≀ 100), 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 ≀ 100), 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": [ "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", "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" ], "output": [ "1\n1\n1\n1\n2\n", "2\n1\n0\n" ] }
390
9
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen. Input The first line of input will have one integer k (1 ≀ k ≀ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≀ ci ≀ 1000). The total number of balls doesn't exceed 1000. Output A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007. Examples Input 3 2 2 1 Output 3 Input 4 1 2 3 4 Output 1680 Note In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 3 1 1 2 2 3 2 1 1 2 3
mod = 10 ** 9 + 7 import math def f(n): return math.factorial(n) k = int(input()) c = [int(input()) for i in range(k)] s, cnt = 0, 1 for i in c: cnt *= f(s + i - 1) // f(i - 1) // f(s) cnt %= mod s += i print(cnt)
{ "input": [ "3\n2\n2\n1\n", "4\n1\n2\n3\n4\n" ], "output": [ "3\n", "1680\n" ] }
391
8
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company! Input The first line of the input contains two space-separated integers, n and d (1 ≀ n ≀ 105, <image>) β€” the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively. Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≀ mi, si ≀ 109) β€” the amount of money and the friendship factor, respectively. Output Print the maximum total friendship factir that can be reached. Examples Input 4 5 75 5 0 100 150 20 75 1 Output 100 Input 5 100 0 7 11 32 99 10 46 8 87 54 Output 111 Note In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse. In the second sample test we can take all the friends.
def key_sort(x): return x[0] v = [] n, d = input().split() n = int(n) d = int(d) for i in range(n): x = input().split() v.append([int(x[0]), int(x[1])]) v.sort(key = key_sort) i = j = s = m = 0 while i < n and j < n: if v[j][0] - v[i][0] >= d: s -= v[i][1] i += 1 else: s += v[j][1] j +=1 if s > m: m = s print(m)
{ "input": [ "5 100\n0 7\n11 32\n99 10\n46 8\n87 54\n", "4 5\n75 5\n0 100\n150 20\n75 1\n" ], "output": [ "111", "100" ] }
392
7
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input contains two space-separated integers n and bx (1 ≀ n ≀ 10, 2 ≀ bx ≀ 40), where n is the number of digits in the bx-based representation of X. The second line contains n space-separated integers x1, x2, ..., xn (0 ≀ xi < bx) β€” the digits of X. They are given in the order from the most significant digit to the least significant one. The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≀ m ≀ 10, 2 ≀ by ≀ 40, bx β‰  by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≀ yi < by) β€” the digits of Y. There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system. Output Output a single character (quotes for clarity): * '<' if X < Y * '>' if X > Y * '=' if X = Y Examples Input 6 2 1 0 1 1 1 1 2 10 4 7 Output = Input 3 3 1 0 2 2 5 2 4 Output &lt; Input 7 16 15 15 4 0 0 7 10 7 9 4 8 0 3 1 5 0 Output &gt; Note In the first sample, X = 1011112 = 4710 = Y. In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y. In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
I=lambda:map(int,input().split()[::-1]) def f(): b,_=I() r,x=0,1 for i in I(): r+=i*x x*=b return r a=f()-f() print("<"if a<0 else ">="[a==0])
{ "input": [ "7 16\n15 15 4 0 0 7 10\n7 9\n4 8 0 3 1 5 0\n", "3 3\n1 0 2\n2 5\n2 4\n", "6 2\n1 0 1 1 1 1\n2 10\n4 7\n" ], "output": [ ">", "<", "=" ] }
393
7
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game. Input The first line of the input contains one integer n (1 ≀ n ≀ 90) β€” the number of interesting minutes. The second line contains n integers t1, t2, ..., tn (1 ≀ t1 < t2 < ... tn ≀ 90), given in the increasing order. Output Print the number of minutes Limak will watch the game. Examples Input 3 7 20 88 Output 35 Input 9 16 20 30 40 50 60 70 80 90 Output 15 Input 9 15 20 30 40 50 60 70 80 90 Output 90 Note In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes. In the second sample, the first 15 minutes are boring. In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
def f(l): for i in range(len(l)): if l[i]-l[i-1]>15: return l[i-1]+15 return 90 n=int(input()) l=list(map(int,input().split())) l.append(0) if 90 not in l: l.append(90) l.sort() print(f(l))
{ "input": [ "3\n7 20 88\n", "9\n15 20 30 40 50 60 70 80 90\n", "9\n16 20 30 40 50 60 70 80 90\n" ], "output": [ "35\n", "90\n", "15\n" ] }
394
8
A tree is an undirected connected graph without cycles. Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent). <image> For this rooted tree the array p is [2, 3, 3, 2]. Given a sequence p1, p2, ..., pn, one is able to restore a tree: 1. There must be exactly one index r that pr = r. A vertex r is a root of the tree. 2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi. A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid. You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them. Input The first line of the input contains an integer n (2 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n). Output In the first line print the minimum number of elements to change, in order to get a valid sequence. In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted. Examples Input 4 2 3 3 4 Output 1 2 3 4 4 Input 5 3 2 2 5 3 Output 0 3 2 2 5 3 Input 8 2 3 5 4 1 6 6 7 Output 2 2 3 7 8 1 6 6 7 Note In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. <image> In the second sample, the given sequence is already valid.
from collections import defaultdict from sys import stdin,setrecursionlimit setrecursionlimit(10**6) import threading def f(a): n=len(a) a=list(map(lambda s:s-1,a)) root=None for i in range(len(a)): if a[i]==i: root=i vis=[0]*(n) traitors=[] for i in range(0,n): cycle=-1 cur=i move=set() while vis[cur]==0: vis[cur]=1 move.add(cur) if a[cur] in move: cycle=cur cur=a[cur] if cycle!=-1: traitors.append(cycle) ans=len(traitors)-1 if root==None: a[traitors[0]]=traitors[0] root=traitors[0] ans+=1 for i in traitors: if i!=root: a[i]=root print(ans) a=list(map(lambda s:s+1,a)) return a n=input() a=list(map(int,input().strip().split())) print(*f(a))
{ "input": [ "5\n3 2 2 5 3\n", "8\n2 3 5 4 1 6 6 7\n", "4\n2 3 3 4\n" ], "output": [ "0\n3 2 2 5 3 ", "2 \n2 3 5 4 4 4 6 7 \n", "1 \n2 3 3 3 \n" ] }
395
8
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room. Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color. Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively. Output Print one integer β€” the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate. Examples Input 5 rbbrr Output 1 Input 5 bbbbb Output 2 Input 3 rbr Output 0 Note In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this. In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns. In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
n, s = int(input()), input() def f(x): a, b = s[::2].count(x[0]), s[1::2].count(x[1]) return min(a, b) + abs(a - b) print(min(f('rb'), f('br')))
{ "input": [ "5\nrbbrr\n", "5\nbbbbb\n", "3\nrbr\n" ], "output": [ "1\n", "2\n", "0\n" ] }
396
7
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, .... <image> The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time. Input The first line of input contains two integers a and b (1 ≀ a, b ≀ 100). The second line contains two integers c and d (1 ≀ c, d ≀ 100). Output Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time. Examples Input 20 2 9 19 Output 82 Input 2 1 16 12 Output -1 Note In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82. In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
def readInts(): return [int(x) for x in input().split()] a, b = readInts() c, d = readInts() l = set(a*i + b for i in range(100)) & set(c*i + d for i in range(100)) print(min(l) if l else -1)
{ "input": [ "20 2\n9 19\n", "2 1\n16 12\n" ], "output": [ "82\n", "-1\n" ] }
397
11
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market. This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible. Help Petya to determine maximum possible total cost. Input The first line contains two integers n and m (1 ≀ n ≀ 100000, 1 ≀ m ≀ 300000) β€” the number of Petya's souvenirs and total weight that he can carry to the market. Then n lines follow. ith line contains two integers wi and ci (1 ≀ wi ≀ 3, 1 ≀ ci ≀ 109) β€” the weight and the cost of ith souvenir. Output Print one number β€” maximum possible total cost of souvenirs that Petya can carry to the market. Examples Input 1 1 2 1 Output 0 Input 2 2 1 3 2 2 Output 3 Input 4 3 3 10 2 7 2 8 1 1 Output 10
def souvenier_calc(max_weight, weights, value): const = len(weights) ans = [-1061109567 for x in range(max_weight+1)] node = [(x, y) for x, y in zip(weights, value)] node = sorted(node, key=lambda x: x[1]/x[0], reverse=True) weights = [x[0] for x in node] value = [x[1] for x in node] sum = 0 sol = 0 ans[0] = 0 for i in range(const): sum += weights[i] if sum > max_weight: sum = max_weight down = max(weights[i], sum-3) for weight in range(sum, down-1, -1): ans[weight] = max(ans[weight], ans[weight-weights[i]]+value[i]) sol = max(sol, ans[weight]) return sol if __name__ == '__main__': N, M = map(int, input().split()) assert(N <= 10**5 and M <= 3*(10**5)), 'Out of range' weights = [] value = [] for i in range(N): x, y = map(int, input().split()) assert(x >= 1 and x <= 3), 'Out of range' assert(y >= 1 and y <= 10**9), 'Out of range' weights.append(x) value.append(y) print(souvenier_calc(M, weights, value))
{ "input": [ "4 3\n3 10\n2 7\n2 8\n1 1\n", "2 2\n1 3\n2 2\n", "1 1\n2 1\n" ], "output": [ "10\n", "3\n", "0\n" ] }
398
7
<image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
import sys input = sys.stdin.buffer.readline def gcd(a, b): if a > b: a, b = b, a if b % a==0: return a return gcd(b % a, a) def process(a, b): g = gcd(a, b) r = a//g s = b//g if g % r != 0: return 'No' g = g//r if g % s != 0: return 'No' G3 = g//s G = round(G3**(1/3)) cube = False for i in range(10): if (G-i)**3==G3 or (G+i)**3==G3: cube = True break if not cube: return 'No' return 'Yes' n = int(input()) for i in range(n): a, b = [int(x) for x in input().split()] sys.stdout.write(process(a, b)+'\n')
{ "input": [ "6\n2 4\n75 45\n8 8\n16 16\n247 994\n1000000000 1000000\n" ], "output": [ "Yes\nYes\nYes\nNo\nNo\nYes\n" ] }
399
8
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai. Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times). After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city. Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected. Input The first line contains three integers n, k and m (1 ≀ n ≀ 105, 2 ≀ k ≀ 109, 1 ≀ m ≀ 109). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 105), where ai is the number of city, person from which must take seat i in the bus. Output Output the number of remaining participants in the line. Examples Input 4 2 5 1 2 3 1 Output 12 Input 1 9 10 1 Output 1 Input 3 2 10 1 2 1 Output 0 Note In the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.
def main(): _, k, m = [int(x) for x in input().split()] a = [] last = ("-1", 0) a.append(last) for ai in input().split(): if last[0] == ai: last = (ai, last[1]+1) a[-1] = last else: last = (ai, 1) a.append(last) if last[1] == k: a.pop() last = a[-1] a.pop(0) s1 = 0 while len(a) > 0 and a[0][0] == a[-1][0]: if len(a) == 1: s = a[0][1] * m r1 = s % k if r1 == 0: print(s1 % k) else: print(r1 + s1) return join = a[0][1] + a[-1][1] if join < k: break elif join % k == 0: s1 += join a.pop() a.pop(0) else: s1 += (join // k) * k a[0] = (a[0][0], join % k) a.pop() break s = 0 for ai in a: s += ai[1] print(s*m + s1) if __name__ == "__main__": main()
{ "input": [ "4 2 5\n1 2 3 1\n", "1 9 10\n1\n", "3 2 10\n1 2 1\n" ], "output": [ "12\n", "1\n", "0\n" ] }