index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
200
7
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for a minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day? Input The first line contains three integers n, L and a (0 ≀ n ≀ 10^{5}, 1 ≀ L ≀ 10^{9}, 1 ≀ a ≀ L). The i-th of the next n lines contains two integers t_{i} and l_{i} (0 ≀ t_{i} ≀ L - 1, 1 ≀ l_{i} ≀ L). It is guaranteed that t_{i} + l_{i} ≀ t_{i + 1} and t_{n} + l_{n} ≀ L. Output Output one integer β€” the maximum number of breaks. Examples Input 2 11 3 0 1 1 1 Output 3 Input 0 5 2 Output 2 Input 1 3 2 1 2 Output 0 Note In the first sample Vasya can take 3 breaks starting after 2, 5 and 8 minutes after the beginning of the day. In the second sample Vasya can take 2 breaks starting after 0 and 2 minutes after the beginning of the day. In the third sample Vasya can't take any breaks.
def inp(): return map(int, input().split()) n, L, a = inp() count,time=0,0 for i in range(n): l, t = inp() diff=l-time if(diff>=a): count+=diff//a time=l+t if(L-time>=a): count+=(L-time)//a print(count)
{ "input": [ "2 11 3\n0 1\n1 1\n", "0 5 2\n", "1 3 2\n1 2\n" ], "output": [ "3\n", "2\n", "0\n" ] }
201
9
Recently, Masha was presented with a chessboard with a height of n and a width of m. The rows on the chessboard are numbered from 1 to n from bottom to top. The columns are numbered from 1 to m from left to right. Therefore, each cell can be specified with the coordinates (x,y), where x is the column number, and y is the row number (do not mix up). Let us call a rectangle with coordinates (a,b,c,d) a rectangle lower left point of which has coordinates (a,b), and the upper right one β€” (c,d). The chessboard is painted black and white as follows: <image> An example of a chessboard. Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat β€” they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle (x_1,y_1,x_2,y_2). Then after him Denis spilled black paint on the rectangle (x_3,y_3,x_4,y_4). To spill paint of color color onto a certain rectangle means that all the cells that belong to the given rectangle become color. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black). Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers! Input The first line contains a single integer t (1 ≀ t ≀ 10^3) β€” the number of test cases. Each of them is described in the following format: The first line contains two integers n and m (1 ≀ n,m ≀ 10^9) β€” the size of the board. The second line contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1 ≀ x_2 ≀ m, 1 ≀ y_1 ≀ y_2 ≀ n) β€” the coordinates of the rectangle, the white paint was spilled on. The third line contains four integers x_3, y_3, x_4, y_4 (1 ≀ x_3 ≀ x_4 ≀ m, 1 ≀ y_3 ≀ y_4 ≀ n) β€” the coordinates of the rectangle, the black paint was spilled on. Output Output t lines, each of which contains two numbers β€” the number of white and black cells after spilling paint, respectively. Example Input 5 2 2 1 1 2 2 1 1 2 2 3 4 2 2 3 2 3 1 4 3 1 5 1 1 5 1 3 1 5 1 4 4 1 1 4 2 1 3 4 4 3 4 1 2 4 2 2 1 3 3 Output 0 4 3 9 2 3 8 8 4 8 Note Explanation for examples: The first picture of each illustration shows how the field looked before the dyes were spilled. The second picture of each illustration shows how the field looked after Maxim spoiled white dye (the rectangle on which the dye was spilled is highlighted with red). The third picture in each illustration shows how the field looked after Denis spoiled black dye (the rectangle on which the dye was spilled is highlighted with red). In the first test, the paint on the field changed as follows: <image> In the second test, the paint on the field changed as follows: <image> In the third test, the paint on the field changed as follows: <image> In the fourth test, the paint on the field changed as follows: <image> In the fifth test, the paint on the field changed as follows: <image>
def count(x,y,p,q,color): if x>p or y>q: return 0 ret=(p-x+1)*(q-y+1)//2 if (p-x)%2==1 or (q-y)%2==1: return ret if color==(x+y)%2: return ret+1 else: return ret t=int(input()) for _ in range(t): n,m=map(int,input().split()) x1,y1,x2,y2=list(map(int,input().split())) x3,y3,x4,y4=list(map(int,input().split())) ret=count(1,1,n,m,0)+count(x1,y1,x2,y2,1)-count(x3,y3,x4,y4,0)-count(max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4),1) print(ret,n*m-ret)
{ "input": [ "5\n2 2\n1 1 2 2\n1 1 2 2\n3 4\n2 2 3 2\n3 1 4 3\n1 5\n1 1 5 1\n3 1 5 1\n4 4\n1 1 4 2\n1 3 4 4\n3 4\n1 2 4 2\n2 1 3 3\n" ], "output": [ "0 4\n3 9\n2 3\n8 8\n4 8\n" ] }
202
8
All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl, yr] of the seats numbers in this row, where yr - yl + 1 = M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say, <image> β€” the row and the seat numbers of the most "central" seat. Then the function value of seats remoteness from the hall center is <image>. If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program. Input The first line contains two integers N and K (1 ≀ N ≀ 1000, 1 ≀ K ≀ 99) β€” the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1, K] β€” requests to the program. Output Output N lines. In the i-th line output Β«-1Β» (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x, yl, yr. Separate the numbers with a space. Examples Input 2 1 1 1 Output 1 1 1 -1 Input 4 3 1 2 3 1 Output 2 2 2 1 1 2 3 1 3 2 1 1
n,k=map(int,input().split()) group=list(map(int,input().split())) available=[[k,1] for i in range(k+1)] center=(k+1)//2 def calc(center,row,col,num): end_col=col+num-1 distance=abs(center-row)*num if col>=center: distance+=(col-center)*num+(num-1)*num//2 elif end_col<=center: distance+=(center-end_col)*num+(num-1)*num//2 else: distance+=(center-col)*(center-col+1)//2+(end_col-center)*(end_col-center+1)//2 return distance for m in group: close,best_row,best_col=10**9,-1,-1 for row in range(1,k+1): col=0 if available[row][0]<m and k-available[row][1]+1<m: continue if available[row][0]==k: col=center-m//2 elif center-available[row][0]<=available[row][1]-center: col=available[row][0]-m+1 else: col=available[row][1] distance=calc(center,row,col,m) if distance<close: close=distance best_row=row best_col=col if close==10**9: print(-1) else: print(best_row,best_col,best_col+m-1) available[best_row][0]=min(available[best_row][0],best_col-1) available[best_row][1]=max(available[best_row][1],best_col+m)
{ "input": [ "4 3\n1 2 3 1\n", "2 1\n1 1\n" ], "output": [ "2 2 2\n1 1 2\n3 1 3\n2 1 1\n", "1 1 1\n-1\n" ] }
203
7
Everybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates. There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have k Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too. You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that k Chosen Ones would be selected by the Technogoblet. Input The first line contains three integers n, m and k (1 ≀ n ≀ 100, 1 ≀ m, k ≀ n) β€” the total number of students, the number of schools and the number of the Chosen Ones. The second line contains n different integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n), where p_i denotes the power of i-th student. The bigger the power, the stronger the student. The third line contains n integers s_1, s_2, …, s_n (1 ≀ s_i ≀ m), where s_i denotes the school the i-th student goes to. At least one student studies in each of the schools. The fourth line contains k different integers c_1, c_2, …, c_k (1 ≀ c_i ≀ n) β€” the id's of the Chosen Ones. Output Output a single integer β€” the minimal number of schools to be made up by Arkady so that k Chosen Ones would be selected by the Technogoblet. Examples Input 7 3 1 1 5 3 4 6 7 2 1 3 1 2 1 2 3 3 Output 1 Input 8 4 4 1 2 3 4 5 6 7 8 4 3 2 1 4 3 2 1 3 4 5 6 Output 2 Note In the first example there's just a single Chosen One with id 3. His power is equal to 3, but in the same school 1, there's a student with id 5 and power 6, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be 4) for the Chosen One, Technogoblet would select students with ids 2 (strongest in 3), 5 (strongest in 1), 6 (strongest in 2) and 3 (strongest in 4). In the second example, you can change the school of student 3 to the made-up 5 and the school of student 4 to the made-up 6. It will cause the Technogoblet to choose students 8, 7, 6, 5, 3 and 4.
def inpl(): return list(map(int, input().split())) from collections import defaultdict H = defaultdict(lambda: 0) N, M, K = inpl() P = inpl() S = inpl() C = inpl() for p, s in zip(P, S): H[s] = max(H[s], p) ans = 0 for c in C: if P[c-1] != H[S[c-1]]: ans += 1 print(ans)
{ "input": [ "8 4 4\n1 2 3 4 5 6 7 8\n4 3 2 1 4 3 2 1\n3 4 5 6\n", "7 3 1\n1 5 3 4 6 7 2\n1 3 1 2 1 2 3\n3\n" ], "output": [ "2\n", "1\n" ] }
204
9
You are given a permutation p of integers from 1 to n, where n is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: * take two indices i and j such that 2 β‹… |i - j| β‰₯ n and swap p_i and p_j. There is no need to minimize the number of operations, however you should use no more than 5 β‹… n operations. One can show that it is always possible to do that. Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5, n is even) β€” the length of the permutation. The second line contains n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) β€” the given permutation. Output On the first line print m (0 ≀ m ≀ 5 β‹… n) β€” the number of swaps to perform. Each of the following m lines should contain integers a_i, b_i (1 ≀ a_i, b_i ≀ n, |a_i - b_i| β‰₯ n/2) β€” the indices that should be swapped in the corresponding swap. Note that there is no need to minimize the number of operations. We can show that an answer always exists. Examples Input 2 2 1 Output 1 1 2 Input 4 3 4 1 2 Output 4 1 4 1 4 1 3 2 4 Input 6 2 5 3 1 4 6 Output 3 1 5 2 5 1 4 Note In the first example, when one swap elements on positions 1 and 2, the array becomes sorted. In the second example, pay attention that there is no need to minimize number of swaps. In the third example, after swapping elements on positions 1 and 5 the array becomes: [4, 5, 3, 1, 2, 6]. After swapping elements on positions 2 and 5 the array becomes [4, 2, 3, 1, 5, 6] and finally after swapping elements on positions 1 and 4 the array becomes sorted: [1, 2, 3, 4, 5, 6].
n = int(input()) l = [*map(int, input().split())] l = [i - 1 for i in l] pos = {} ans = [] for i, j in enumerate(l): pos[j] = i def swap(i, j): ans.append((pos[l[i]] + 1, pos[l[j]] + 1)) pos[l[i]], pos[l[j]] = pos[l[j]], pos[l[i]] l[i], l[j] = l[j], l[i] def solve(i): u = n - 1 if pos[i] < n // 2 else 0 v = 0 if pos[i] < n // 2 else n - 1 swap(pos[i], u) if abs(u - i) * 2 >= n: swap(u, i) else: swap(u, v) swap(v, i) for i in range(1, n - 1): if l[i] != i: solve(i) if l[0] != 0: swap(0, n - 1) print(len(ans)) print('\n'.join([' '.join(map(str, [*i])) for i in ans]))
{ "input": [ "2\n2 1\n", "4\n3 4 1 2\n", "6\n2 5 3 1 4 6\n" ], "output": [ "1\n1 2\n", "2\n1 3\n2 4\n", "5\n1 6\n2 6\n1 6\n1 5\n1 4\n" ] }
205
12
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from 1 to ⌊ (2n^2)/(9) βŒ‹ has to be written on the blackboard at least once. It is guaranteed that such an arrangement exists. Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of nodes. Each of the next n-1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree. Output Output n-1 lines, each of form u v x (0 ≀ x ≀ 10^6), which will mean that you wrote number x on the edge between u, v. Set of edges (u, v) has to coincide with the set of edges of the input graph, but you can output edges in any order. You can also output ends of edges in an order different from the order in input. Examples Input 3 2 3 2 1 Output 3 2 1 1 2 2 Input 4 2 4 2 3 2 1 Output 4 2 1 3 2 2 1 2 3 Input 5 1 2 1 3 1 4 2 5 Output 2 1 1 5 2 1 3 1 3 4 1 6 Note In the first example, distance between nodes 1 and 2 is equal to 2, between nodes 2 and 3 to 1, between 1 and 3 to 3. In the third example, numbers from 1 to 9 (inclusive) will be written on the blackboard, while we need just from 1 to 5 to pass the test.
import math n = int(input()) if n == 1: print() else: edge = [list(map(int, input().split())) for i in range(1, n) ] g = {} for x, y in edge: if x not in g: g[x] = [] if y not in g: g[y] = [] g[x].append(y) g[y].append(x) def find_centroid(g): p = {} size = {} p[1] = -1 Q = [1] i = 0 while i < len(Q): u = Q[i] for v in g[u]: if p[u] == v: continue p[v] = u Q.append(v) i+=1 for u in Q[::-1]: size[u] = 1 for v in g[u]: if p[u] == v: continue size[u] += size[v] cur = 1 n = size[cur] while True: max_ = n - size[cur] ind_ = p[cur] for v in g[cur]: if v == p[cur]: continue if size[v] > max_: max_ = size[v] ind_ = v if max_ <= n // 2: return cur cur = ind_ def find_center(g): d = {} d[1] = 0 Q = [(1, 0)] while len(Q) > 0: u, dis = Q.pop(0) for v in g[u]: if v not in d: d[v] = dis +1 Q.append((v, d[v])) max_length = -1 s = None for u, dis in d.items(): if dis > max_length: max_length = dis s = u d = {} pre = {} d[s] = 0 Q = [(s, 0)] while len(Q) > 0: u, dis = Q.pop(0) for v in g[u]: if v not in d: pre[v] = u d[v] = dis +1 Q.append((v, d[v])) max_length = -1 e = None for u, dis in d.items(): if dis > max_length: max_length = dis e = u route = [e] while pre[route[-1]] != s: route.append(pre[route[-1]]) print(route) return route[len(route) // 2] root = find_centroid(g) p = {} size = {} Q = [root] p[root] = -1 i = 0 while i < len(Q): u = Q[i] for v in g[u]: if p[u] == v: continue p[v] = u Q.append(v) i+=1 for u in Q[::-1]: size[u] = 1 for v in g[u]: if p[u] == v: continue size[u] += size[v] gr = [(u, size[u]) for u in g[root]] gr = sorted(gr, key=lambda x:x[1]) thres = math.ceil((n-1) / 3) sum_ = 0 gr1 = [] gr2 = [] i = 0 while sum_ < thres: gr1.append(gr[i][0]) sum_ += gr[i][1] i+=1 while i < len(gr): gr2.append(gr[i][0]) i+=1 def asign(u, W, ew): if size[u] == 1: return cur = 0 for v in g[u]: if v == p[u]: continue first = W[cur] ew.append((u, v, first)) W_ = [x - first for x in W[cur+1: cur+size[v]]] asign(v, W_, ew) cur+=size[v] a, b = 0, 0 for x in gr1: a += size[x] for x in gr2: b += size[x] arr_1 = [x for x in range(1, a+1)] arr_2 = [i*(a+1) for i in range(1, b+1)] ew = [] cur = 0 for u in gr1: first = arr_1[cur] ew.append((root, u, first)) W_ = [x - first for x in arr_1[cur+1:cur+size[u]]] cur += size[u] #print(u, W_) asign(u, W_, ew) cur = 0 for u in gr2: first = arr_2[cur] ew.append((root, u, first)) W_ = [x - first for x in arr_2[cur+1:cur+size[u]]] cur += size[u] #print(u, W_) asign(u, W_, ew) for u, v, w in ew: print('{} {} {}'.format(u, v, w))
{ "input": [ "4\n2 4\n2 3\n2 1\n", "3\n2 3\n2 1\n", "5\n1 2\n1 3\n1 4\n2 5\n" ], "output": [ "2 4 1\n2 3 2\n2 1 4\n", "2 3 1\n2 1 2\n", "1 2 1\n2 5 1\n1 3 3\n1 4 6\n" ] }
206
8
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ k), where a_i is the show, the episode of which will be shown in i-th day. The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately. How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows d (1 ≀ d ≀ n) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of d consecutive days in which all episodes belong to the purchased shows. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then t test case descriptions follow. The first line of each test case contains three integers n, k and d (1 ≀ n ≀ 100, 1 ≀ k ≀ 100, 1 ≀ d ≀ n). The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ k), where a_i is the show that is broadcasted on the i-th day. It is guaranteed that the sum of the values ​​of n for all test cases in the input does not exceed 100. Output Print t integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for d consecutive days. Please note that it is permissible that you will be able to watch more than d days in a row. Example Input 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 Output 2 1 4 5 Note In the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show 1 and on show 2. So the answer is two. In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show. In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows. In the fourth test case, you can buy subscriptions to shows 3,5,7,8,9, and you will be able to watch shows for the last eight days.
def main(): n, k, d = map(int, input().split()) l = list(map(int, input().split())) rez = d for i in range(n - d + 1): rez = min(rez, len(set(l[i:i+d]))) print(rez) t = int(input()) for i in range(t): main()
{ "input": [ "4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3\n" ], "output": [ "2\n1\n4\n5\n" ] }
207
10
The only difference between easy and hard versions is constraints. You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≀ r_i) and it covers all integer points j such that l_i ≀ j ≀ r_i. The integer point is called bad if it is covered by strictly more than k segments. Your task is to remove the minimum number of segments so that there are no bad points at all. Input The first line of the input contains two integers n and k (1 ≀ k ≀ n ≀ 200) β€” the number of segments and the maximum number of segments by which each integer point can be covered. The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ 200) β€” the endpoints of the i-th segment. Output In the first line print one integer m (0 ≀ m ≀ n) β€” the minimum number of segments you need to remove so that there are no bad points. In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≀ p_i ≀ n) β€” indices of segments you remove in any order. If there are multiple answers, you can print any of them. Examples Input 7 2 11 11 9 11 7 8 8 9 7 8 9 11 7 9 Output 3 1 4 7 Input 5 1 29 30 30 30 29 29 28 30 30 30 Output 3 1 2 4 Input 6 1 2 3 3 3 2 3 2 2 2 3 2 3 Output 4 1 3 5 6
n,k = map(int,input().split()) L = [list(map(int,input().split())) for i in range(n)] for i in range(n): L[i].append(i) L.sort(key=lambda x:x[1]) # print(L) def c(x): for i in range(x[0],x[1]+1): if T[i] >= k: return 0 return 1 ans = 0 A=[] T = [0] * 203 i = 0 t = 0 while i < n : if c(L[i]) == 1: for j in range(L[i][0], L[i][1]+1): T[j] += 1 t = L[i][0] else: A.append(L[i][2]+1) ans += 1 i += 1 # print(T) A.sort() print(ans) print(" ".join([str(i) for i in A]))
{ "input": [ "5 1\n29 30\n30 30\n29 29\n28 30\n30 30\n", "7 2\n11 11\n9 11\n7 8\n8 9\n7 8\n9 11\n7 9\n", "6 1\n2 3\n3 3\n2 3\n2 2\n2 3\n2 3\n" ], "output": [ "3\n4 1 5 ", "3\n7 4 6 ", "4\n1 3 5 6\n" ] }
208
7
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process. You are standing in the m-th position in the line. Before the process starts, you may choose up to k different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded. Suppose that you're doing your choices optimally. What is the greatest integer x such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to x? Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains three space-separated integers n, m and k (1 ≀ m ≀ n ≀ 3500, 0 ≀ k ≀ n - 1) β€” the number of elements in the array, your position in line and the number of people whose choices you can fix. The second line of each test case contains n positive integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9) β€” elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 3500. Output For each test case, print the largest integer x such that you can guarantee to obtain at least x. Example Input 4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 Output 8 4 1 1 Note In the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element. * the first person will take the last element (5) because he or she was forced by you to take the last element. After this turn the remaining array will be [2, 9, 2, 3, 8]; * the second person will take the first element (2) because he or she was forced by you to take the first element. After this turn the remaining array will be [9, 2, 3, 8]; * if the third person will choose to take the first element (9), at your turn the remaining array will be [2, 3, 8] and you will take 8 (the last element); * if the third person will choose to take the last element (8), at your turn the remaining array will be [9, 2, 3] and you will take 9 (the first element). Thus, this strategy guarantees to end up with at least 8. We can prove that there is no strategy that guarantees to end up with at least 9. Hence, the answer is 8. In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 4.
from sys import stdin, stderr readline = stdin.buffer.readline def rl(): return [int(w) for w in readline().split()] t, = rl() for _ in range(t): n,m,k = rl() a = rl() k = min(k, m-1) print(max( min(max(a[x+y], a[n-m+x+y]) for y in range(m-k)) for x in range(k+1) ))
{ "input": [ "4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\n" ], "output": [ "8\n4\n1\n1\n" ] }
209
9
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move the figure to cells: * (i - 1, j - 1); * (i - 1, j); * (i - 1, j + 1); * (i, j - 1); * (i, j + 1); * (i + 1, j - 1); * (i + 1, j); * (i + 1, j + 1); Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell. Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. n^2-1 cells should contain 0 figures and one cell should contain n^2 figures). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 200) β€” the number of test cases. Then t test cases follow. The only line of the test case contains one integer n (1 ≀ n < 5 β‹… 10^5) β€” the size of the board. It is guaranteed that n is odd (not divisible by 2). It is guaranteed that the sum of n over all test cases does not exceed 5 β‹… 10^5 (βˆ‘ n ≀ 5 β‹… 10^5). Output For each test case print the answer β€” the minimum number of moves needed to get all the figures into one cell. Example Input 3 1 5 499993 Output 0 40 41664916690999888
def solve(): n=int(input()) return int((n-1)*n*(n+1)/3) T=int(input()) for t in range(T): print(solve())
{ "input": [ "3\n1\n5\n499993\n" ], "output": [ "0\n40\n41664916690999888\n" ] }
210
8
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string s and delete them. For example, if s = 1011001 then the following moves are possible: 1. delete s_1 and s_2: 1011001 β†’ 11001; 2. delete s_2 and s_3: 1011001 β†’ 11001; 3. delete s_4 and s_5: 1011001 β†’ 10101; 4. delete s_6 and s_7: 1011001 β†’ 10110. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win. Input First line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Only line of each test case contains one string s (1 ≀ |s| ≀ 100), consisting of only characters 0 and 1. Output For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register. Example Input 3 01 1111 0011 Output DA NET NET Note In the first test case after Alice's move string s become empty and Bob can not make any move. In the second test case Alice can not make any move initially. In the third test case after Alice's move string s turn into 01. Then, after Bob's move string s become empty and Alice can not make any move.
def f(n): if min(n.count("1"),n.count("0")) %2==0: print("NET") else: print("DA") x = int(input()) for i in range(x): n = input() f(n)
{ "input": [ "3\n01\n1111\n0011\n" ], "output": [ "DA\nNET\nNET\n" ] }
211
7
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of a equal to zero. Input The first line contains one integer n (1 ≀ n ≀ 100 000): the number of elements of the array. The second line contains n elements of an array a separated by spaces: a_1, a_2, ..., a_n (-10^9 ≀ a_i ≀ 10^9). Output The output should contain six lines representing three operations. For each operation, print two lines: * The first line contains two integers l, r (1 ≀ l ≀ r ≀ n): the bounds of the selected segment. * The second line contains r-l+1 integers b_l, b_{l+1}, ..., b_r (-10^{18} ≀ b_i ≀ 10^{18}): the numbers to add to a_l, a_{l+1}, …, a_r, respectively; b_i should be divisible by r - l + 1. Example Input 4 1 3 2 4 Output 1 1 -1 3 4 4 2 2 4 -3 -6 -6
def mulLen(): n = int(input()) a = list(map(int, input().split())) print(1, 1) print(-a[0]) a[0] = 0 if n == 1: print(1,1) print(0) print(1,1) print(0) else: print(2,n) for i in a[1:]: print(i*(n-1), end=" ") print() print(1, n) for i in a: print(-n*i, end=" ") mulLen()
{ "input": [ "4\n1 3 2 4\n" ], "output": [ "1 1\n-1\n2 4\n9 6 12\n1 4\n0 -12 -8 -16\n" ] }
212
9
In the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai β€” how many people who are taller than him/her and stand in queue in front of him. After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order. When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number ai. Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers hi β€” the heights of people in the queue, so that the numbers ai are correct. Input The first input line contains integer n β€” the number of people in the queue (1 ≀ n ≀ 3000). Then n lines contain descriptions of the people as "namei ai" (one description on one line), where namei is a non-empty string consisting of lowercase Latin letters whose length does not exceed 10 characters (the i-th person's name), ai is an integer (0 ≀ ai ≀ n - 1), that represents the number of people who are higher and stand in the queue in front of person i. It is guaranteed that all names are different. Output If there's no acceptable order of the people in the queue, print the single line containing "-1" without the quotes. Otherwise, print in n lines the people as "namei hi", where hi is the integer from 1 to 109 (inclusive), the possible height of a man whose name is namei. Print the people in the order in which they stand in the queue, starting from the head of the queue and moving to its tail. Numbers hi are not necessarily unique. Examples Input 4 a 0 b 2 c 0 d 0 Output a 150 c 170 d 180 b 160 Input 4 vasya 0 petya 1 manya 3 dunay 3 Output -1
n = int(input()) a = [] for _ in range(n): name, num = input().split() a.append([name, int(num)]) a = sorted(a, key = lambda x: x[1]) h = [] def solve(a): h = [] for name, num in a: if num > len(h): return False, -1 if num == 0: if len(h) == 0: h.append([name, 1]) else: h.append([name, h[-1][1]+1]) else: h = h[:-num] + [[name, h[-num][1]]] + h[-num:] for h_ in h[-num:]: h_[1] += 1 h = {name: h_ for name, h_ in h} for x in a: x[1] = h[x[0]] return True, a flg, ans = solve(a) if flg == False: print(ans) else: for name, h in ans: print(name+' '+str(h)) #4 #a 0 #b 2 #c 0 #d 0
{ "input": [ "4\nvasya 0\npetya 1\nmanya 3\ndunay 3\n", "4\na 0\nb 2\nc 0\nd 0\n" ], "output": [ "-1\n", "a 1\nc 3\nd 4\nb 2\n" ] }
213
9
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side. Artem wants to increment the values in some cells by one to make a good. More formally, find a good matrix b that satisfies the following condition β€” * For all valid (i,j), either b_{i,j} = a_{i,j} or b_{i,j} = a_{i,j}+1. For the constraints of this problem, it can be shown that such a matrix b always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10). Description of the test cases follows. The first line of each test case contains two integers n, m (1 ≀ n ≀ 100, 1 ≀ m ≀ 100) β€” the number of rows and columns, respectively. The following n lines each contain m integers. The j-th integer in the i-th line is a_{i,j} (1 ≀ a_{i,j} ≀ 10^9). Output For each case, output n lines each containing m integers. The j-th integer in the i-th line is b_{i,j}. Example Input 3 3 2 1 2 4 5 7 8 2 2 1 1 3 3 2 2 1 3 2 2 Output 1 2 5 6 7 8 2 1 4 3 2 4 3 2 Note In all the cases, you can verify that no two adjacent cells have the same value and that b is the same as a with some values incremented by one.
def solve(n, m): for i in range(n): row = list(map(int, input().split())) for j in range(m): if (row[j]+i+j) % 2: row[j] += 1 print(*row) t = int(input()) for i in range(t): n, m = map(int, input().split()) solve(n, m)
{ "input": [ "3\n3 2\n1 2\n4 5\n7 8\n2 2\n1 1\n3 3\n2 2\n1 3\n2 2\n" ], "output": [ "2 3\n5 6\n8 9\n2 1\n3 4\n2 3\n3 2\n" ] }
214
8
You are given an array [a_1, a_2, ..., a_n] such that 1 ≀ a_i ≀ 10^9. Let S be the sum of all elements of the array a. Let's call an array b of n integers beautiful if: * 1 ≀ b_i ≀ 10^9 for each i from 1 to n; * for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or b_{i + 1} divides b_i (or both); * 2 βˆ‘ _{i = 1}^{n} |a_i - b_i| ≀ S. Your task is to find any beautiful array. It can be shown that at least one beautiful array always exists. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (2 ≀ n ≀ 50). The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). Output For each test case, print the beautiful array b_1, b_2, ..., b_n (1 ≀ b_i ≀ 10^9) on a separate line. It can be shown that at least one beautiful array exists under these circumstances. If there are multiple answers, print any of them. Example Input 4 5 1 2 3 4 5 2 4 6 2 1 1000000000 6 3 4 8 1 2 3 Output 3 3 3 3 3 3 6 1 1000000000 4 4 8 1 3 3
#Created by Pradeep import math def solve(): n=int(input()) nrr=list(map(int, input().split())) for i in nrr: p=int(math.log2(i)) ans=2**p print(ans, end=' ') for _ in range(int(input())): solve()
{ "input": [ "4\n5\n1 2 3 4 5\n2\n4 6\n2\n1 1000000000\n6\n3 4 8 1 2 3\n" ], "output": [ "\n3 3 3 3 3\n3 6\n1 1000000000\n4 4 8 1 3 3\n" ] }
215
8
The princess is going to escape the dragon's cave, and she needs to plan it carefully. The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend f hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning. The princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is c miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off. Input The input data contains integers vp, vd, t, f and c, one per line (1 ≀ vp, vd ≀ 100, 1 ≀ t, f ≀ 10, 1 ≀ c ≀ 1000). Output Output the minimal number of bijous required for the escape to succeed. Examples Input 1 2 1 1 10 Output 2 Input 1 2 1 1 8 Output 1 Note In the first case one hour after the escape the dragon will discover it, and the princess will be 1 mile away from the cave. In two hours the dragon will overtake the princess 2 miles away from the cave, and she will need to drop the first bijou. Return to the cave and fixing the treasury will take the dragon two more hours; meanwhile the princess will be 4 miles away from the cave. Next time the dragon will overtake the princess 8 miles away from the cave, and she will need the second bijou, but after this she will reach the castle without any further trouble. The second case is similar to the first one, but the second time the dragon overtakes the princess when she has reached the castle, and she won't need the second bijou.
def main(): vp, vd, t, f, c = [int(input()) for x in range(5)] p, d, count = t * vp, 0, 0 while (p < c) and (vd > vp): p = ((p / (vd - vp)) * vd) if p < c: count += 1 p += ((p / vd) * vp) + (f * vp) print(count) main()
{ "input": [ "1\n2\n1\n1\n10\n", "1\n2\n1\n1\n8\n" ], "output": [ "2\n", "1\n" ] }
216
10
Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store β€” "PriceFixed". Here are some rules of that store: * The store has an infinite number of items of every product. * All products have the same price: 2 rubles per item. * For every product i there is a discount for experienced buyers: if you buy b_i items of products (of any type, not necessarily type i), then for all future purchases of the i-th product there is a 50\% discount (so you can buy an item of the i-th product for 1 ruble!). Lena needs to buy n products: she must purchase at least a_i items of the i-th product. Help Lena to calculate the minimum amount of money she needs to spend if she optimally chooses the order of purchasing. Note that if she wants, she can buy more items of some product than needed. Input The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of products. Each of next n lines contains a product description. Each description consists of two integers a_i and b_i (1 ≀ a_i ≀ 10^{14}, 1 ≀ b_i ≀ 10^{14}) β€” the required number of the i-th product and how many products you need to buy to get the discount on the i-th product. The sum of all a_i does not exceed 10^{14}. Output Output the minimum sum that Lena needs to make all purchases. Examples Input 3 3 4 1 3 1 5 Output 8 Input 5 2 7 2 8 1 2 2 4 1 8 Output 12 Note In the first example, Lena can purchase the products in the following way: 1. one item of product 3 for 2 rubles, 2. one item of product 1 for 2 rubles, 3. one item of product 1 for 2 rubles, 4. one item of product 2 for 1 ruble (she can use the discount because 3 items are already purchased), 5. one item of product 1 for 1 ruble (she can use the discount because 4 items are already purchased). In total, she spends 8 rubles. It can be proved that it is impossible to spend less. In the second example Lena can purchase the products in the following way: 1. one item of product 1 for 2 rubles, 2. two items of product 2 for 2 rubles for each, 3. one item of product 5 for 2 rubles, 4. one item of product 3 for 1 ruble, 5. two items of product 4 for 1 ruble for each, 6. one item of product 1 for 1 ruble. In total, she spends 12 rubles.
# stdin = open('testdata.txt') # def input(): # return stdin.readline().strip() n = int(input()) a = [""]*n ans = 0 sm=0 for i in range(n): g,h = [int(x) for x in input().split()] a[i] = [h,g] sm+=g a.sort() for i in range(n-1,-1,-1): x = a[i] k = min(x[0],sm) ans += min(sm - ans - k,x[1]) print(sm*2-ans)
{ "input": [ "5\n2 7\n2 8\n1 2\n2 4\n1 8\n", "3\n3 4\n1 3\n1 5\n" ], "output": [ "12\n", "8\n" ] }
217
7
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place. Your task is to count what number of teams from the given list shared the k-th place. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≀ pi, ti ≀ 50) β€” the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. Output In the only line print the sought number of teams that got the k-th place in the final results' table. Examples Input 7 2 4 10 4 10 4 10 3 20 2 1 2 1 1 10 Output 3 Input 5 4 3 1 3 1 5 3 3 1 3 1 Output 4 Note The final results' table for the first sample is: * 1-3 places β€” 4 solved problems, the penalty time equals 10 * 4 place β€” 3 solved problems, the penalty time equals 20 * 5-6 places β€” 2 solved problems, the penalty time equals 1 * 7 place β€” 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams. The final table for the second sample is: * 1 place β€” 5 solved problems, the penalty time equals 3 * 2-5 places β€” 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams.
def main(): n,k=[int(i) for i in input().split()] l=[] for i in range(n): l.append([int(i) for i in input().split()]) l.sort(key=lambda x : (-x[0],x[1])) print(l.count(l[k-1])) return 0 if __name__ == '__main__': main()
{ "input": [ "5 4\n3 1\n3 1\n5 3\n3 1\n3 1\n", "7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10\n" ], "output": [ "4\n", "3\n" ] }
218
9
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≀ k ≀ 105) β€” the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≀ n ≀ 100) β€” the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
# https://codeforces.com/contest/232/problem/A # WA def f_3(n): return n * (n-1) * (n-2) // 6 def f_2(n): return n * (n-1) // 2 a_3 = [f_3(i) for i in range(100)] a_2 = [f_2(i) for i in range(100)] def find_2(x, a): arr = [] cur = len(a) - 1 while x > 0: while x < a[cur]: cur -= 1 arr.append(cur) x -= a[cur] return arr def find_3(x, a): cur = len(a) - 1 while x < a[cur]: cur -= 1 x -= a[cur] return cur, x def build(x): base, remain = find_3(x, a_3) arr = find_2(remain, a_2) n = base #print(base, arr) if len(arr) > 0: n += len(arr) m = [[0]*n for _ in range(n)] for i in range(base): for j in range(base): if i == j: continue m[i][j] = 1 m[j][i] = 1 for i, x in enumerate(arr): for j in range(x): m[base+i][j] = 1 m[j][base+i] = 1 return m def pr(m): for i in range(len(m)): print(''.join([str(x) for x in m[i]])) k = int(input()) m = build(k) print(len(m)) pr(m)
{ "input": [ "10\n", "1\n" ], "output": [ "5\n01111\n10111\n11011\n11101\n11110\n", "3\n011\n101\n110\n" ] }
219
8
Little Elephant loves magic squares very much. A magic square is a 3 Γ— 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15. <image> The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 105. Help the Little Elephant, restore the original magic square, given the Elephant's notes. Input The first three lines of the input contain the Little Elephant's notes. The first line contains elements of the first row of the magic square. The second line contains the elements of the second row, the third line is for the third row. The main diagonal elements that have been forgotten by the Elephant are represented by zeroes. It is guaranteed that the notes contain exactly three zeroes and they are all located on the main diagonal. It is guaranteed that all positive numbers in the table do not exceed 105. Output Print three lines, in each line print three integers β€” the Little Elephant's magic square. If there are multiple magic squares, you are allowed to print any of them. Note that all numbers you print must be positive and not exceed 105. It is guaranteed that there exists at least one magic square that meets the conditions. Examples Input 0 1 1 1 0 1 1 1 0 Output 1 1 1 1 1 1 1 1 1 Input 0 3 6 5 0 5 4 7 0 Output 6 3 6 5 5 5 4 7 4
def mi(): return map(int, input().split()) q,w,e = mi() a,s,d = mi() z,x,c = mi() q = int((a+2*d-w)/2) s = e+d-q c = e+s+z-q-s print (q, w, e) print (a, s, d) print (z, x, c)
{ "input": [ "0 1 1\n1 0 1\n1 1 0\n", "0 3 6\n5 0 5\n4 7 0\n" ], "output": [ "1 1 1\n1 1 1\n1 1 1\n", "6 3 6\n5 5 5\n4 7 4\n" ] }
220
8
The Bitlandians are quite weird people. They have very peculiar customs. As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work. The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000. Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500. Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of eggs. Next n lines contain two integers ai and gi each (0 ≀ ai, gi ≀ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg. Output If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa - Sg| ≀ 500. If there are several solutions, you are allowed to print any of them. Examples Input 2 1 999 999 1 Output AG Input 3 400 600 400 600 400 600 Output AGA
from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) from math import pi n=it() su=0 s=[] for i in range(n): a,g=mp() if su+a<=500: su+=a s+=["A"] else: su-=g s+=["G"] print(''.join(s))
{ "input": [ "2\n1 999\n999 1\n", "3\n400 600\n400 600\n400 600\n" ], "output": [ "AG\n", "AGA\n" ] }
221
7
Unfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4. Vasya has a set of k distinct non-negative integers d1, d2, ..., dk. Vasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner? Input The first input line contains integer k (1 ≀ k ≀ 100) β€” the number of integers. The second line contains k distinct space-separated integers d1, d2, ..., dk (0 ≀ di ≀ 100). Output In the first line print a single integer n the maximum number of the chosen integers. In the second line print n distinct non-negative integers β€” the required integers. If there are multiple solutions, print any of them. You can print the numbers in any order. Examples Input 4 100 10 1 0 Output 4 0 1 10 100 Input 3 2 70 3 Output 2 2 70
def fn(a,b): (a,b)=((3-len(a))*'0'+a),((3-len(b))*'0'+b) for i in range(3): if a[i]!='0' and b[i]!='0':return False return True n=int(input()) a=list(map(str, input().split())) ans1=[] temp=[] ans2=0 for i in range(n): temp=[a[i]] for j in range(n): if fn(a[i],a[j]) and a[i]!=a[j]: c=0 for k in temp: if fn(k,a[j]):c+=1 if c==len(temp):temp.append(a[j]) if len(temp)>ans2: ans1=temp ans2=len(temp) print(ans2) print(' '.join(ans1))
{ "input": [ "4\n100 10 1 0\n", "3\n2 70 3\n" ], "output": [ "4\n100 10 1 0\n", "2\n2 70\n" ] }
222
7
β€” Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? β€” Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees. Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai β€” some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly! The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: * The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; * the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; * and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart? Input The first line contains a single integer n β€” the initial number of trees in the woodland belt, 2 ≀ n. The second line contains space-separated integers ai β€” the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value. * to get 30 points, you need to solve the problem with constraints: n ≀ 100 (subproblem A1); * to get 100 points, you need to solve the problem with constraints: n ≀ 3Β·105 (subproblems A1+A2). Output In the first line print two integers β€” the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k. In the next line print k integers β€” the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right. If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal. Examples Input 5 1 2 3 1 2 Output 8 1 1 Input 5 1 -2 3 1 -2 Output 5 2 2 5
def main(): n, aa = int(input()), list(map(int, input().split())) partialsum, s, d, ranges = [0] * n, 0, {}, [] for i, a in enumerate(aa): if a > 0: s += a partialsum[i] = s if a in d: d[a].append(i) else: d[a] = [i] ranges = [] for a, l in d.items(): lo, hi = l[0], l[-1] if lo < hi: ranges.append((partialsum[hi - 1] - partialsum[lo] + a * 2, lo, hi)) s, lo, hi = max(ranges) res = list(range(1, lo + 1)) for i in range(lo + 1, hi): if aa[i] < 0: res.append(i + 1) res.extend(range(hi + 2, n + 1)) print(s, len(res)) print(" ".join(map(str, res))) if __name__ == '__main__': main()
{ "input": [ "5\n1 2 3 1 2\n", "5\n1 -2 3 1 -2\n" ], "output": [ "8 1\n1 ", "5 2\n2 5 " ] }
223
7
Pavel loves grid mazes. A grid maze is an n Γ— m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him. Input The first line contains three integers n, m, k (1 ≀ n, m ≀ 500, 0 ≀ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze. Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall. Output Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them. Examples Input 3 4 2 #..# ..#. #... Output #.X# X.#. #... Input 5 4 5 #... #.#. .#.. ...# .#.# Output #XXX #X#. X#.. ...# .#.#
from collections import defaultdict, deque def helper(row, col): queue = deque([(row, col)]) visited = {(row, col)} while queue: r, c = queue.popleft() for x, y in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]: if 0 <= x < n and 0 <= y < m and grid[x][y] == '.' and (x, y) not in visited: queue.append((x, y)) visited.add((x, y)) if len(visited) > s-k: grid[x][y] = 'X' n, m, k = map(int, input().split()) grid = [] s = 0 for i in range(n): grid.append(list(input())) for j in range(m): if grid[i][j] == '.': s += 1 row, col = i, j if k: helper(row, col) for i in range(n): print(''.join(grid[i]))
{ "input": [ "3 4 2\n#..#\n..#.\n#...\n", "5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n" ], "output": [ "#..#\n..#X\n#..X\n", "#...\n#.#.\nX#..\nXX.#\nX#X#\n" ] }
224
9
User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. 1. At first, the score is 0. 2. For each block of contiguous "o"s with length x the score increases by x2. 3. For each block of contiguous "x"s with length y the score decreases by y2. For example, if a = 6, b = 3 and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals 22 - 12 + 32 - 22 + 12 = 9. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o". User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards. Input The first line contains two space-separated integers a and b (0 ≀ a, b ≀ 105; a + b β‰₯ 1) β€” the number of "o" cards and the number of "x" cards. Output In the first line print a single integer v β€” the maximum score that ainta can obtain. In the second line print a + b characters describing the deck. If the k-th card of the deck contains "o", the k-th character must be "o". If the k-th card of the deck contains "x", the k-th character must be "x". The number of "o" characters must be equal to a, and the number of "x " characters must be equal to b. If there are many ways to maximize v, print any. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 2 3 Output -1 xoxox Input 4 0 Output 16 oooo Input 0 4 Output -16 xxxx
a,b=map(int,input().split()) def sqr(x): return x*x def work( num, flag=0 ): ans=sqr(a-num+1)+num-1 could = min(b, num+1) cc=b//could res=b%could ans-=res * sqr(cc+1) + (could-res)*sqr(cc) if flag: print(ans) list='' res2=could-res if could==num+1: list+='x'*cc res2-=1 ta=a list+='o'*(a-num+1) ta-=a-num+1 while ta>0: u=cc+int(res>0) if res>0: res-=1 else: res2-=1 list+='x'*u list+='o' ta-=1 if res>0 or res2>0: list+='x'*(cc+int(res>0)) print(str(list)) return ans if a==0: print(-sqr(b)) print('x'*b) elif b==0: print(sqr(a)) print('o'*a) else: now=1 for i in range(1,a+1): if i-1<=b and work(i)>work(now): now=i work(now,1)
{ "input": [ "0 4\n", "2 3\n", "4 0\n" ], "output": [ "-16\nxxxx\n", "-1\nxxoox\n", "16\noooo\n" ] }
225
10
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!' The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects? Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting. Input The first line contains integers n and p (3 ≀ n ≀ 3Β·105; 0 ≀ p ≀ n) β€” the number of coders in the F company and the minimum number of agreed people. Each of the next n lines contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of coders named by the i-th coder. It is guaranteed that xi β‰  i, yi β‰  i, xi β‰  yi. Output Print a single integer β€” the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) and (2, 1) are considered identical. Examples Input 4 2 2 3 1 4 1 4 2 1 Output 6 Input 8 6 5 6 5 7 5 8 6 2 2 1 7 3 1 3 1 4 Output 1
from collections import defaultdict from bisect import bisect_left as lower import sys input = sys.stdin.readline def put(): return map(int, input().split()) try: n,m = put() cnt, mp, ans = [0]*n, defaultdict(), [0]*n for _ in range(n): x,y = put() x,y = x-1,y-1 key = (min(x,y), max(x,y)) if key in mp: mp[key]+=1 else: mp[key]=1 cnt[x]+=1 cnt[y]+=1 except: print('lol') for (x,y),val in mp.items(): if cnt[x]+cnt[y]>= m and cnt[x]+cnt[y]-val<m: ans[x]-=1 ans[y]-=1 scnt = cnt.copy() scnt.sort() for i in range(n): ans[i]+= n-lower(scnt, m-cnt[i]) if 2*cnt[i]>=m: ans[i]-=1 print(sum(ans)//2)
{ "input": [ "8 6\n5 6\n5 7\n5 8\n6 2\n2 1\n7 3\n1 3\n1 4\n", "4 2\n2 3\n1 4\n1 4\n2 1\n" ], "output": [ "1\n", "6\n" ] }
226
8
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team. At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix data structures well. Bizon Senior loves suffix automaton. By applying it once to a string, he can remove from this string any single character. Bizon Middle knows suffix array well. By applying it once to a string, he can swap any two characters of this string. The guys do not know anything about the suffix tree, but it can help them do much more. Bizon the Champion wonders whether the "Bizons" can solve the problem. Perhaps, the solution do not require both data structures. Find out whether the guys can solve the problem and if they can, how do they do it? Can they solve it either only with use of suffix automaton or only with use of suffix array or they need both structures? Note that any structure may be used an unlimited number of times, the structures may be used in any order. Input The first line contains a non-empty word s. The second line contains a non-empty word t. Words s and t are different. Each word consists only of lowercase English letters. Each word contains at most 100 letters. Output In the single line print the answer to the problem. Print "need tree" (without the quotes) if word s cannot be transformed into word t even with use of both suffix array and suffix automaton. Print "automaton" (without the quotes) if you need only the suffix automaton to solve the problem. Print "array" (without the quotes) if you need only the suffix array to solve the problem. Print "both" (without the quotes), if you need both data structures to solve the problem. It's guaranteed that if you can solve the problem only with use of suffix array, then it is impossible to solve it only with use of suffix automaton. This is also true for suffix automaton. Examples Input automaton tomat Output automaton Input array arary Output array Input both hot Output both Input need tree Output need tree Note In the third sample you can act like that: first transform "both" into "oth" by removing the first character using the suffix automaton and then make two swaps of the string using the suffix array and get "hot".
def issub(a,b): i=0 for ch in a: if i<len(b) and b[i]==ch: i+=1 return i==len(b) a,b=input(),input() sa,sb=sorted(a),sorted(b) if issub(a,b): print('automaton') elif sa==sb: print('array') elif issub(sa,sb): print('both') else: print('need tree')
{ "input": [ "need\ntree\n", "automaton\ntomat\n", "array\narary\n", "both\nhot\n" ], "output": [ "need tree\n", "automaton\n", "array\n", "both\n" ] }
227
9
Today there is going to be an unusual performance at the circus β€” hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. Input The first line contains number n (2 ≀ n ≀ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. Output Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. Examples Input 3 HTH Output 0 Input 9 HTHTHTHHT Output 2 Note In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then β€” the tiger in position 9 with the hamster in position 7.
def f(k): res=0 if k=='T': res=1 return(res) n=int(input()) s=input() t=0 for i in range(n): t+=f(s[i]) tw=0 for i in range(t): tw=tw+1-f(s[i]) m=tw for i in range(n-1): tw=tw+f(s[i])-f(s[(i+t)%n]) m=min(m,tw) print(m)
{ "input": [ "3\nHTH\n", "9\nHTHTHTHHT\n" ], "output": [ "0", "2" ] }
228
10
Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit. Input The first line contains three integers n,x,y (1 ≀ n ≀ 105, 1 ≀ x, y ≀ 106) β€” the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1 ≀ ai ≀ 109) β€” the number of hits needed do destroy the i-th monster. Output Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time. Examples Input 4 3 2 1 2 3 4 Output Vanya Vova Vanya Both Input 2 1 1 1 2 Output Both Both Note In the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1. In the second sample Vanya and Vova make the first and second hit simultaneously at time 1.
n,x,y=map(int,input().split()) def f(a,x,y):return (a*x+x+y-1)//(x+y) for _ in[0]*n:n=int(input());r=f(n,x,y)*y-f(n,y,x)*x;print(['Both','Vova','Vanya'][(r>0)+(r<0)*2])
{ "input": [ "2 1 1\n1\n2\n", "4 3 2\n1\n2\n3\n4\n" ], "output": [ "Both\nBoth\n", "Vanya\nVova\nVanya\nBoth\n" ] }
229
11
Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1]. <image> Input The first line contains integer n (1 ≀ n ≀ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≀ xi ≀ 108, 2 ≀ hi ≀ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point. Output Print n space-separated numbers zi β€” the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself). Examples Input 4 16 5 20 5 10 10 18 2 Output 3 1 4 1 Input 4 0 10 1 5 9 10 15 10 Output 4 1 2 1
from typing import TypeVar, Generic, Callable, List import sys from array import array # noqa: F401 from bisect import bisect_left, bisect_right def input(): return sys.stdin.buffer.readline().decode('utf-8') T = TypeVar('T') class SegmentTree(Generic[T]): __slots__ = ["size", "tree", "identity", "op", "update_op"] def __init__(self, size: int, identity: T, op: Callable[[T, T], T], update_op: Callable[[T, T], T]) -> None: self.size = size self.tree = [identity] * (size * 2) self.identity = identity self.op = op self.update_op = update_op def build(self, a: List[T]) -> None: tree = self.tree tree[self.size:self.size + len(a)] = a for i in range(self.size - 1, 0, -1): tree[i] = self.op(tree[i << 1], tree[(i << 1) + 1]) def find(self, left: int, right: int) -> T: left += self.size right += self.size tree, result, op = self.tree, self.identity, self.op while left < right: if left & 1: result = op(tree[left], result) left += 1 if right & 1: result = op(tree[right - 1], result) left, right = left >> 1, right >> 1 return result def update(self, i: int, value: T) -> None: op, tree = self.op, self.tree i = self.size + i tree[i] = self.update_op(tree[i], value) while i > 1: i >>= 1 tree[i] = op(tree[i << 1], tree[(i << 1) + 1]) n = int(input()) a = sorted((tuple(map(int, input().split())) + (i, ) for i in range(n)), reverse=True) pos = sorted(x for x, _, _ in a) x_set = set() for x, h, i in a: x_set.add(x) x_set.add(x + h) comp_dict = {x: i for i, x in enumerate(sorted(x_set), start=1)} segt = SegmentTree[int](len(x_set) + 10, -10**9, max, max) ans = [0] * n for x, h, i in a: rx = max(x + h, segt.find(comp_dict[x], comp_dict[x + h])) res = bisect_left(pos, rx - 1) - bisect_left(pos, x) # print(x, rx, pos, bisect_left(pos, rx - 1)) ans[i] = res segt.update(comp_dict[x], rx) print(*ans)
{ "input": [ "4\n16 5\n20 5\n10 10\n18 2\n", "4\n0 10\n1 5\n9 10\n15 10\n" ], "output": [ "3 1 4 1 ", "4 1 2 1 " ] }
230
9
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice. Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm: * b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence. * For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1. In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only. Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it. Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one. Input The first input line of the input contains a single integer n (3 ≀ n ≀ 500 000) β€” the length of the initial sequence. The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself. Output If the sequence will never become stable, print a single number - 1. Otherwise, first print a single integer β€” the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β€” the resulting sequence itself. Examples Input 4 0 0 1 1 Output 0 0 0 1 1 Input 5 0 1 0 1 0 Output 2 0 0 0 0 0 Note In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) n = int(input()) L = lt() count = 0 i = 0 c = [None for i in range(n)] while i < n-1: j = i while j < n-1 and L[j] != L[j+1]: j += 1 span = j-i+1 for k in range(i,i+span//2): c[k] = L[i] for k in range(i+span//2,j+1): c[k] = L[j] count = max(count,(span-1)//2) i = j+1 if i == n-1: c[i] = L[i] print(count) print(' '.join([str(r) for r in c]))
{ "input": [ "5\n0 1 0 1 0\n", "4\n0 0 1 1\n" ], "output": [ "2\n0 0 0 0 0", "0\n0 0 1 1" ] }
231
7
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path. Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine. Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him. Input The first line of the input contains three integers β€” the number of vertices of the polygon n (<image>), and coordinates of point P. Each of the next n lines contains two integers β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value. Output Print a single real value number β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 0 0 0 1 -1 2 1 2 Output 12.566370614359172464 Input 4 1 -1 0 0 1 2 2 0 1 1 Output 21.991148575128551812 Note In the first sample snow will be removed from that area: <image>
def main(): n, a, b = map(int, input().split()) l, res = [], [] for _ in range(n): u, v = input().split() l.append((int(u) - a, int(v) - b)) x0, y0 = l[-1] for x1, y1 in l: res.append(x1 * x1 + y1 * y1) dx, dy = x1 - x0, y1 - y0 if (x0 * dx + y0 * dy) * (x1 * dx + y1 * dy) < 0: x0 = x0 * y1 - x1 * y0 res.append(x0 * x0 / (dx * dx + dy * dy)) x0, y0 = x1, y1 print((max(res) - min(res)) * 3.141592653589793) if __name__ == '__main__': main()
{ "input": [ "3 0 0\n0 1\n-1 2\n1 2\n", "4 1 -1\n0 0\n1 2\n2 0\n1 1\n" ], "output": [ "12.566370614359172464\n", "21.991148575128551812\n" ] }
232
7
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of damage. In order to break the shield Dante has to deal exactly c units of damage. Find out if this is possible. Input The first line of the input contains three integers a, b, c (1 ≀ a, b ≀ 100, 1 ≀ c ≀ 10 000) β€” the number of units of damage dealt by Ebony gun and Ivory gun, and the total number of damage required to break the shield, respectively. Output Print "Yes" (without quotes) if Dante can deal exactly c damage to the shield and "No" (without quotes) otherwise. Examples Input 4 6 15 Output No Input 3 2 7 Output Yes Input 6 11 6 Output Yes Note In the second sample, Dante can fire 1 bullet from Ebony and 2 from Ivory to deal exactly 1Β·3 + 2Β·2 = 7 damage. In the third sample, Dante can fire 1 bullet from ebony and no bullets from ivory to do 1Β·6 + 0Β·11 = 6 damage.
def main(): a, b, c = map(int, input().split()) while c % a != 0 and c > 0: c -= b print('No' if c < 0 else 'Yes') if __name__ == '__main__': main()
{ "input": [ "6 11 6\n", "3 2 7\n", "4 6 15\n" ], "output": [ "YES", "YES", "NO" ] }
233
10
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an. While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1, b2, ..., bn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way). Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother. Input The first line contains three integers n, l, r (1 ≀ n ≀ 105, 1 ≀ l ≀ r ≀ n) β€” the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ n) β€” the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ n) β€” the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes. Output Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes). Examples Input 5 2 4 3 4 2 3 1 3 2 3 4 1 Output TRUTH Input 3 1 2 1 2 3 3 1 2 Output LIE Input 4 2 4 1 1 1 1 1 1 1 1 Output TRUTH Note In the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]). In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother. In the third example for any values l and r there is a situation when Stepan said the truth.
def main(): s = input().split() n = int(s[0]) l = int(s[1]) r = int(s[2]) s = input().split() arr1 = [] for i in range(n): k = int(s[i]) arr1.append(k) s = input().split() for i in range(n): k = int(s[i]) if arr1[i] != k and (i+1 < l or i+1 > r): print('LIE') return print('TRUTH') return if __name__ == '__main__': main()
{ "input": [ "4 2 4\n1 1 1 1\n1 1 1 1\n", "5 2 4\n3 4 2 3 1\n3 2 3 4 1\n", "3 1 2\n1 2 3\n3 1 2\n" ], "output": [ "TRUTH\n", "TRUTH\n", "LIE\n" ] }
234
10
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Arkady's choice) by ai. Each extension can't be used more than once, the extensions can be used in any order. Now Arkady's field has size h Γ— w. He wants to enlarge it so that it is possible to place a rectangle of size a Γ— b on it (along the width or along the length, with sides parallel to the field sides). Find the minimum number of extensions needed to reach Arkady's goal. Input The first line contains five integers a, b, h, w and n (1 ≀ a, b, h, w, n ≀ 100 000) β€” the sizes of the rectangle needed to be placed, the initial sizes of the field and the number of available extensions. The second line contains n integers a1, a2, ..., an (2 ≀ ai ≀ 100 000), where ai equals the integer a side multiplies by when the i-th extension is applied. Output Print the minimum number of extensions needed to reach Arkady's goal. If it is not possible to place the rectangle on the field with all extensions, print -1. If the rectangle can be placed on the initial field, print 0. Examples Input 3 3 2 4 4 2 5 4 10 Output 1 Input 3 3 3 3 5 2 3 5 4 2 Output 0 Input 5 5 1 2 3 2 2 3 Output -1 Input 3 4 1 1 3 2 3 2 Output 3 Note In the first example it is enough to use any of the extensions available. For example, we can enlarge h in 5 times using the second extension. Then h becomes equal 10 and it is now possible to place the rectangle on the field.
def isin(a,b,h,w): return (h >= a and w >= b) or (h >= b and w >= a) a,b,h,w,n = map(int, input().split()) c = sorted(list(map(int, input().split())), key=lambda x: -x) if isin(a,b,h,w): print(0) exit() vis = {h: w} for i in range(len(c)): nc = c[i] pairs = [] for l in vis.keys(): pair = (l,vis[l]*nc) if isin(a,b,pair[0], pair[1]): print(i + 1) exit() pairs.append(pair) if nc*l not in vis or vis[l] > vis[nc*l]: pair = (nc*l, vis[l]) if isin(a,b,pair[0], pair[1]): print(i + 1) exit() pairs.append(pair) for p in pairs: vis[p[0]] = p[1] print(-1)
{ "input": [ "5 5 1 2 3\n2 2 3\n", "3 3 3 3 5\n2 3 5 4 2\n", "3 3 2 4 4\n2 5 4 10\n", "3 4 1 1 3\n2 3 2\n" ], "output": [ "-1", "0", "1", "3" ] }
235
8
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits. Input You are given a string consisting of 6 characters (all characters are digits from 0 to 9) β€” this string denotes Luba's ticket. The ticket can start with the digit 0. Output Print one number β€” the minimum possible number of digits Luba needs to replace to make the ticket lucky. Examples Input 000000 Output 0 Input 123456 Output 2 Input 111000 Output 1 Note In the first example the ticket is already lucky, so the answer is 0. In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required. In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required.
def solve(): s = input() x = [int(z) for z in s] y, z = x[:3], x[3:] if sum(y) < sum(z): y, z = z, y a = sum(y) - sum(z) b = [y[-1], y[-2], y[-3], 9 - z[0], 9 - z[1], 9 - z[2]] b.sort() c = 0 cnt = 0 while c < a: c += b.pop() cnt += 1 return cnt print(solve())
{ "input": [ "111000\n", "000000\n", "123456\n" ], "output": [ "1\n", "0\n", "2\n" ] }
236
10
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible. Input Input begins with an integer N (2 ≀ N ≀ 3Β·105), the number of days. Following this is a line with exactly N integers p1, p2, ..., pN (1 ≀ pi ≀ 106). The price of one share of stock on the i-th day is given by pi. Output Print the maximum amount of money you can end up with at the end of N days. Examples Input 9 10 5 4 7 9 12 6 2 10 Output 20 Input 20 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 Output 41 Note In the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is - 5 - 4 + 9 + 12 - 2 + 10 = 20.
import math from heapq import * def maxProfit(prices, days): payoff = 0 maxPrice, minPrice = max(prices), min(prices) maxIndex, minIndex = prices.index(maxPrice), prices.index(minPrice) iterator = iter(prices) h = [] # heap if days == 1: print(0) return for i in range(days): p = next(iterator) if not i: heappush(h, p) continue if h[0] < p: payoff += p - h[0] heappop(h) heappush(h, p) heappush(h, p) print(payoff) if __name__ == "__main__": n = int(input()) prices = list(map(int, input().split())) maxProfit(prices, n)
{ "input": [ "9\n10 5 4 7 9 12 6 2 10\n", "20\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4\n" ], "output": [ "20\n", "41\n" ] }
237
7
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly. It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off. Input The single line contains three integers k, d and t (1 ≀ k, d, t ≀ 1018). Output Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9. Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if <image>. Examples Input 3 2 6 Output 6.5 Input 4 2 20 Output 20.0 Note In the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for <image>. Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for <image>. Thus, after four minutes the chicken will be cooked for <image>. Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready <image>. In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.
def check(x): X=int(x) r=X//d*(k+d) x-=X//d*d if(x>=k): r+=k+x else: r+=2*x return r>=2*t k,d,t=map(int,input().split()) d*=k//d+(k%d!=0) l=0 r=1e20 for i in range(200): med=(r+l)/2 if(check(med)): r=med else: l=med print(l)
{ "input": [ "4 2 20\n", "3 2 6\n" ], "output": [ "20.000000000000000", "6.500000000000000" ] }
238
9
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there. Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell. Help Vasya! Calculate the maximum total weight of mushrooms he can collect. Input The first line contains the number n (1 ≀ n ≀ 3Β·105) β€” the length of the glade. The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1, b2, ..., bn (1 ≀ bi ≀ 106) is the growth rate of mushrooms in the second row of the glade. Output Output one number β€” the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once. Examples Input 3 1 2 3 6 5 4 Output 70 Input 3 1 1000 10000 10 100 100000 Output 543210 Note In the first test case, the optimal route is as follows: <image> Thus, the collected weight of mushrooms will be 0Β·1 + 1Β·2 + 2Β·3 + 3Β·4 + 4Β·5 + 5Β·6 = 70. In the second test case, the optimal route is as follows: <image> Thus, the collected weight of mushrooms will be 0Β·1 + 1Β·10 + 2Β·100 + 3Β·1000 + 4Β·10000 + 5Β·100000 = 543210.
import sys import io stream_enable = 0 inpstream = """ 3 1 2 3 6 5 4 """ if stream_enable: sys.stdin = io.StringIO(inpstream) input() def inpmap(): return list(map(int, input().split())) n = int(input()) arr = [inpmap(), inpmap()] s = [0] * n s[-1] = arr[0][-1] + arr[1][-1] for i in range(n - 2, -1, -1): s[i] = s[i + 1] + arr[0][i] + arr[1][i] # print(s) a = [0] * n a[-1] = arr[1][-1] * 2 + arr[0][-1] b = [0] * n b[-1] = arr[0][-1] * 2 + arr[1][-1] for i in range(n - 2, -1, -1): a[i] = arr[0][i] + a[i + 1] + s[i + 1] + arr[1][i] * (n - i) * 2 b[i] = arr[1][i] + b[i + 1] + s[i + 1] + arr[0][i] * (n - i) * 2 # print(a) # print(b) dp = [0] * n dp[-1] = arr[n % 2][-1] for i in range(n - 2, -1, -1): d = i % 2 g1 = arr[1 - d][i] + dp[i + 1] + s[i + 1] * 2 g2 = (a, b)[d][i + 1] + arr[1 - d][i] * ((n - i) * 2 - 1) dp[i] = max(g1, g2) print(dp[0])
{ "input": [ "3\n1 2 3\n6 5 4\n", "3\n1 1000 10000\n10 100 100000\n" ], "output": [ "70\n", "543210\n" ] }
239
10
You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 ≀ |a|, |b| ≀ n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a β‹… x = b or b β‹… x = a), where |x| denotes the absolute value of x. After such a transformation, your score increases by |x| points and you are not allowed to transform a into b nor b into a anymore. Initially, you have a score of 0. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve? Input A single line contains a single integer n (2 ≀ n ≀ 100 000) β€” the given integer described above. Output Print an only integer β€” the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print 0. Examples Input 4 Output 8 Input 6 Output 28 Input 2 Output 0 Note In the first example, the transformations are 2 β†’ 4 β†’ (-2) β†’ (-4) β†’ 2. In the third example, it is impossible to perform even a single transformation.
def fun_with_integers_linear2_solve(): n = int(input()) ans = 0 for i in range(2, n): cant = n // i ans += (cant * (cant + 1) // 2 - 1) print(ans * 4) fun_with_integers_linear2_solve()
{ "input": [ "2\n", "4\n", "6\n" ], "output": [ "0", "8", "28" ] }
240
9
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that: 1. For each i (1 ≀ i ≀ k), s_{p_i} = 'a'. 2. For each i (1 ≀ i < k), there is such j that p_i < j < p_{i + 1} and s_j = 'b'. The Nut is upset because he doesn't know how to find the number. Help him. This number should be calculated modulo 10^9 + 7. Input The first line contains the string s (1 ≀ |s| ≀ 10^5) consisting of lowercase Latin letters. Output In a single line print the answer to the problem β€” the number of such sequences p_1, p_2, …, p_k modulo 10^9 + 7. Examples Input abbaa Output 5 Input baaaa Output 4 Input agaa Output 3 Note In the first example, there are 5 possible sequences. [1], [4], [5], [1, 4], [1, 5]. In the second example, there are 4 possible sequences. [2], [3], [4], [5]. In the third example, there are 3 possible sequences. [1], [3], [4].
mod = 1000000007 def md(x): return ((x%mod)+mod)%mod s = input() r = 1 a = 1 for i in s: if i == "a": a += 1 elif i == "b": r = md(r*a) a = 1 r = md(r*a) print (md(r-1))
{ "input": [ "agaa\n", "baaaa\n", "abbaa\n" ], "output": [ "3\n", "4\n", "5\n" ] }
241
11
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings s of length m and t is a string t + s_1 + t + s_2 + … + t + s_m + t, where s_i denotes the i-th symbol of the string s, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings s and t is not necessarily equal to product of t and s. Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to 3, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to 1, since all neighboring symbols in it are different. In order to entertain Roman, Denis wrote down n strings p_1, p_2, p_3, …, p_n on the paper and asked him to calculate the beauty of the string ( … (((p_1 β‹… p_2) β‹… p_3) β‹… … ) β‹… p_n, where s β‹… t denotes a multiplication of strings s and t. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most 10^9. Input The first line contains a single integer n (2 ≀ n ≀ 100 000) β€” the number of strings, wroted by Denis. Next n lines contain non-empty strings p_1, p_2, …, p_n, consisting of lowercase english letters. It's guaranteed, that the total length of the strings p_i is at most 100 000, and that's the beauty of the resulting product is at most 10^9. Output Print exactly one integer β€” the beauty of the product of the strings. Examples Input 3 a b a Output 3 Input 2 bnn a Output 1 Note In the first example, the product of strings is equal to "abaaaba". In the second example, the product of strings is equal to "abanana".
from math import * import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) n = mint() a = [0]*256 b = [0]*256 for k in range(0,n): #print(a[ord('a'):ord('z')+1]) for i in range(ord('a'),ord('z')+1): b[i] = min(a[i],1) i = 0 s = list(minp()) l = len(s) q = 0 while i < l: j = i + 1 while j < l and s[j] == s[i]: j += 1 z = ord(s[i]) w = j-i if i == 0: q = w if j == l: w += (w+1)*a[z] elif a[z] != 0: w += 1 elif j == l: w += 1 if s[0] == s[-1]: w += q b[z] = max(b[z], w) i = j a,b = b,a print(max(a))
{ "input": [ "2\nbnn\na\n", "3\na\nb\na\n" ], "output": [ "1", "3" ] }
242
7
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible. The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≑ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once. Find the maximum number of chests Neko can open. Input The first line contains integers n and m (1 ≀ n, m ≀ 10^5) β€” the number of chests and the number of keys. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the numbers written on the treasure chests. The third line contains m integers b_1, b_2, …, b_m (1 ≀ b_i ≀ 10^9) β€” the numbers written on the keys. Output Print the maximum number of chests you can open. Examples Input 5 4 9 14 6 2 11 8 4 7 20 Output 3 Input 5 1 2 4 6 8 10 5 Output 1 Input 1 4 10 20 30 40 50 Output 0 Note In the first example, one possible way to unlock 3 chests is as follows: * Use first key to unlock the fifth chest, * Use third key to unlock the second chest, * Use fourth key to unlock the first chest. In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice). In the third example, no key can unlock the given chest.
def I(): return map(int, input().split()) n, m = I() a = sum(i % 2 for i in list(I())) b = sum(i % 2 for i in list(I())) print(min(a, m-b)+min(n-a, b))
{ "input": [ "5 1\n2 4 6 8 10\n5\n", "1 4\n10\n20 30 40 50\n", "5 4\n9 14 6 2 11\n8 4 7 20\n" ], "output": [ "1\n", "0\n", "3\n" ] }
243
9
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≀ m ≀ n) special items of them. These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty. Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded. <image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10. Tokitsukaze wants to know the number of operations she would do in total. Input The first line contains three integers n, m and k (1 ≀ n ≀ 10^{18}, 1 ≀ m ≀ 10^5, 1 ≀ m, k ≀ n) β€” the number of items, the number of special items to be discarded and the number of positions in each page. The second line contains m distinct integers p_1, p_2, …, p_m (1 ≀ p_1 < p_2 < … < p_m ≀ n) β€” the indices of special items which should be discarded. Output Print a single integer β€” the number of operations that Tokitsukaze would do in total. Examples Input 10 4 5 3 5 7 10 Output 3 Input 13 4 5 7 8 9 10 Output 1 Note For the first example: * In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5; * In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7; * In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10. For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once.
def gns(): return list(map(int,input().split())) n,m,k=gns() ms=gns() ms=[x-1 for x in ms] ans=0 if k==1: print(m) quit() i=0 while i<m: ans+=1 p=(ms[i]%k+k-i%k)%k to=ms[i]+(k-p)-1 while i<m and ms[i]<=to: i+=1 print(ans)
{ "input": [ "13 4 5\n7 8 9 10\n", "10 4 5\n3 5 7 10\n" ], "output": [ "1\n", "3\n" ] }
244
7
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends. Input The only line contains four integers a_1, a_2, a_3 and a_4 (1 ≀ a_i ≀ 100) β€” the numbers of candies in each bag. Output Output YES if it's possible to give the bags to Dawid's friends so that both friends receive the same amount of candies, or NO otherwise. Each character can be printed in any case (either uppercase or lowercase). Examples Input 1 7 11 5 Output YES Input 7 3 2 5 Output NO Note In the first sample test, Dawid can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive 12 candies. In the second sample test, it's impossible to distribute the bags.
def I(): return map(int, input().split()) a = sorted(list(I())) print("YES" if a[0]+a[3] == a[1]+a[2] or a[0]+a[1]+a[2] == a[3] else "NO")
{ "input": [ "1 7 11 5\n", "7 3 2 5\n" ], "output": [ "YES\n", "NO\n" ] }
245
11
The only difference between easy and hard versions is constraints. Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you. There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free. Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β†’ {1, 5} β†’ {1, 2, 3, 5} β†’ {1, 2, 3, 4, 5}. Calculate the minimum number of coins you have to spend so that everyone votes for you. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 5000) β€” the number of voters. The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 ≀ p_i ≀ 10^9, 0 ≀ m_i < n). It is guaranteed that the sum of all n over all test cases does not exceed 5000. Output For each test case print one integer β€” the minimum number of coins you have to spend so that everyone votes for you. Example Input 3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5 Output 8 0 7 Note In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β†’ {1, 3} β†’ {1, 2, 3}. In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β†’ {1, 3, 5} β†’ {1, 2, 3, 5} β†’ {1, 2, 3, 5, 6, 7} β†’ {1, 2, 3, 4, 5, 6, 7}. In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β†’ {1, 2, 3, 4, 5} β†’ {1, 2, 3, 4, 5, 6}.
import sys import heapq as hq readline = sys.stdin.readline read = sys.stdin.read ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def solve(): n = ni() vot = [tuple(nm()) for _ in range(n)] vot.sort(key = lambda x: (-x[0], x[1])) q = list() c = 0 cost = 0 for i in range(n): hq.heappush(q, vot[i][1]) while n - i - 1 + c < vot[i][0]: cost += hq.heappop(q) c += 1 print(cost) return # solve() T = ni() for _ in range(T): solve()
{ "input": [ "3\n3\n1 5\n2 10\n2 8\n7\n0 1\n3 1\n1 1\n6 1\n1 1\n4 1\n4 1\n6\n2 6\n2 3\n2 8\n2 7\n4 4\n5 5\n" ], "output": [ "8\n0\n7\n" ] }
246
9
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes. The main school of the capital is located in (s_x, s_y). There are n students attending this school, the i-th of them lives in the house located in (x_i, y_i). It is possible that some students live in the same house, but no student lives in (s_x, s_y). After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the i-th student goes from the school to his house is |s_x - x_i| + |s_y - y_i|. The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the i-th student will buy a shawarma if at least one of the shortest paths from the school to the i-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students). You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself. Input The first line contains three integers n, s_x, s_y (1 ≀ n ≀ 200 000, 0 ≀ s_x, s_y ≀ 10^{9}) β€” the number of students and the coordinates of the school, respectively. Then n lines follow. The i-th of them contains two integers x_i, y_i (0 ≀ x_i, y_i ≀ 10^{9}) β€” the location of the house where the i-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated. Output The output should consist of two lines. The first of them should contain one integer c β€” the maximum number of students that will buy shawarmas at the tent. The second line should contain two integers p_x and p_y β€” the coordinates where the tent should be located. If there are multiple answers, print any of them. Note that each of p_x and p_y should be not less than 0 and not greater than 10^{9}. Examples Input 4 3 2 1 3 4 2 5 1 4 1 Output 3 4 2 Input 3 100 100 0 0 0 0 100 200 Output 2 99 100 Input 7 10 12 5 6 20 23 15 4 16 5 4 54 12 1 4 15 Output 4 10 11 Note In the first example, If we build the shawarma tent in (4, 2), then the students living in (4, 2), (4, 1) and (5, 1) will visit it. In the second example, it is possible to build the shawarma tent in (1, 1), then both students living in (0, 0) will visit it.
def main(): n, sx, sy = map(int, input().split()) t, b, l, r = 0, 0, 0, 0 for i in range(n): x, y = map(int, input().split()) if x < sx: l += 1 if x > sx: r += 1 if y < sy: b += 1 if y > sy: t += 1 a = [(l, (sx - 1, sy)), (r, (sx + 1, sy)), (b, (sx, sy - 1)), (t, (sx, sy + 1))] ans = max(a) print(ans[0]) print(*ans[1]) main()
{ "input": [ "7 10 12\n5 6\n20 23\n15 4\n16 5\n4 54\n12 1\n4 15\n", "4 3 2\n1 3\n4 2\n5 1\n4 1\n", "3 100 100\n0 0\n0 0\n100 200\n" ], "output": [ "4\n11 12", "3\n4 2", "2\n99 100" ] }
247
10
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: * for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array; * for the array [1, 2, 3, 4] MEX equals to 0 because 0 is the minimum non-negative integer not presented in the array; * for the array [0, 1, 4, 3] MEX equals to 2 because 2 is the minimum non-negative integer not presented in the array. You are given an empty array a=[] (in other words, a zero-length array). You are also given a positive integer x. You are also given q queries. The j-th query consists of one integer y_j and means that you have to append one element y_j to the array. The array length increases by 1 after a query. In one move, you can choose any index i and set a_i := a_i + x or a_i := a_i - x (i.e. increase or decrease any element of the array by x). The only restriction is that a_i cannot become negative. Since initially the array is empty, you can perform moves only after the first query. You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element). You have to find the answer after each of q queries (i.e. the j-th answer corresponds to the array of length j). Operations are discarded before each query. I.e. the array a after the j-th query equals to [y_1, y_2, ..., y_j]. Input The first line of the input contains two integers q, x (1 ≀ q, x ≀ 4 β‹… 10^5) β€” the number of queries and the value of x. The next q lines describe queries. The j-th query consists of one integer y_j (0 ≀ y_j ≀ 10^9) and means that you have to append one element y_j to the array. Output Print the answer to the initial problem after each query β€” for the query j print the maximum value of MEX after first j queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries. Examples Input 7 3 0 1 2 2 0 0 10 Output 1 2 3 3 4 4 7 Input 4 3 1 2 1 2 Output 0 0 0 0 Note In the first example: * After the first query, the array is a=[0]: you don't need to perform any operations, maximum possible MEX is 1. * After the second query, the array is a=[0, 1]: you don't need to perform any operations, maximum possible MEX is 2. * After the third query, the array is a=[0, 1, 2]: you don't need to perform any operations, maximum possible MEX is 3. * After the fourth query, the array is a=[0, 1, 2, 2]: you don't need to perform any operations, maximum possible MEX is 3 (you can't make it greater with operations). * After the fifth query, the array is a=[0, 1, 2, 2, 0]: you can perform a[4] := a[4] + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3]. Now MEX is maximum possible and equals to 4. * After the sixth query, the array is a=[0, 1, 2, 2, 0, 0]: you can perform a[4] := a[4] + 3 = 0 + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3, 0]. Now MEX is maximum possible and equals to 4. * After the seventh query, the array is a=[0, 1, 2, 2, 0, 0, 10]. You can perform the following operations: * a[3] := a[3] + 3 = 2 + 3 = 5, * a[4] := a[4] + 3 = 0 + 3 = 3, * a[5] := a[5] + 3 = 0 + 3 = 3, * a[5] := a[5] + 3 = 3 + 3 = 6, * a[6] := a[6] - 3 = 10 - 3 = 7, * a[6] := a[6] - 3 = 7 - 3 = 4. The resulting array will be a=[0, 1, 2, 5, 3, 6, 4]. Now MEX is maximum possible and equals to 7.
import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n,x = mints() c = [0]*x ans = 0 for i in range(n): y = mint() c[y%x] += 1 while c[ans%x] > 0: c[ans%x] -= 1 ans += 1 print(ans) solve()
{ "input": [ "4 3\n1\n2\n1\n2\n", "7 3\n0\n1\n2\n2\n0\n0\n10\n" ], "output": [ "0\n0\n0\n0\n", "1\n2\n3\n3\n4\n4\n7\n" ] }
248
10
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications. The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm. Input The first line of input consists of single integer n β€” the number of news categories (1 ≀ n ≀ 200 000). The second line of input consists of n integers a_i β€” the number of publications of i-th category selected by the batch algorithm (1 ≀ a_i ≀ 10^9). The third line of input consists of n integers t_i β€” time it takes for targeted algorithm to find one new publication of category i (1 ≀ t_i ≀ 10^5). Output Print one integer β€” the minimal required time for the targeted algorithm to get rid of categories with the same size. Examples Input 5 3 7 9 7 8 5 2 5 7 5 Output 6 Input 5 1 2 3 4 5 1 1 1 1 1 Output 0 Note In the first example, it is possible to find three publications of the second type, which will take 6 seconds. In the second example, all news categories contain a different number of publications.
# from collections import defaultdict # for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) ts = list(map(int, input().split())) tt = [(ts[i], i) for i in range(n)] tt.sort(reverse=True) conflict = {} next = {} money = 0 def get_next(i): if i not in conflict: return i if next[i] in conflict: next[i] = get_next(next[i]) return next[i] for tx in tt: t, i = tx nee = get_next(a[i]) money += (nee - a[i]) * t conflict[nee] = True next[nee] = nee+1 print(money)
{ "input": [ "5\n3 7 9 7 8\n5 2 5 7 5\n", "5\n1 2 3 4 5\n1 1 1 1 1\n" ], "output": [ "6\n", "0\n" ] }
249
10
Alice and Bob are playing yet another card game. This time the rules are the following. There are n cards lying in a row in front of them. The i-th card has value a_i. First, Alice chooses a non-empty consecutive segment of cards [l; r] (l ≀ r). After that Bob removes a single card j from that segment (l ≀ j ≀ r). The score of the game is the total value of the remaining cards on the segment (a_l + a_{l + 1} + ... + a_{j - 1} + a_{j + 1} + ... + a_{r - 1} + a_r). In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is 0. Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible. What segment should Alice choose so that the score is maximum possible? Output the maximum score. Input The first line contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of cards. The second line contains n integers a_1, a_2, ..., a_n (-30 ≀ a_i ≀ 30) β€” the values on the cards. Output Print a single integer β€” the final score of the game. Examples Input 5 5 -2 10 -1 4 Output 6 Input 8 5 2 5 3 -30 -30 6 9 Output 10 Input 3 -10 6 -15 Output 0 Note In the first example Alice chooses a segment [1;5] β€” the entire row of cards. Bob removes card 3 with the value 10 from the segment. Thus, the final score is 5 + (-2) + (-1) + 4 = 6. In the second example Alice chooses a segment [1;4], so that Bob removes either card 1 or 3 with the value 5, making the answer 5 + 2 + 3 = 10. In the third example Alice can choose any of the segments of length 1: [1;1], [2;2] or [3;3]. Bob removes the only card, so the score is 0. If Alice chooses some other segment then the answer will be less than 0.
def do(arr): res = 0 for i in range(30, -31, -1): temp = 0 for x in arr: if x > i: temp = 0 else: res = max(res, temp + x - i) temp = max(0, temp + x) return res input() lst = list(map(int, input().split())) print(do(lst))
{ "input": [ "3\n-10 6 -15\n", "8\n5 2 5 3 -30 -30 6 9\n", "5\n5 -2 10 -1 4\n" ], "output": [ "0\n", "10\n", "6\n" ] }
250
10
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly. Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers. Given number n, can you find the two digit permutations that have this property? Input The first line contains a positive integer n β€” the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes. Output Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them. Examples Input 198 Output 981 819 Input 500 Output 500 500
import itertools def countZeroes(s): ret = 0 for i in s: if i != '0': break ret += 1 return ret def stupid(n): ansMax = 0 bn1 = n bn2 = n for n1 in itertools.permutations(n): for n2 in itertools.permutations(n): val = str(int(''.join(n1)) + int(''.join(n2)))[::-1] cnt = countZeroes(val) if cnt > ansMax: ansMax = cnt bn1 = ''.join(n1) bn2 = ''.join(n2) return (bn1, bn2) def solution(n): ansMax = n.count('0') bestN1 = n.replace('0', '') + ansMax * '0' bestN2 = n.replace('0', '') + ansMax * '0' for i in range(1, 10): cnt1 = [n.count(str(j)) for j in range(10)] cnt2 = [n.count(str(j)) for j in range(10)] if cnt1[i] == 0 or cnt2[10 - i] == 0: continue cnt1[i] -= 1 cnt2[10 - i] -= 1 curN1 = str(i) curN2 = str(10 - i) ansCur = 1 for j in range(10): addend = min(cnt1[j], cnt2[9 - j]) ansCur += addend cnt1[j] -= addend cnt2[9 - j] -= addend curN1 += str(j) * addend curN2 += str(9 - j) * addend if cnt1[0] > 0 and cnt2[0] > 0: addend = min(cnt1[0], cnt2[0]) ansCur += addend cnt1[0] -= addend cnt2[0] -= addend curN1 = '0' * addend + curN1 curN2 = '0' * addend + curN2 if ansCur > ansMax: ansMax = ansCur f = lambda x: str(x[0]) * x[1] bestN1 = ''.join(map(f, enumerate(cnt1))) + curN1[::-1] bestN2 = ''.join(map(f, enumerate(cnt2))) + curN2[::-1] return (bestN1, bestN2) n = input() print('\n'.join(solution(n)))
{ "input": [ "500\n", "198\n" ], "output": [ "500\n500", "981\n819" ] }
251
7
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a β‰  b) will indulge if: 1. gcd(a, b) = 1 or, 2. a divides b or b divides a. gcd(a, b) β€” the maximum number x such that a is divisible by x and b is divisible by x. For example, if n=3 and the kids sit on chairs with numbers 2, 3, 4, then they will indulge since 4 is divided by 2 and gcd(2, 3) = 1. If kids sit on chairs with numbers 4, 6, 10, then they will not indulge. The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no 2 of the kid that can indulge. More formally, she wants no pair of chairs a and b that the kids occupy to fulfill the condition above. Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing an integer n (1 ≀ n ≀ 100) β€” the number of kids. Output Output t lines, which contain n distinct integers from 1 to 4n β€” the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print n numbers in any order. Example Input 3 2 3 4 Output 6 4 4 6 10 14 10 12 8
def fun(n): ls=[i for i in range(2*n,4*n,2)] print(*ls) T = int(input()) for i in range(T): t= int(input()) fun(t)
{ "input": [ "3\n2\n3\n4\n" ], "output": [ "8 6\n12 10 8\n16 14 12 10\n" ] }
252
9
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1. A string a is lexicographically smaller than a string b if and only if one of the following holds: * a is a prefix of b, but a β‰  b; * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. Input The first line contains a single integer T (1 ≀ T ≀ 10 000) β€” the number of test cases. The next 2 β‹… T lines contain the description of test cases. The description of each test case consists of two lines. The first line of the description contains two integers n and k (1 ≀ k ≀ n ≀ 10^5) β€” the length of string s and number k respectively. The second line contains string s consisting of lowercase English letters. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist. Example Input 4 4 2 abcd 3 1 abc 4 3 aaaa 9 3 abaabaaaa Output acac abc -1 abaabaaab Note In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful. In the second test case each letter appears 0 or 1 times in s, so s itself is the answer. We can show that there is no suitable string in the third test case. In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
from collections import Counter def calc(c, l): s = 0 r = [0]*26 for i in range(26): s += (k-c[i]%k)%k r[i] = (k-c[i]%k)%k if s>l: return -1 ans = "a"*(l-s) for i in range(26): ans += (chr(i+97))*r[i] return ans for nt in range(int(input())): n, k = map(int,input().split()) s = input() if n%k!=0: print (-1) continue c = [0]*26 for i in s: c[ord(i)-97] += 1 ans = True for i in c: if i%k!=0: ans = False if ans: print (s) continue found = False for i in range(n-1, -1, -1): c[ord(s[i])-97] -= 1 for j in range(ord(s[i])+1, 123): c[j-97] += 1 suff = calc(c, n-i-1) if suff!=-1: found = True suff = s[0:i]+chr(j)+suff break c[j-97] -= 1 if found: break print (suff)
{ "input": [ "4\n4 2\nabcd\n3 1\nabc\n4 3\naaaa\n9 3\nabaabaaaa\n" ], "output": [ "\nacac\nabc\n-1\nabaabaaab\n" ] }
253
8
Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into n sub-tracks. You are given an array a where a_i represents the number of traffic cars in the i-th sub-track. You define the inconvenience of the track as βˆ‘_{i=1}^{n} βˆ‘_{j=i+1}^{n} \lvert a_i-a_j\rvert, where |x| is the absolute value of x. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track. Find the minimum inconvenience you can achieve. Input The first line of input contains a single integer t (1≀ t≀ 10 000) β€” the number of test cases. The first line of each test case contains a single integer n (1≀ n≀ 2β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (0≀ a_i≀ 10^9). It is guaranteed that the sum of n over all test cases does not exceed 2β‹… 10^5. Output For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times. Example Input 3 3 1 2 3 4 0 1 1 0 10 8 3 6 11 5 2 1 7 10 4 Output 0 4 21 Note For the first test case, you can move a car from the 3-rd sub-track to the 1-st sub-track to obtain 0 inconvenience. For the second test case, moving any car won't decrease the inconvenience of the track.
def calc(): n = int(input()) l = list(map(int, input().split(' '))) ss = sum(l) ans = (ss % n) * (n - (ss % n)) print(ans) t = int(input()) for _i in range(t): calc()
{ "input": [ "3\n3\n1 2 3\n4\n0 1 1 0\n10\n8 3 6 11 5 2 1 7 10 4\n" ], "output": [ "0\n4\n21\n" ] }
254
9
How to make a cake you'll never eat. Ingredients. * 2 carrots * 0 calories * 100 g chocolate spread * 1 pack of flour * 1 egg Method. 1. Put calories into the mixing bowl. 2. Take carrots from refrigerator. 3. Chop carrots. 4. Take chocolate spread from refrigerator. 5. Put chocolate spread into the mixing bowl. 6. Combine pack of flour into the mixing bowl. 7. Fold chocolate spread into the mixing bowl. 8. Add chocolate spread into the mixing bowl. 9. Put pack of flour into the mixing bowl. 10. Add egg into the mixing bowl. 11. Fold pack of flour into the mixing bowl. 12. Chop carrots until choped. 13. Pour contents of the mixing bowl into the baking dish. Serves 1. Input The only line of input contains a sequence of integers a0, a1, ... (1 ≀ a0 ≀ 100, 0 ≀ ai ≀ 1000 for i β‰₯ 1). Output Output a single integer. Examples Input 4 1 2 3 4 Output 30
# PRE-PROGRAM inp = [] def read(): global inp if not inp: inp = list(map(int, input().split()))[::-1] return inp.pop() # INGREDIENTS carrots = 2 calories = 0 chocolate_spread = 100 #g pack_of_flour = 1 egg = 1 mixing_bowl = [] baking_dish = [] # METHOD mixing_bowl.append(calories) # 1 carrots = read() # 2 for i in range(carrots, 0, -1): # 3 chocolate_spread = read() # 4 mixing_bowl.append(chocolate_spread) # 5 mixing_bowl[-1] *= pack_of_flour # 6 chocolate_spread = mixing_bowl.pop() # 7 mixing_bowl[-1] += chocolate_spread # 8 mixing_bowl.append(pack_of_flour) # 9 mixing_bowl[-1] += egg # 10 pack_of_flour = mixing_bowl.pop() # 11 # 12 baking_dish.extend(mixing_bowl) # 13 print('\n'.join(map(str, baking_dish))) # Serves 1
{ "input": [ "4 1 2 3 4\n" ], "output": [ "30" ] }
255
7
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP. In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed. The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca". Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland. Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B. Input The first line contains integer n (1 ≀ n ≀ 5Β·105) β€” the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters. Output Print a single number β€” length of the sought dynasty's name in letters. If Vasya's list is wrong and no dynasty can be found there, print a single number 0. Examples Input 3 abc ca cba Output 6 Input 4 vvp vvp dam vvp Output 0 Input 3 ab c def Output 1 Note In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings). In the second sample there aren't acceptable dynasties. The only dynasty in the third sample consists of one king, his name is "c".
from queue import PriorityQueue from queue import Queue import math from collections import * import sys import operator as op from functools import reduce # sys.setrecursionlimit(10 ** 6) MOD = int(1e9 + 7) input = sys.stdin.readline def ii(): return list(map(int, input().strip().split())) def ist(): return list(input().strip().split()) n, = ii() l = [[0 for i in range(26)] for i in range(26)] for i in range(n): s = input().strip() a, b = ord(s[0])-97, ord(s[-1])-97 for j in range(26): if l[j][a] > 0: l[j][b] = max(l[j][a]+len(s), l[j][b]) l[a][b] = max(l[a][b], len(s)) ans = 0 for i in range(26): if l[i][i] > ans: ans = l[i][i] print(ans)
{ "input": [ "4\nvvp\nvvp\ndam\nvvp\n", "3\nab\nc\ndef\n", "3\nabc\nca\ncba\n" ], "output": [ "0\n", "1\n", "6\n" ] }
256
7
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≀ i ≀ n; 1 ≀ j ≀ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value <image>. Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears. In the problem, fraction <image> denotes division in real numbers, that is, no rounding is performed. Input The first input line contains integer n (1 ≀ n ≀ 50) β€” the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 104) in the order of strict increasing. The third input line contains integer m (1 ≀ m ≀ 50) β€” the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces. Output Print the number of "integer" gears with the maximum ratio among all "integer" gears. Examples Input 2 4 5 3 12 13 15 Output 2 Input 4 1 2 3 4 5 10 11 12 13 14 Output 1 Note In the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.
from sys import stdin import math def read(): return map(int, stdin.readline().split()) read() a = list(read()) read() b = list(read()) magic = [ x // y for x in b for y in a if x % y == 0 ] print(magic.count ( max(magic) ) )
{ "input": [ "4\n1 2 3 4\n5\n10 11 12 13 14\n", "2\n4 5\n3\n12 13 15\n" ], "output": [ "1\n", "2\n" ] }
257
7
Valera had two bags of potatoes, the first of these bags contains x (x β‰₯ 1) potatoes, and the second β€” y (y β‰₯ 1) potatoes. Valera β€” very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k. Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order. Input The first line of input contains three integers y, k, n (1 ≀ y, k, n ≀ 109; <image> ≀ 105). Output Print the list of whitespace-separated integers β€” all possible values of x in ascending order. You should print each possible value of x exactly once. If there are no such values of x print a single integer -1. Examples Input 10 1 10 Output -1 Input 10 6 40 Output 2 8 14 20 26
def potatoes_bags(y,k,n): s=' '.join(map(str,range(k-y%k,n-y+1,k))) return s if s else -1 y,k,n=map(int,input().split()) print(potatoes_bags(y,k,n))
{ "input": [ "10 6 40\n", "10 1 10\n" ], "output": [ "2 8 14 20 26\n", "-1\n" ] }
258
10
You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1. A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v1, v2, ..., vd such, that nodes v1 and vd are connected by an edge of the graph, also for any integer i (1 ≀ i < d) nodes vi and vi + 1 are connected by an edge of the graph. Input The first line contains three integers n, m, k (3 ≀ n, m ≀ 105; 2 ≀ k ≀ n - 1) β€” the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers ai, bi (1 ≀ ai, bi ≀ n; ai β‰  bi) β€” the indexes of the graph nodes that are connected by the i-th edge. It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph. Output In the first line print integer r (r β‰₯ k + 1) β€” the length of the found cycle. In the next line print r distinct integers v1, v2, ..., vr (1 ≀ vi ≀ n) β€” the found simple cycle. It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them. Examples Input 3 3 2 1 2 2 3 3 1 Output 3 1 2 3 Input 4 6 3 4 3 1 2 1 3 1 4 2 3 2 4 Output 4 3 4 1 2
def f(): n, m, k = map(int, input().split()) p = [[] for i in range(n + 1)] for i in range(m): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) t, r = [0] * (n + 1), [1] x = t[1] = 1 i = 0 - k while True: for y in p[x]: if t[y] == 2: return r[r.index(y): ] if t[y]: continue t[y], x = 1, y r.append(x) i += 1 if i >= 0: t[r[i]] = 2 break t = f() print(len(t)) print(' '.join(map(str, t)))
{ "input": [ "4 6 3\n4 3\n1 2\n1 3\n1 4\n2 3\n2 4\n", "3 3 2\n1 2\n2 3\n3 1\n" ], "output": [ "4\n1 2 3 4 ", "3\n1 2 3 " ] }
259
8
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible. Input The only line of the input contains one string s of length n (1 ≀ n ≀ 5Β·104) containing only lowercase English letters. Output If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible. If there exists multiple answers, you are allowed to print any of them. Examples Input bbbabcbbb Output bbbcbbb Input rquwmzexectvnbanemsmdufrg Output rumenanemur Note A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
def p2(a): n = len(a) last = [[0] * 26 for _ in range(n)] last[0][ord(a[0])-97] = 0 for i in range(1, n): for j in range(26): last[i][j] = last[i-1][j] last[i][ord(a[i])-97] = i dp = [''] * n for i in range(n-1, -1, -1): for j in range(n-1, i, -1): k = last[j][ord(a[i])-97] if k > i: if (k - i) == 1 and len(dp[j]) < 2: dp[j] = a[i] + a[i] elif len(dp[j]) < (len(dp[k-1]) + 2): dp[j] = a[i] + dp[k - 1] + a[i] if len(dp[j]) >= 100: if len(dp[j]) == 101: return dp[j][:50] + dp[j][51:] else: return dp[j] dp[i] = a[i] return dp[n-1] print(p2(input()))
{ "input": [ "rquwmzexectvnbanemsmdufrg\n", "bbbabcbbb\n" ], "output": [ "rumenanemur", "bbbcbbb" ] }
260
8
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3. Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message. Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less. Output In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise. Examples Input 3 i love you &lt;3i&lt;3love&lt;23you&lt;3 Output yes Input 7 i am not main in the family &lt;3i&lt;&gt;3am&lt;3the&lt;3&lt;main&lt;3in&lt;3the&lt;3&gt;&lt;3family&lt;3 Output no Note Please note that Dima got a good old kick in the pants for the second sample from the statement.
def readln(): return tuple(map(int, input().split())) n, = readln() sms = '<3'.join([''] + [input() for _ in range(n)] + ['']) s = 0 for c in list(input()): if sms[s] == c: s += 1 if s == len(sms): break print('yes' if s == len(sms) else 'no')
{ "input": [ "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n&lt;3i&lt;&gt;3am&lt;3the&lt;3&lt;main&lt;3in&lt;3the&lt;3&gt;&lt;3family&lt;3\n", "3\ni\nlove\nyou\n&lt;3i&lt;3love&lt;23you&lt;3\n" ], "output": [ "no\n", "no\n" ] }
261
7
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her. Input The first line contains integer n (1 ≀ n ≀ 1000) β€” the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000. Output On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game. Examples Input 4 4 1 2 10 Output 12 5 Input 7 1 2 3 4 5 6 7 Output 16 12 Note In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.
n = int(input()) c = [int(x) for x in input().split()] s, d = 0, 0 def pop(): if c[0] > c[-1]: return c.pop(0) else: return c.pop() while c: s += pop() if c: d += pop() print(s, d)
{ "input": [ "7\n1 2 3 4 5 6 7\n", "4\n4 1 2 10\n" ], "output": [ "16 12\n", "12 5\n" ] }
262
7
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills. According to the borscht recipe it consists of n ingredients that have to be mixed in proportion <image> litres (thus, there should be a1 Β·x, ..., an Β·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately? Input The first line of the input contains two space-separated integers n and V (1 ≀ n ≀ 20, 1 ≀ V ≀ 10000). The next line contains n space-separated integers ai (1 ≀ ai ≀ 100). Finally, the last line contains n space-separated integers bi (0 ≀ bi ≀ 100). Output Your program should output just one real number β€” the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4. Examples Input 1 100 1 40 Output 40.0 Input 2 100 1 1 25 30 Output 50.0 Input 2 100 1 1 60 60 Output 100.0
def mi(): return map(int, input().split()) n,v = mi() a = list(mi()) b = list(mi()) x = 100000 for i in range(n): x = min(x,b[i]/a[i]) print (min(sum(a)*x,v))
{ "input": [ "1 100\n1\n40\n", "2 100\n1 1\n60 60\n", "2 100\n1 1\n25 30\n" ], "output": [ "40.0000", "100.0000", "50.0000" ] }
263
10
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: 1. the number of good substrings of even length; 2. the number of good substrings of odd length. Input The first line of the input contains a single string of length n (1 ≀ n ≀ 105). Each character of the string will be either 'a' or 'b'. Output Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length. Examples Input bb Output 1 2 Input baab Output 2 4 Input babb Output 2 5 Input babaa Output 2 7 Note In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length. In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length. In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length. Definitions A substring s[l, r] (1 ≀ l ≀ r ≀ n) of string s = s1s2... sn is string slsl + 1... sr. A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
def main(): s = input() a = [0, 0] b = [0, 0] res = [0, 0] for i, c in enumerate(s, 1): ii, ij = i%2, (i+1)%2 _a = a if c == 'a' else b res[1] += _a[ii] + 1 res[0] += _a[ij] _a[ii] += 1 print(*res) if __name__ == '__main__': main()
{ "input": [ "babaa\n", "bb\n", "baab\n", "babb\n" ], "output": [ "2 7\n", "1 2\n", "2 4\n", "2 5\n" ] }
264
9
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles. Initially, each mole i (1 ≀ i ≀ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible. Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi). A regiment is compact only if the position points of the 4 moles form a square with non-zero area. Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible. Input The first line contains one integer n (1 ≀ n ≀ 100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≀ xi, yi, ai, bi ≀ 104). Output Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes). Examples Input 4 1 1 0 0 -1 1 0 0 -1 1 0 0 1 -1 0 0 1 1 0 0 -2 1 0 0 -1 1 0 0 1 -1 0 0 1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 2 2 0 1 -1 0 0 -2 3 0 0 -2 -1 1 -2 0 Output 1 -1 3 3 Note In the first regiment we can move once the second or the third mole. We can't make the second regiment compact. In the third regiment, from the last 3 moles we can move once one and twice another one. In the fourth regiment, we can move twice the first mole and once the third mole.
def r(t): t[0], t[1] = t[2] + t[3] - t[1], t[3] + t[0] - t[2] f = [(0, 0), (1, 3), (2, 15), (3, 63)] h = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] g = lambda u, v: (u[0] - v[0]) ** 2 + (u[1] - v[1]) ** 2 for i in range(int(input())): p = [list(map(int, input().split())) for j in range(4)] s = 13 for q in range(256): t = sum((q >> k) & 3 for k in (0, 2, 4, 6)) d = sorted(g(p[u], p[v]) for u, v in h) if 0 != d[4] == d[5] == 2 * d[0] == 2 * d[3]: s = min(s, t) for i, k in f: if q & k == k: r(p[i]) print(s if s < 13 else -1)
{ "input": [ "4\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-2 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n-1 1 0 0\n2 2 0 1\n-1 0 0 -2\n3 0 0 -2\n-1 1 -2 0\n" ], "output": [ "1\n-1\n3\n3\n" ] }
265
8
Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n. Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given. Input The first line of the input will contain a single integer n (2 ≀ n ≀ 50). The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given. Output Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them. Examples Input 2 0 1 1 0 Output 2 1 Input 5 0 2 2 1 2 2 0 4 1 3 2 4 0 1 3 1 1 1 0 1 2 3 3 1 0 Output 2 5 4 1 3 Note In the first case, the answer can be {1, 2} or {2, 1}. In the second case, another possible answer is {2, 4, 5, 1, 3}.
def s(): n = int(input()) a = [] for _ in range(n): a.append(max(map(int,input().split(' ')))) a[a.index(n-1)] = n print(*a) s()
{ "input": [ "2\n0 1\n1 0\n", "5\n0 2 2 1 2\n2 0 4 1 3\n2 4 0 1 3\n1 1 1 0 1\n2 3 3 1 0\n" ], "output": [ "1 2 ", "2 4 5 1 3 " ] }
266
10
A super computer has been built in the Turtle Academy of Sciences. The computer consists of nΒ·mΒ·k CPUs. The architecture was the paralellepiped of size n Γ— m Γ— k, split into 1 Γ— 1 Γ— 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k. In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x, y, z) can send messages to CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) (of course, if they exist), there is no feedback, that is, CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) cannot send messages to CPU (x, y, z). Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a, b, c) controls CPU (d, e, f) , if there is a chain of CPUs (xi, yi, zi), such that (x1 = a, y1 = b, z1 = c), (xp = d, yp = e, zp = f) (here and below p is the length of the chain) and the CPU in the chain with number i (i < p) can send messages to CPU i + 1. Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x, y, z) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x, y, z) CPUs: (a, b, c) and (d, e, f), such that (a, b, c) controls (d, e, f) before (x, y, z) is turned off and stopped controlling it after the turning off. Input The first line contains three integers n, m and k (1 ≀ n, m, k ≀ 100) β€” the dimensions of the Super Computer. Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each β€” the description of a layer in the format of an m Γ— k table. Thus, the state of the CPU (x, y, z) is corresponded to the z-th character of the y-th line of the block number x. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line. Output Print a single integer β€” the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control. Examples Input 2 2 3 000 000 111 111 Output 2 Input 3 3 3 111 111 111 111 111 111 111 111 111 Output 19 Input 1 1 10 0101010101 Output 0 Note In the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2, 1, 2) turns off, it disrupts the control by CPU (2, 1, 3) over CPU (2, 1, 1), and when CPU (2, 2, 2) is turned off, it disrupts the control over CPU (2, 2, 3) by CPU (2, 2, 1). In the second sample all processors except for the corner ones are critical. In the third sample there is not a single processor controlling another processor, so the answer is 0.
def safe(pos): return pos[0] >= 0 and pos[0] < n and pos[1] >= 0 and pos[1] < m and pos[2] >= 0 and pos[2] < p def CPU_status(pos, number): return safe(pos) and super_computer[pos[0]][pos[1]][pos[2]] == number def critical(x,y,z): if super_computer[x][y][z] != '0': current = [x,y,z] for i in range(3): parent = current.copy() parent[i]-=1 if CPU_status(parent, '1'): for j in range(3): child, alt = current.copy(), parent.copy() child[j]+=1 alt[j]+=1 if CPU_status(child, '1') and (CPU_status(alt, '0') or j == i): return 1 return 0 n, m, p = map(int, input().split()) super_computer, crit = ([], 0) for i in range(n): super_computer.append([input() for _ in range(m)]) if i != n-1: input() for i in range(n): for j in range(m): for k in range(p): crit += critical(i,j,k) print(crit)
{ "input": [ "1 1 10\n0101010101\n", "2 2 3\n000\n000\n\n111\n111\n", "3 3 3\n111\n111\n111\n\n111\n111\n111\n\n111\n111\n111\n" ], "output": [ "0\n", "2\n", "19\n" ] }
267
7
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage. They will be N guests tonight: N - 1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to N - 1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, N. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure: The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes – in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.) You should know that zombies are very greedy and sly, and they know this too – basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order: 1. survive the event (they experienced death already once and know it is no fun), 2. get as many brains as possible. Heidi goes first and must make an offer which at least half of the attendees will accept, and which allocates at least one brain for Heidi herself. What is the smallest number of brains that have to be in the chest for this to be possible? Input The only line of input contains one integer: N, the number of attendees (1 ≀ N ≀ 109). Output Output one integer: the smallest number of brains in the chest which allows Heidi to take one brain home. Examples Input 1 Output 1 Input 4 Output 2 Note
def zombi(n): return (n + 1) // 2 print(zombi(int(input())))
{ "input": [ "1\n", "4\n" ], "output": [ "1\n", "2\n" ] }
268
10
Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score a and Lexa starts with score b. In a single turn, both Memory and Lexa get some integer in the range [ - k;k] (i.e. one integer among - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k) and add them to their current scores. The game has exactly t turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn. Memory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are (2k + 1)2t games in total. Since the answer can be very large, you should print it modulo 109 + 7. Please solve this problem for Memory. Input The first and only line of input contains the four integers a, b, k, and t (1 ≀ a, b ≀ 100, 1 ≀ k ≀ 1000, 1 ≀ t ≀ 100) β€” the amount Memory and Lexa start with, the number k, and the number of turns respectively. Output Print the number of possible games satisfying the conditions modulo 1 000 000 007 (109 + 7) in one line. Examples Input 1 2 2 1 Output 6 Input 1 1 1 2 Output 31 Input 2 12 3 1 Output 0 Note In the first sample test, Memory starts with 1 and Lexa starts with 2. If Lexa picks - 2, Memory can pick 0, 1, or 2 to win. If Lexa picks - 1, Memory can pick 1 or 2 to win. If Lexa picks 0, Memory can pick 2 to win. If Lexa picks 1 or 2, Memory cannot win. Thus, there are 3 + 2 + 1 = 6 possible games in which Memory wins.
def c(n, k): if k > n: return 0 a = b = 1 for i in range(n - k + 1, n + 1): a *= i for i in range(1, k + 1): b *= i return a // b a, b, k, t = map(int, input().split()) n, m, s = 2 * k + 1, 2 * t, 2 * k * t + b - a ans, mod = 0, 1000000007 for i in range(m + 1): ans = (ans + [1, -1][i & 1] * c(m, i) * c(m + s - n * i, m)) % mod print((pow(n, m, mod) - ans) % mod)
{ "input": [ "1 2 2 1\n", "1 1 1 2\n", "2 12 3 1\n" ], "output": [ " 6\n", " 31\n", "0\n" ] }
269
9
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city. Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai. For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: 1. the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2; 2. the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2; 3. the second monster can't eat the fifth monster because they are not neighbors; 4. the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≀ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last. You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other. Input The first line contains single integer n (1 ≀ n ≀ 500) β€” the number of monsters in the initial queue. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the initial weights of the monsters. The third line contains single integer k (1 ≀ k ≀ n) β€” the number of monsters in the queue after the joke. The fourth line contains k integers b1, b2, ..., bk (1 ≀ bj ≀ 5Β·108) β€” the weights of the monsters after the joke. Monsters are listed in the order from the beginning of the queue to the end. Output In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line. Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x β€” the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again. When one monster eats another the queue decreases. If there are several answers, print any of them. Examples Input 6 1 2 2 2 1 2 2 5 5 Output YES 2 L 1 R 4 L 3 L Input 5 1 2 3 4 5 1 15 Output YES 5 L 4 L 3 L 2 L Input 5 1 1 1 3 3 3 2 1 6 Output NO Note In the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue: * the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2]; * the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2]; * the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3]; * the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue.
f = lambda: list(map(int, input().split())) def g(i, j, k): z = y = i for x in range(i, j): if a[x] > a[y]: y = x if y > i: z = y else: while a[y] == a[i]: y += 1 if y == j: return [] y -= 1 l = [str(k + y - x) + ' L' for x in range(i, y)] r = [str(k + y - z) + ' R' for x in range(y + 1, j)] return r + l if z == i else l + r n, a, m, b = f()[0], f(), f()[0], f() d = ['YES'] s = i = k = 0 for j, q in enumerate(a, 1): s += q if k < m and s == b[k]: d += g(i, j, k + 1) s, i, k = 0, j, k + 1 print('\n'.join(d) if len(d) + m > n and k == m else 'NO')
{ "input": [ "5\n1 1 1 3 3\n3\n2 1 6\n", "6\n1 2 2 2 1 2\n2\n5 5\n", "5\n1 2 3 4 5\n1\n15\n" ], "output": [ "NO\n", "YES\n2 L\n1 R\n2 R\n2 R\n", "YES\n5 L\n4 L\n3 L\n2 L\n" ] }
270
7
In Berland each high school student is characterized by academic performance β€” integer value between 1 and 5. In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known β€” integer value between 1 and 5. The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal. To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class A and one student of class B. After that, they both change their groups. Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance. Input The first line of the input contains integer number n (1 ≀ n ≀ 100) β€” number of students in both groups. The second line contains sequence of integer numbers a1, a2, ..., an (1 ≀ ai ≀ 5), where ai is academic performance of the i-th student of the group A. The third line contains sequence of integer numbers b1, b2, ..., bn (1 ≀ bi ≀ 5), where bi is academic performance of the i-th student of the group B. Output Print the required minimum number of exchanges or -1, if the desired distribution of students can not be obtained. Examples Input 4 5 4 4 4 5 5 4 5 Output 1 Input 6 1 1 1 1 1 1 5 5 5 5 5 5 Output 3 Input 1 5 3 Output -1 Input 9 3 2 5 5 2 3 3 3 2 4 1 4 1 1 2 4 4 1 Output 4
def calc(): sum=0 for i in range(1,6): a1=a.count(i) a2=b.count(i) if((a1+a2)%2==1): return -1 sum+=abs(a1-a2) return (sum//4) n=int(input()) a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] print(calc())
{ "input": [ "6\n1 1 1 1 1 1\n5 5 5 5 5 5\n", "4\n5 4 4 4\n5 5 4 5\n", "9\n3 2 5 5 2 3 3 3 2\n4 1 4 1 1 2 4 4 1\n", "1\n5\n3\n" ], "output": [ "3\n", "1\n", "4\n", "-1\n" ] }
271
11
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: * Labels form a valid permutation of length n β€” an integer sequence such that each integer from 1 to n appears exactly once in it. * If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu. * Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions. Input The first line contains two integer numbers n, m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105). Next m lines contain two integer numbers v and u (1 ≀ v, u ≀ n, v β‰  u) β€” edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges. Output Print n numbers β€” lexicographically smallest correct permutation of labels of vertices. Examples Input 3 3 1 2 1 3 3 2 Output 1 3 2 Input 4 5 3 1 4 1 2 3 3 4 2 4 Output 4 1 2 3 Input 5 4 3 1 2 1 2 3 4 5 Output 3 1 2 4 5
import collections import heapq def constructGraph(n, edges): graph = collections.defaultdict(list) inDegree = [0 for _ in range(n)] for edge in edges: a, b = edge[0]-1, edge[1]-1 graph[b].append(a) inDegree[a] += 1 return [graph, inDegree] def solve(n, edges): graph, inDegree = constructGraph(n, edges) answer = [0 for _ in range(n)] pq = [] for i in range(n): if inDegree[i] == 0: heapq.heappush(pq, -i) current = n while pq: currentNode = -heapq.heappop(pq) answer[currentNode] = current current -= 1 if currentNode not in graph: continue for neighNode in graph[currentNode]: inDegree[neighNode] -= 1 if inDegree[neighNode] == 0: heapq.heappush(pq, -neighNode) return answer n, m = map(int, input().split()) edges = [] for _ in range(m): edges.append(list(map(int, input().split()))) print(*solve(n, edges), sep = ' ')
{ "input": [ "3 3\n1 2\n1 3\n3 2\n", "4 5\n3 1\n4 1\n2 3\n3 4\n2 4\n", "5 4\n3 1\n2 1\n2 3\n4 5\n" ], "output": [ "1 3 2\n", "4 1 2 3\n", "3 1 2 4 5\n" ] }
272
7
You are given two lists of non-zero digits. Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? Input The first line contains two integers n and m (1 ≀ n, m ≀ 9) β€” the lengths of the first and the second lists, respectively. The second line contains n distinct digits a1, a2, ..., an (1 ≀ ai ≀ 9) β€” the elements of the first list. The third line contains m distinct digits b1, b2, ..., bm (1 ≀ bi ≀ 9) β€” the elements of the second list. Output Print the smallest pretty integer. Examples Input 2 3 4 2 5 7 6 Output 25 Input 8 8 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 Output 1 Note In the first example 25, 46, 24567 are pretty, as well as many other integers. The smallest among them is 25. 42 and 24 are not pretty because they don't have digits from the second list. In the second example all integers that have at least one digit different from 9 are pretty. It's obvious that the smallest among them is 1, because it's the smallest positive integer.
def readInts(): return map(int, input().split()) input() a = list(readInts()) b = list(readInts()) for i in range(1,10): if ( i in a ) and ( i in b ): print(i) exit() a = min(a) b = min(b) print ( min(a,b)*10 + max(a,b) )
{ "input": [ "8 8\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n", "2 3\n4 2\n5 7 6\n" ], "output": [ "1\n", "25\n" ] }
273
7
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. <image> Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where * f1 = 1, * f2 = 1, * fn = fn - 2 + fn - 1 (n > 2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name. Input The first and only line of input contains an integer n (1 ≀ n ≀ 1000). Output Print Eleven's new name on the first and only line of output. Examples Input 8 Output OOOoOooO Input 15 Output OOOoOooOooooOoo
def main(): n = int(input()) name = ["o"] * n b,c=1,1 while c <= n: name[c - 1] = 'O' b,c = c,b+c print(''.join(name)) if __name__ == '__main__': main()
{ "input": [ "8\n", "15\n" ], "output": [ "OOOoOooO\n", "OOOoOooOooooOoo\n" ] }
274
7
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2. Diameter of multiset consisting of one point is 0. You are given n points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed d? Input The first line contains two integers n and d (1 ≀ n ≀ 100, 0 ≀ d ≀ 100) β€” the amount of points and the maximum allowed diameter respectively. The second line contains n space separated integers (1 ≀ xi ≀ 100) β€” the coordinates of the points. Output Output a single integer β€” the minimum number of points you have to remove. Examples Input 3 1 2 1 4 Output 1 Input 3 0 7 7 7 Output 0 Input 6 3 1 3 4 6 9 10 Output 3 Note In the first test case the optimal strategy is to remove the point with coordinate 4. The remaining points will have coordinates 1 and 2, so the diameter will be equal to 2 - 1 = 1. In the second test case the diameter is equal to 0, so its is unnecessary to remove any points. In the third test case the optimal strategy is to remove points with coordinates 1, 9 and 10. The remaining points will have coordinates 3, 4 and 6, so the diameter will be equal to 6 - 3 = 3.
def D(a): return a[-1]-a[0] n,d=map(int,input().split()) a=[int(i) for i in input().split()] a.sort() m=1000 for i in range(0,n): for j in range(i,n): if D(a[i:j+1])<=d: m=min(m,n-len(a[i:j+1])) print(m)
{ "input": [ "6 3\n1 3 4 6 9 10\n", "3 1\n2 1 4\n", "3 0\n7 7 7\n" ], "output": [ "3\n", "1\n", "0\n" ] }
275
10
One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units. In order for production to work, it is needed to deploy two services S_1 and S_2 to process incoming requests using the servers of the department. Processing of incoming requests of service S_i takes x_i resource units. The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service S_i is deployed using k_i servers, then the load is divided equally between these servers and each server requires only x_i / k_i (that may be a fractional number) resource units. Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides. Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services. Input The first line contains three integers n, x_1, x_2 (2 ≀ n ≀ 300 000, 1 ≀ x_1, x_2 ≀ 10^9) β€” the number of servers that the department may use, and resource units requirements for each of the services. The second line contains n space-separated integers c_1, c_2, …, c_n (1 ≀ c_i ≀ 10^9) β€” the number of resource units provided by each of the servers. Output If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes). Otherwise print the word "Yes" (without the quotes). In the second line print two integers k_1 and k_2 (1 ≀ k_1, k_2 ≀ n) β€” the number of servers used for each of the services. In the third line print k_1 integers, the indices of the servers that will be used for the first service. In the fourth line print k_2 integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them. Examples Input 6 8 16 3 5 2 9 8 7 Output Yes 3 2 1 2 6 5 4 Input 4 20 32 21 11 11 12 Output Yes 1 3 1 2 3 4 Input 4 11 32 5 5 16 16 Output No Input 5 12 20 7 8 4 11 9 Output No Note In the first sample test each of the servers 1, 2 and 6 will will provide 8 / 3 = 2.(6) resource units and each of the servers 5, 4 will provide 16 / 2 = 8 resource units. In the second sample test the first server will provide 20 resource units and each of the remaining servers will provide 32 / 3 = 10.(6) resource units.
def fin(c, x): return (x + c - 1) // c def ck(x, b): r = (n, n) for i in range(b, n): r = min(r, (i + fin(c[i][0], x), i)) return r def sol(r, l): if r[0] <= n and l[0] <= n and r[1] < n and l[1] < n : print("Yes") print(r[0] - r[1], l[0]- l[1]) print(' '.join([str(x[1]) for x in c[r[1]:r[0]]])) print(' '.join([str(x[1]) for x in c[l[1]:l[0]]])) return True else: return False n, x1, x2 = [int(x) for x in input().split()] c = sorted([(int(x), i + 1) for i, x in enumerate(input().split())]) r1 = ck(x1, 0) l1 = ck(x2, r1[0]) r2 = ck(x2, 0) l2 = ck(x1, r2[0]) if not sol(r1, l1) and not sol(l2, r2): print("No") # 6 8 16 # 3 5 2 9 8 7
{ "input": [ "4 20 32\n21 11 11 12\n", "4 11 32\n5 5 16 16\n", "6 8 16\n3 5 2 9 8 7\n", "5 12 20\n7 8 4 11 9\n" ], "output": [ "Yes\n1 3\n1 \n2 3 4 \n", "No\n", "Yes\n2 2\n2 6 \n5 4 ", "No\n" ] }
276
10
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned. If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible. Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up. Input The first line contains a single integer n (1 ≀ n ≀ 50) β€” the number of tasks. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 108), where ai represents the amount of power required for the i-th task. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 100), where bi is the number of processors that i-th task will utilize. Output Print a single integer value β€” the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up. Examples Input 6 8 10 9 9 8 10 1 1 1 1 1 1 Output 9000 Input 6 8 10 9 9 8 10 1 10 5 5 1 10 Output 1160 Note In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9. In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.
# Codeforces Round #488 by NEAR (Div. 2) import collections from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import math import sys def getIntList(): return list(map(int, input().split())) import bisect def makePair(z): return [(z[i], z[i+1]) for i in range(0,len(z),2) ] N, = getIntList() za = getIntList() zb = getIntList() sa = set(za) xa = list(sa) xa.sort(reverse = True) zz = [(t, sorted([zb[i] for i in range(N) if za[i] == t]) ) for t in xa ] #print(zz) lastdp = [[] for i in range(52)] lastdp[0] = [(0,0)] def addres(z, t): if len(z) ==0: z.append(t) return i = bisect.bisect_right(z,t) if i>0 and z[i-1][1] >= t[1]: return if i<len(z) and t[1] >= z[i][1]: z[i] = t return z.insert(i,t) for x in zz: nowdp = [[] for i in range(52)] for i in range(len(lastdp)): tz = lastdp[i] if len( tz ) ==0 : continue num = len(x[1]) hide = min(i, num ) tb = sum(x[1]) acc =0; for j in range(hide + 1): la = x[0] * (num-j) lb = tb - acc if j<num: acc += x[1][j] for t in tz: # t = (0,0) tr = (t[0] + la, t[1] + lb) addres(nowdp[ i -j + num -j] ,tr) lastdp = nowdp #print(lastdp) res = 10 ** 20 for x in lastdp: for y in x: t = math.ceil(y[0] *1000 / y[1] ) res = min( res,t) print(res)
{ "input": [ "6\n8 10 9 9 8 10\n1 1 1 1 1 1\n", "6\n8 10 9 9 8 10\n1 10 5 5 1 10\n" ], "output": [ "9000\n", "1160\n" ] }
277
10
You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C. Find the number of different groups of three integers (a, b, c) such that 1≀ a≀ b≀ c and parallelepiped AΓ— BΓ— C can be paved with parallelepipeds aΓ— bΓ— c. Note, that all small parallelepipeds have to be rotated in the same direction. For example, parallelepiped 1Γ— 5Γ— 6 can be divided into parallelepipeds 1Γ— 3Γ— 5, but can not be divided into parallelepipeds 1Γ— 2Γ— 3. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each of the next t lines contains three integers A, B and C (1 ≀ A, B, C ≀ 10^5) β€” the sizes of the parallelepiped. Output For each test case, print the number of different groups of three points that satisfy all given conditions. Example Input 4 1 1 1 1 6 1 2 2 2 100 100 100 Output 1 4 4 165 Note In the first test case, rectangular parallelepiped (1, 1, 1) can be only divided into rectangular parallelepiped with sizes (1, 1, 1). In the second test case, rectangular parallelepiped (1, 6, 1) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 1, 3) and (1, 1, 6). In the third test case, rectangular parallelepiped (2, 2, 2) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 2, 2) and (2, 2, 2).
N=100001 fac=[0 for i in range(N)] for i in range(1,N): for j in range(i,N,i): fac[j]+=1 def gcd(a,b): if a<b: a,b=b,a while b>0: a,b=b,a%b return a def ctt(A,B,C): la=fac[A] lb=fac[B] lc=fac[C] ab=gcd(A,B) ac=gcd(A,C) bc=gcd(B,C) abc=gcd(ab,C) dupabc=fac[abc] dupac=fac[ac]-dupabc dupbc=fac[bc]-dupabc dupab=fac[ab]-dupabc lax=la-dupabc-dupab-dupac lbx=lb-dupabc-dupab-dupbc lcx=lc-dupabc-dupac-dupbc ctx=lax*lbx*lcx ctx+=lax*lbx*(lc-lcx) ctx+=lax*lcx*(lb-lbx) ctx+=lcx*lbx*(la-lax) ctx+=lax*((lb-lbx)*(lc-lcx)-(dupabc+dupbc)*(dupabc+dupbc-1)/2) ctx+=lbx*((la-lax)*(lc-lcx)-(dupabc+dupac)*(dupabc+dupac-1)/2) ctx+=lcx*((la-lax)*(lb-lbx)-(dupabc+dupab)*(dupabc+dupab-1)/2) ctx+=dupab*dupac*dupbc ctx+=dupab*dupac*(dupab+dupac+2)/2 ctx+=dupab*dupbc*(dupab+dupbc+2)/2 ctx+=dupbc*dupac*(dupbc+dupac+2)/2 ctx+=dupabc*(dupab*dupac+dupab*dupbc+dupbc*dupac) ctx+=dupabc*(dupab*(dupab+1)+(dupbc+1)*dupbc+(dupac+1)*dupac)/2 ctx+=(dupabc+1)*dupabc*(dupab+dupac+dupbc)/2 ctx+=(dupabc*dupabc+dupabc*(dupabc-1)*(dupabc-2)/6) return int(ctx) n=int(input()) for _ in range(n): a,b,c = map(int,input().split()) print(ctt(a,b,c)) exit()
{ "input": [ "4\n1 1 1\n1 6 1\n2 2 2\n100 100 100\n" ], "output": [ "1\n4\n4\n165\n" ] }
278
8
When Masha came to math classes today, she saw two integer sequences of length n - 1 on the blackboard. Let's denote the elements of the first sequence as a_i (0 ≀ a_i ≀ 3), and the elements of the second sequence as b_i (0 ≀ b_i ≀ 3). Masha became interested if or not there is an integer sequence of length n, which elements we will denote as t_i (0 ≀ t_i ≀ 3), so that for every i (1 ≀ i ≀ n - 1) the following is true: * a_i = t_i | t_{i + 1} (where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR)) and * b_i = t_i \& t_{i + 1} (where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND)). The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence t_i of length n exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them. Input The first line contains a single integer n (2 ≀ n ≀ 10^5) β€” the length of the sequence t_i. The second line contains n - 1 integers a_1, a_2, …, a_{n-1} (0 ≀ a_i ≀ 3) β€” the first sequence on the blackboard. The third line contains n - 1 integers b_1, b_2, …, b_{n-1} (0 ≀ b_i ≀ 3) β€” the second sequence on the blackboard. Output In the first line print "YES" (without quotes), if there is a sequence t_i that satisfies the conditions from the statements, and "NO" (without quotes), if there is no such sequence. If there is such a sequence, on the second line print n integers t_1, t_2, …, t_n (0 ≀ t_i ≀ 3) β€” the sequence that satisfies the statements conditions. If there are multiple answers, print any of them. Examples Input 4 3 3 2 1 2 0 Output YES 1 3 2 0 Input 3 1 3 3 2 Output NO Note In the first example it's easy to see that the sequence from output satisfies the given conditions: * t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1 and t_1 \& t_2 = (01_2) \& (11_2) = (01_2) = 1 = b_1; * t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2 and t_2 \& t_3 = (11_2) \& (10_2) = (10_2) = 2 = b_2; * t_3 | t_4 = (10_2) | (00_2) = (10_2) = 2 = a_3 and t_3 \& t_4 = (10_2) \& (00_2) = (00_2) = 0 = b_3. In the second example there is no such sequence.
def my(a, b, c): for x, y in zip(a, b): for z in range(4): if c[-1] | z == x and c[-1] & z == y: c += [z] break else: return [] return c n = int(input()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] for i in range(4): t = my(a, b, [i]) if t: print('YES') print(*t) break else: print('NO')
{ "input": [ "4\n3 3 2\n1 2 0\n", "3\n1 3\n3 2\n" ], "output": [ "YES\n1 3 2 0 ", "NO" ] }
279
8
Initially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0, 2, 3] is 1, while the mex of the multiset [1, 2, 1] is 0. More formally, on the step m, when Ildar already has an array a_1, a_2, …, a_{m-1}, he chooses some subset of indices 1 ≀ i_1 < i_2 < … < i_k < m (possibly, empty), where 0 ≀ k < m, and appends the mex(a_{i_1}, a_{i_2}, … a_{i_k}) to the end of the array. After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array a_1, a_2, …, a_n the minimum step t such that he has definitely made a mistake on at least one of the steps 1, 2, …, t, or determine that he could have obtained this array without mistakes. Input The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of steps Ildar made. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 10^9) β€” the array Ildar obtained. Output If Ildar could have chosen the subsets on each step in such a way that the resulting array is a_1, a_2, …, a_n, print -1. Otherwise print a single integer t β€” the smallest index of a step such that a mistake was made on at least one step among steps 1, 2, …, t. Examples Input 4 0 1 2 1 Output -1 Input 3 1 0 1 Output 1 Input 4 0 1 2 239 Output 4 Note In the first example it is possible that Ildar made no mistakes. Here is the process he could have followed. * 1-st step. The initial array is empty. He can choose an empty subset and obtain 0, because the mex of an empty set is 0. Appending this value to the end he gets the array [0]. * 2-nd step. The current array is [0]. He can choose a subset [0] and obtain an integer 1, because mex(0) = 1. Appending this value to the end he gets the array [0,1]. * 3-rd step. The current array is [0,1]. He can choose a subset [0,1] and obtain an integer 2, because mex(0,1) = 2. Appending this value to the end he gets the array [0,1,2]. * 4-th step. The current array is [0,1,2]. He can choose a subset [0] and obtain an integer 1, because mex(0) = 1. Appending this value to the end he gets the array [0,1,2,1]. Thus, he can get the array without mistakes, so the answer is -1. In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from 0. In the third example he could have obtained [0, 1, 2] without mistakes, but 239 is definitely wrong.
def mex(a,n): m = -1 for i in range(n): if a[i]-m>1: return i+1 m = max(m,a[i]) return -1 n = int(input()) a = [*map(int,input().split())] print(mex(a,n))
{ "input": [ "3\n1 0 1\n", "4\n0 1 2 1\n", "4\n0 1 2 239\n" ], "output": [ "1\n", "-1\n", "4\n" ] }
280
8
You are given an integer number n. The following algorithm is applied to it: 1. if n = 0, then end algorithm; 2. find the smallest prime divisor d of n; 3. subtract d from n and go to step 1. Determine the number of subtrations the algorithm will make. Input The only line contains a single integer n (2 ≀ n ≀ 10^{10}). Output Print a single integer β€” the number of subtractions the algorithm will make. Examples Input 5 Output 1 Input 4 Output 2 Note In the first example 5 is the smallest prime divisor, thus it gets subtracted right away to make a 0. In the second example 2 is the smallest prime divisor at both steps.
def subtraction(n): i=2 while i*i<n and n%i: i+=1 if i*i>n: i=n return 1+(n-i)//2 n=int(input()) print(subtraction(n))
{ "input": [ "4\n", "5\n" ], "output": [ "2\n", "1\n" ] }
281
8
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: <image> Petr called his car dealer, who instructed him to rotate the lock's wheel exactly n times. The i-th rotation should be a_i degrees, either clockwise or counterclockwise, and after all n rotations the pointer should again point at zero. This confused Petr a little bit as he isn't sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all n rotations the pointer will point at zero again. Input The first line contains one integer n (1 ≀ n ≀ 15) β€” the number of rotations. Each of the following n lines contains one integer a_i (1 ≀ a_i ≀ 180) β€” the angle of the i-th rotation in degrees. Output If it is possible to do all the rotations so that the pointer will point at zero after all of them are performed, print a single word "YES". Otherwise, print "NO". Petr will probably buy a new car in this case. You can print each letter in any case (upper or lower). Examples Input 3 10 20 30 Output YES Input 3 10 10 10 Output NO Input 3 120 120 120 Output YES Note In the first example, we can achieve our goal by applying the first and the second rotation clockwise, and performing the third rotation counterclockwise. In the second example, it's impossible to perform the rotations in order to make the pointer point at zero in the end. In the third example, Petr can do all three rotations clockwise. In this case, the whole wheel will be rotated by 360 degrees clockwise and the pointer will point at zero again.
def f(a, i): if i == n: return a % 360 == 0 return f(a - ls[i], i+1) or f(a + ls[i], i+1) n = int(input()) ls = [int(input()) for _ in '0'*n] print('YNEOS'[not f(0,0)::2])
{ "input": [ "3\n10\n10\n10\n", "3\n120\n120\n120\n", "3\n10\n20\n30\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
282
9
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed. For example, the following matrices are palindromic: <image> The following matrices are not palindromic because they change after the order of rows is reversed: <image> The following matrices are not palindromic because they change after the order of columns is reversed: <image> You are given n^2 integers. Put them into a matrix of n rows and n columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO". Input The first line contains one integer n (1 ≀ n ≀ 20). The second line contains n^2 integers a_1, a_2, ..., a_{n^2} (1 ≀ a_i ≀ 1000) β€” the numbers to put into a matrix of n rows and n columns. Output If it is possible to put all of the n^2 numbers into a matrix of n rows and n columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print n lines with n space-separated numbers β€” the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable. Examples Input 4 1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1 Output YES 1 2 2 1 8 2 2 8 8 2 2 8 1 2 2 1 Input 3 1 1 1 1 1 3 3 3 3 Output YES 1 3 1 3 1 3 1 3 1 Input 4 1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1 Output NO Input 1 10 Output YES 10 Note Note that there exist multiple answers for the first two examples.
n = int(input()) a = list(map(int, input().split())) d = {} res = [[0] * n for i in range(n)] for i in a: d[i] = d.get(i, 0) + 1 def put(a, i, j, k, d): d[k] -= 4 a[i][j] = k a[n-i-1][j] = k a[i][n-j-1] = k a[n-i-1][n-j-1] = k for i in range(n//2): for j in range(n//2): for k in d: if d[k] >= 4: put(res, i, j, k, d) break if n % 2 == 1: for i in range(n//2): for k in d: if d[k] >= 2: d[k] -= 2 res[i][n//2] = k res[n-i-1][n//2] = k break for k in d: if d[k] >= 2: d[k] -= 2 res[n//2][i] = k res[n//2][n-i-1] = k break if n % 2 == 1: for k in d: if d[k] >= 1: d[k] -= 1 res[n//2][n//2] = k break if any(v for k, v in d.items()): print("NO") exit() print("YES") for i in res: print(' '.join(map(str, i)))
{ "input": [ "4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1\n", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1\n", "1\n10\n", "3\n1 1 1 1 1 3 3 3 3\n" ], "output": [ "YES\n1 2 2 1 \n2 8 8 2 \n2 8 8 2 \n1 2 2 1 \n", "NO\n", "YES\n10 \n", "YES\n1 3 1 \n3 1 3 \n1 3 1 \n" ] }
283
12
You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
n,m = map(int,input().split()) a = [] g = [[] for i in range(n)] for i in range(m): x,y = map(int,input().split()) x-=1;y-=1 g[x].append(y) g[y].append(x) a.append([x,y]) b = [-1]*n b[0] = 0 que = [0] def nibu(x): for i in g[x]: if b[i] != -1 and (b[i] == b[x]): print("NO") exit() elif b[i] == -1: b[i] = b[x]^1 que.append(i) while que: nibu(que.pop()) ans = [] for i in range(m): if b[a[i][0]] == 0: ans.append("0") else: ans.append("1") print("YES") print("".join(ans))
{ "input": [ "6 5\n1 5\n2 1\n1 4\n3 1\n6 1\n" ], "output": [ "YES\n10100" ] }
284
11
You are given two arrays a and b, both of length n. Let's define a function f(l, r) = βˆ‘_{l ≀ i ≀ r} a_i β‹… b_i. Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of βˆ‘_{1 ≀ l ≀ r ≀ n} f(l, r). Since the answer can be very large, you have to print it modulo 998244353. Note that you should minimize the answer but not its remainder. Input The first line of the input contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in a and b. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6), 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 (1 ≀ b_j ≀ 10^6), where b_j is the j-th element of b. Output Print one integer β€” the minimum possible value of βˆ‘_{1 ≀ l ≀ r ≀ n} f(l, r) after rearranging elements of b, taken modulo 998244353. Note that you should minimize the answer but not its remainder. Examples Input 5 1 8 7 2 4 9 7 2 9 3 Output 646 Input 1 1000000 1000000 Output 757402647 Input 2 1 3 4 2 Output 20
def main(): R = lambda : list(map(int,input().split())) n = int(input()) a = sorted([num*(idx+1)*(n-idx) for idx,num in enumerate(R())]) b = sorted(R(),reverse = True) print(sum((x*y) for x,y in zip(a,b))%998244353) if __name__ == '__main__': main()
{ "input": [ "1\n1000000\n1000000\n", "5\n1 8 7 2 4\n9 7 2 9 3\n", "2\n1 3\n4 2\n" ], "output": [ "757402647\n", "646\n", "20\n" ] }
285
10
The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250. Heidi recently got her hands on a multiverse observation tool. She was able to see all n universes lined up in a row, with non-existent links between them. She also noticed that the Doctor was in the k-th universe. The tool also points out that due to restrictions originating from the space-time discontinuum, the number of universes will never exceed m. Obviously, the multiverse is unstable because of free will. Each time a decision is made, one of two events will randomly happen: a new parallel universe is created, or a non-existent link is broken. More specifically, * When a universe is created, it will manifest itself between any two adjacent universes or at one of the ends. * When a link is broken, it could be cut between any two adjacent universes. After separating the multiverse into two segments, the segment NOT containing the Doctor will cease to exist. Heidi wants to perform a simulation of t decisions. Each time a decision is made, Heidi wants to know the length of the multiverse (i.e. the number of universes), and the position of the Doctor. Input The first line contains four integers n, k, m and t (2 ≀ k ≀ n ≀ m ≀ 250, 1 ≀ t ≀ 1000). Each of the following t lines is in one of the following formats: * "1 i" β€” meaning that a universe is inserted at the position i (1 ≀ i ≀ l + 1), where l denotes the current length of the multiverse. * "0 i" β€” meaning that the i-th link is broken (1 ≀ i ≀ l - 1), where l denotes the current length of the multiverse. Output Output t lines. Each line should contain l, the current length of the multiverse and k, the current position of the Doctor. It is guaranteed that the sequence of the steps will be valid, i.e. the multiverse will have length at most m and when the link breaking is performed, there will be at least one universe in the multiverse. Example Input 5 2 10 4 0 1 1 1 0 4 1 2 Output 4 1 5 2 4 2 5 3 Note The multiverse initially consisted of 5 universes, with the Doctor being in the second. First, link 1 was broken, leaving the multiverse with 4 universes, and the Doctor in the first. Then, a universe was added to the leftmost end of the multiverse, increasing the multiverse length to 5, and the Doctor was then in the second universe. Then, the rightmost link was broken. Finally, a universe was added between the first and the second universe.
import sys def main(): input = sys.stdin.readline() n, k, m, t = [int(j) for j in input.split()] for i in range(t): input = sys.stdin.readline() d, c = [int(j) for j in input.split()] if d == 0: if c<k: n -= c k -= c else: n = c else: if c<=k: k += 1 n += 1 print(n,k) if __name__ == '__main__': main()
{ "input": [ "5 2 10 4\n0 1\n1 1\n0 4\n1 2\n" ], "output": [ "4 1\n5 2\n4 2\n5 3\n" ] }
286
7
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after the student 1 in clockwise order (there are no students between them), the student 3 comes right after the student 2 in clockwise order, and so on, and the student n comes right after the student n - 1 in clockwise order. A counterclockwise round dance is almost the same thing β€” the only difference is that the student i should be right after the student i - 1 in counterclockwise order (this condition should be met for every i from 2 to n). For example, if the indices of students listed in clockwise order are [2, 3, 4, 5, 1], then they can start a clockwise round dance. If the students have indices [3, 2, 1, 4] in clockwise order, then they can start a counterclockwise round dance. Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 200) β€” the number of queries. Then q queries follow. The first line of the query contains one integer n (1 ≀ n ≀ 200) β€” the number of students. The second line of the query contains a permutation of indices p_1, p_2, ..., p_n (1 ≀ p_i ≀ n), where p_i is the index of the i-th student (in clockwise order). It is guaranteed that all p_i are distinct integers from 1 to n (i. e. they form a permutation). Output For each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO". Example Input 5 4 1 2 3 4 3 1 3 2 5 1 2 3 5 4 1 1 5 3 2 1 5 4 Output YES YES NO YES YES
d=lambda l,n: l[n:] + l[:n] def k(m): for i in range(len(m)): if(d(m,i)==sorted(m) or d(m,i)==sorted(m,reverse=True)): return "YES" return "NO" for _ in range(int(input())): n=int(input()) f=list(map(int,input().split())) print(k(f))
{ "input": [ "5\n4\n1 2 3 4\n3\n1 3 2\n5\n1 2 3 5 4\n1\n1\n5\n3 2 1 5 4\n" ], "output": [ "YES\nYES\nNO\nYES\nYES\n" ] }
287
9
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input The first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation. Output If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers. Examples Input 7 4 Output 1 Input 4 7 Output 1 Note A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations. In the first sample the permutation looks like that: 1 2 3 4 6 7 5 The only suitable position is 4. In the second sample the permutation looks like that: 2 1 3 4 The only suitable position is 4.
def lucky(x): s=str(x) return s.count('4')+s.count('7')==len(s) def Gen_lucky(n): if(len(n)==1): if(n<"4"): return 0 if(n<"7"): return 1 return 2 s=str(n) if(s[0]<'4'): return 0 if(s[0]=='4'): return Gen_lucky(s[1:]) if(s[0]<'7'): return 2**(len(s)-1) if(s[0]=='7'): return 2**(len(s)-1)+Gen_lucky(s[1:]) else: return 2**len(s) def Form(X,k): if(k==0): return X for i in range(len(X)): if(k>=F[len(X)-i-1]): h=k//F[len(X)-i-1] r=k%F[len(X)-i-1] G=list(X[i+1:]) G.remove(X[i+h]) G=[X[i]]+G return Form(X[:i]+[X[i+h]]+G,r) p=1 F=[1] i=1 while(p<=10**15): p*=i F.append(p) i+=1 n,k=map(int,input().split()) if(n<=14): if(k>F[n]): print(-1) else: L=Form(list(range(1,n+1)),k-1) x=0 for i in range(n): if(lucky(i+1) and lucky(L[i])): x+=1 print(x) else: L=Form(list(range(n-14,n+1)),k-1) ss=str(n-15) x=0 for i in range(1,len(ss)): x+=2**i x+=Gen_lucky(ss) for i in range(n-14,n+1): if(lucky(L[i-n+14]) and lucky(i)): x+=1 print(x)
{ "input": [ "4 7\n", "7 4\n" ], "output": [ "1", "1" ] }
288
7
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on. <image> Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 2). For example, the complexity of 1 4 2 3 5 is 2 and the complexity of 1 3 5 7 6 4 2 is 1. No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of light bulbs on the garland. The second line contains n integers p_1,\ p_2,\ …,\ p_n (0 ≀ p_i ≀ n) β€” the number on the i-th bulb, or 0 if it was removed. Output Output a single number β€” the minimum complexity of the garland. Examples Input 5 0 5 0 2 3 Output 2 Input 7 1 0 0 5 0 0 2 Output 1 Note In the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only (5, 4) and (2, 3) are the pairs of adjacent bulbs that have different parity. In the second case, one of the correct answers is 1 7 3 5 6 4 2.
from functools import lru_cache N = int(input()) nums = list(map(int, input().strip().split())) @lru_cache(None) def dp(a, b, last): if a < 0 or b < 0: return N if a == 0 and b == 0: return 0 i = N - a - b if nums[i] != 0: bit = nums[i] & 1 if bit == 0: a -= 1 else: b -= 1 return dp(a, b, bit) + (bit ^ last) else: return min(dp(a - 1, b, 0) + last, dp(a, b - 1, 1) + 1 - last) b, a = (N + 1) // 2, N // 2 print(min(dp(a, b, 0), dp(a, b, 1)))
{ "input": [ "7\n1 0 0 5 0 0 2\n", "5\n0 5 0 2 3\n" ], "output": [ "1\n", "2\n" ] }
289
8
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence! We say that a string formed by n characters '(' or ')' is simple if its length n is even and positive, its first n/2 characters are '(', and its last n/2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple. Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty. Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead? A sequence of characters a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Input The only line of input contains a string s (1 ≀ |s| ≀ 1000) formed by characters '(' and ')', where |s| is the length of s. Output In the first line, print an integer k β€” the minimum number of operations you have to apply. Then, print 2k lines describing the operations in the following format: For each operation, print a line containing an integer m β€” the number of characters in the subsequence you will remove. Then, print a line containing m integers 1 ≀ a_1 < a_2 < ... < a_m β€” the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string. If there are multiple valid sequences of operations with the smallest k, you may print any of them. Examples Input (()(( Output 1 2 1 3 Input )( Output 0 Input (()()) Output 1 4 1 2 5 6 Note In the first sample, the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '(((', and no more operations can be performed on it. Another valid answer is choosing indices 2 and 3, which results in the same final string. In the second sample, it is already impossible to perform any operations.
import sys input = sys.stdin.readline def main(): al = list(input()) al.pop() n = len(al) ans = [False]*n ok = 0 i,j = 0,n-1 while i<j: while i<n and al[i]==')': i+=1 while j>=0 and al[j]=='(': j-=1 if i<j and al[i]=='(' and al[j]==')': ans[i] = ans[j] = True ok+=2 i+=1 j-=1 print(1 if ok!=0 else 0) if ok!=0: print(ok) for i in range(n): if ans[i]==True: print(i+1,end=' ') main()
{ "input": [ "(()((\n", "(()())\n", ")(\n" ], "output": [ "1\n2\n1 3 ", "1\n4\n1 2 5 6 ", "0" ] }
290
10
Slime and his n friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the i-th player has a_i biscuits. At each second, Slime will choose a biscuit randomly uniformly among all a_1 + a_2 + … + a_n biscuits, and the owner of this biscuit will give it to a random uniform player among n-1 players except himself. The game stops when one person will have all the biscuits. As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time. For convenience, as the answer can be represented as a rational number p/q for coprime p and q, you need to find the value of (p β‹… q^{-1})mod 998 244 353. You can prove that qmod 998 244 353 β‰  0. Input The first line contains one integer n\ (2≀ n≀ 100 000): the number of people playing the game. The second line contains n non-negative integers a_1,a_2,...,a_n\ (1≀ a_1+a_2+...+a_n≀ 300 000), where a_i represents the number of biscuits the i-th person own at the beginning. Output Print one integer: the expected value of the time that the game will last, modulo 998 244 353. Examples Input 2 1 1 Output 1 Input 2 1 2 Output 3 Input 5 0 0 0 0 35 Output 0 Input 5 8 4 2 0 1 Output 801604029 Note For the first example, in the first second, the probability that player 1 will give the player 2 a biscuit is 1/2, and the probability that player 2 will give the player 1 a biscuit is 1/2. But anyway, the game will stop after exactly 1 second because only one player will occupy all biscuits after 1 second, so the answer is 1.
MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(cC) curr %= MOD l.append(curr) out = 0 for v in a: out += l[tot - v] out %= MOD zero = l[tot] out -= (n - 1) * zero out *= inv(n) print(out % MOD)
{ "input": [ "2\n1 2\n", "5\n8 4 2 0 1\n", "2\n1 1\n", "5\n0 0 0 0 35\n" ], "output": [ "3\n", "801604029\n", "1\n", "0\n" ] }
291
8
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it). It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression a tor b. Both numbers a and b are written in the ternary notation one under the other one (b under a). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 1410 tor 5010 = 01123 tor 12123 = 10213 = 3410. Petya wrote numbers a and c on a piece of paper. Help him find such number b, that a tor b = c. If there are several such numbers, print the smallest one. Input The first line contains two integers a and c (0 ≀ a, c ≀ 109). Both numbers are written in decimal notation. Output Print the single integer b, such that a tor b = c. If there are several possible numbers b, print the smallest one. You should print the number in decimal notation. Examples Input 14 34 Output 50 Input 50 34 Output 14 Input 387420489 225159023 Output 1000000001 Input 5 5 Output 0
def f(l): a,c = l p = 1 r = 0 while a>0 or c>0: r += p*((c%3-a%3)%3) p *= 3 c = c//3 a = a//3 return r l = list(map(int,input().split())) print(f(l))
{ "input": [ "387420489 225159023\n", "14 34\n", "50 34\n", "5 5\n" ], "output": [ "1000000001\n", "50\n", "14\n", "0\n" ] }
292
8
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem: You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k operations with this array. Define one operation as the following: 1. Set d to be the maximum value of your array. 2. For every i from 1 to n, replace a_{i} with d-a_{i}. The goal is to predict the contents in the array after k operations. Please help Ray determine what the final sequence will look like! Input Each test contains multiple test cases. The first line contains the number of cases t (1 ≀ t ≀ 100). Description of the test cases follows. The first line of each test case contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 10^{18}) – the length of your array and the number of operations to perform. The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (-10^9 ≀ a_{i} ≀ 10^9) – the initial contents of your array. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each case, print the final version of array a after k operations described above. Example Input 3 2 1 -199 192 5 19 5 -1 4 2 0 1 2 69 Output 391 0 0 6 1 3 5 0 Note In the first test case the array changes as follows: * Initially, the array is [-199, 192]. d = 192. * After the operation, the array becomes [d-(-199), d-192] = [391, 0].
def iter(a): m = max(a) return [m-a for a in a] for _ in range(int(input())): n, k = map(int, input().split()) a = [int(x) for x in input().split()] print(*iter(a)) if k%2 else print(*iter(iter(a)))
{ "input": [ "3\n2 1\n-199 192\n5 19\n5 -1 4 2 0\n1 2\n69\n" ], "output": [ "391 0 \n0 6 1 3 5 \n0 \n" ] }
293
9
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them. Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely: * The piranha i can eat the piranha i-1 if the piranha i-1 exists and a_{i - 1} < a_i. * The piranha i can eat the piranha i+1 if the piranha i+1 exists and a_{i + 1} < a_i. When the piranha i eats some piranha, its size increases by one (a_i becomes a_i + 1). Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas. Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them. For example, if a = [5, 3, 4, 4, 5], then the third piranha can be dominant. Consider the sequence of its moves: * The piranha eats the second piranha and a becomes [5, \underline{5}, 4, 5] (the underlined piranha is our candidate). * The piranha eats the third piranha and a becomes [5, \underline{6}, 5]. * The piranha eats the first piranha and a becomes [\underline{7}, 5]. * The piranha eats the second piranha and a becomes [\underline{8}]. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of piranhas in the aquarium. The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9), where a_i is the size of the i-th piranha. It is guaranteed that the sum of n does not exceed 3 β‹… 10^5 (βˆ‘ n ≀ 3 β‹… 10^5). Output For each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any. Example Input 6 5 5 3 4 4 5 3 1 1 1 5 4 4 3 4 4 5 5 5 4 3 2 3 1 1 2 5 5 4 3 5 5 Output 3 -1 4 3 3 1 Note The first test case of the example is described in the problem statement. In the second test case of the example, there are no dominant piranhas in the aquarium. In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes [4, 4, 5, 4], then it can eat any other piranha in the aquarium.
def f(): input() s = list(map(int, input().split())) i = s.index(max(s)) + 1 if i > 1: return i while i < len(s): if s[i - 1] != s[i]: return i i += 1 return -1 for i in range(int(input())): print(f())
{ "input": [ "6\n5\n5 3 4 4 5\n3\n1 1 1\n5\n4 4 3 4 4\n5\n5 5 4 3 2\n3\n1 1 2\n5\n5 4 3 5 5\n" ], "output": [ "1\n-1\n2\n2\n3\n1\n" ] }
294
8
There are n glasses on the table numbered 1, …, n. The glass i can hold up to a_i units of water, and currently contains b_i units of water. You would like to choose k glasses and collect as much water in them as possible. To that effect you can pour water from one glass to another as many times as you like. However, because of the glasses' awkward shape (and totally unrelated to your natural clumsiness), each time you try to transfer any amount of water, half of the amount is spilled on the floor. Formally, suppose a glass i currently contains c_i units of water, and a glass j contains c_j units of water. Suppose you try to transfer x units from glass i to glass j (naturally, x can not exceed c_i). Then, x / 2 units is spilled on the floor. After the transfer is done, the glass i will contain c_i - x units, and the glass j will contain min(a_j, c_j + x / 2) units (excess water that doesn't fit in the glass is also spilled). Each time you transfer water, you can arbitrarlly choose from which glass i to which glass j to pour, and also the amount x transferred can be any positive real number. For each k = 1, …, n, determine the largest possible total amount of water that can be collected in arbitrarily chosen k glasses after transferring water between glasses zero or more times. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of glasses. The following n lines describe the glasses. The i-th of these lines contains two integers a_i and b_i (0 ≀ b_i ≀ a_i ≀ 100, a_i > 0) β€” capacity, and water amount currently contained for the glass i, respectively. Output Print n real numbers β€” the largest amount of water that can be collected in 1, …, n glasses respectively. Your answer will be accepted if each number is within 10^{-9} absolute or relative tolerance of the precise answer. Example Input 3 6 5 6 5 10 2 Output 7.0000000000 11.0000000000 12.0000000000 Note In the sample case, you can act as follows: * for k = 1, transfer water from the first two glasses to the third one, spilling (5 + 5) / 2 = 5 units and securing 2 + (5 + 5) / 2 = 7 units; * for k = 2, transfer water from the third glass to any of the first two, spilling 2 / 2 = 1 unit and securing 5 + 5 + 2 / 2 = 11 units; * for k = 3, do nothing. All 5 + 5 + 2 = 12 units are secured.
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n=int(input()) AB=[tuple(map(int,input().split())) for i in range(n)] SUMB=0 for a,b in AB: SUMB+=b def calc(suma,sumb): return min(suma,(SUMB+sumb)/2) DP=[[-1]*10005 for i in range(n+1)] DP[0][0]=0 for i in range(n): a,b=AB[i] for j in range(i,-1,-1): for k in range(100*j,-1,-1): if DP[j][k]!=-1: DP[j+1][k+a]=max(DP[j+1][k+a],DP[j][k]+b) A=[] for i in range(1,n+1): ANS=0 for j in range(100*i+1): if DP[i][j]==-1: continue ANS=max(ANS,calc(j,DP[i][j])) A.append(ANS) print(*A)
{ "input": [ "3\n6 5\n6 5\n10 2\n" ], "output": [ "\n7.0000000000 11.0000000000 12.0000000000\n" ] }
295
8
After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you). <image> You are given an array h_1, h_2, ..., h_n, where h_i is the height of the i-th mountain, and k β€” the number of boulders you have. You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is h_i): * if h_i β‰₯ h_{i + 1}, the boulder will roll to the next mountain; * if h_i < h_{i + 1}, the boulder will stop rolling and increase the mountain height by 1 (h_i = h_i + 1); * if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the k-th boulder or determine that it will fall into the waste collection system. Input The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers n and k (1 ≀ n ≀ 100; 1 ≀ k ≀ 10^9) β€” the number of mountains and the number of boulders. The second line contains n integers h_1, h_2, ..., h_n (1 ≀ h_i ≀ 100) β€” the height of the mountains. It is guaranteed that the sum of n over all test cases does not exceed 100. Output For each test case, print -1 if the k-th boulder will fall into the collection system. Otherwise, print the position of the k-th boulder. Example Input 4 4 3 4 1 2 3 2 7 1 8 4 5 4 1 2 3 3 1 5 3 1 Output 2 1 -1 -1 Note Let's simulate the first case: * The first boulder starts at i = 1; since h_1 β‰₯ h_2 it rolls to i = 2 and stops there because h_2 < h_3. * The new heights are [4,2,2,3]. * The second boulder starts at i = 1; since h_1 β‰₯ h_2 the boulder rolls to i = 2; since h_2 β‰₯ h_3 the boulder rolls to i = 3 and stops there because h_3 < h_4. * The new heights are [4,2,3,3]. * The third boulder starts at i = 1; since h_1 β‰₯ h_2 it rolls to i = 2 and stops there because h_2 < h_3. * The new heights are [4,3,3,3]. The positions where each boulder stopped are the following: [2,3,2]. In the second case, all 7 boulders will stop right at the first mountain rising its height from 1 to 8. The third case is similar to the first one but now you'll throw 5 boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to [4, 3, 3, 3], that's why the other two boulders will fall into the collection system. In the fourth case, the first and only boulders will fall straight into the collection system.
def process(h): for i in range(1, len(h)): if h[i] > h[i-1]: h[i-1] += 1 return i-1 return -1 for _ in range(int(input())): n, k = list(map(int, input().split())) h = list(map(int, input().split())) for j in range(k): res = process(h) if res == -1: print(-1) break else: print(res+1)
{ "input": [ "4\n4 3\n4 1 2 3\n2 7\n1 8\n4 5\n4 1 2 3\n3 1\n5 3 1\n" ], "output": [ "\n2\n1\n-1\n-1\n" ] }
296
9
As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≀ u < v ≀ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, 0 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2) - 1)) β€” the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≀ u_i, v_i ≀ n, u β‰  v, 1 ≀ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer β€” the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image>
import sys, os if os.environ['USERNAME']=='kissz': inp=open('in3.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def getp(i): L=[] while parent[i]>=0: L+=[i] i=parent[i] for j in L: parent[j]=i return i n,m=map(int,inp().split()) neighbors=[set() for _ in range(n)] G=[[] for _ in range(n)] E=[] xors=0 for _ in range(m): u,v,w=map(int,inp().split()) neighbors[u-1].add(v-1) neighbors[v-1].add(u-1) E+=[(w,v-1,u-1)] xors^=w s=0 parent=[-1]*n k=(n*(n-1))//2-m nodes=set(range(n)) conn=0 for p in range(n): if p not in nodes: continue nodes.remove(p) Q=[p] while Q: i=Q.pop() new_nodes=set() for j in nodes: if j not in neighbors[i]: parent[j]=p G[i].append((j,True)) G[j].append((i,True)) new_nodes.add(j) conn+=1 debug(i,j,0) k-=1 Q.append(j) nodes-=new_nodes debug(parent) if conn<n-1 or k==0: E.sort() for w,u,v in E: pu=getp(u) pv=getp(v) if pu!=pv: s+=w parent[pu]=pv G[u].append((v,False)) G[v].append((u,False)) conn+=1 debug(u,v,w) elif k==0 and w<xors: Q=[(u,False)] seen=[False]*n seen[u]=True while Q: i,new=Q.pop() for j,new_edge in G[i]: if not seen[j]: seen[j]=True new_edge |= new if j==v: Q=[] break else: Q.append((j,new_edge)) if new_edge: s+=w debug('corr ',u,v,w) k+=1; if conn>=n-1 and (k>0 or w>xors): break if k==0: s+=xors debug('no corr ', xors) print(s)
{ "input": [ "4 4\n2 1 14\n1 4 14\n3 2 15\n4 3 8\n", "5 6\n2 3 11\n5 3 7\n1 4 10\n2 4 14\n4 3 8\n2 5 6\n", "6 6\n3 6 4\n2 4 1\n4 5 7\n3 4 10\n3 5 1\n5 2 15\n" ], "output": [ "\n15\n", "\n6\n", "\n0\n" ] }
297
10
This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≀ r ≀ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≀ i ≀ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2βŒ‰ questions, where ⌈ x βŒ‰ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≀ n ≀ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≀ a, b ≀ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2βŒ‰ queries. Each query is made in the format "? r", where r is an integer 1 ≀ r ≀ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If at any point you make an invalid query or try to make more than ⌈ n/2 βŒ‰ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≀ n ≀ 2 000). The next nβˆ’1 lines contain two integers u and v (1 ≀ u,v ≀ n) denoting an edge between u and v (u β‰  v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
import sys input = sys.stdin.readline flush = sys.stdout.flush def query(x): print('?', x) flush() return list(map(int, input().split())) n = int(input()) ans = set() A = query(1) X, Y = [], [] for i, a in enumerate(A, 1): if not a % 2: X.append(i) else: Y.append(i) if len(X) > len(Y): X, Y = Y, X for x in X: if x != 1: B = query(x) else: B = A for i, b in enumerate(B, 1): if b == 1: ans.add((x, i)) print('!') flush() for a in ans: print(*a) flush()
{ "input": [ "4\n\n0 1 2 2\n\n1 0 1 1", "5\n\n2 2 1 1 0\n" ], "output": [ "\n? 1\n\n? 2\n\n!\n4 2\n1 2\n2 3\n", "\n? 5\n\n!\n4 5\n3 5\n2 4\n1 3\n" ] }
298
8
You are given n points on a plane. All points are different. Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC. The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are considered the same. Input The first line contains a single integer n (3 ≀ n ≀ 3000) β€” the number of points. Next n lines contain the points. The i-th line contains coordinates of the i-th point: two space-separated integers xi, yi ( - 1000 ≀ xi, yi ≀ 1000). It is guaranteed that all given points are different. Output Print the single number β€” the answer to the problem. Examples Input 3 1 1 2 2 3 3 Output 1 Input 3 0 0 -1 0 0 1 Output 0
import sys import fractions def solve(): n , res = int(input()), 0 xs, ys = list(), list() mem = set() for i in range(n): x, y = map(int, input().split()) xs.append(x) ys.append(y) mem.add((x, y)) for i in range(n): for j in range(i + 1, n): sumx, sumy = (xs[i] + xs[j]), (ys[i] + ys[j]) if sumx % 2 == 0 and sumy % 2 == 0: wantx, wanty = sumx//2, sumy //2 if (wantx, wanty) in mem: res+=1 print(res) if sys.hexversion == 50594544 : sys.stdin = open("test.txt") solve()
{ "input": [ "3\n0 0\n-1 0\n0 1\n", "3\n1 1\n2 2\n3 3\n" ], "output": [ "0\n", "1\n" ] }
299
7
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≀ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line. Input The single line of the input contains two integers n and m (1 ≀ n, m ≀ 100), separated by a space. Output Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them. Examples Input 3 3 Output GBGBGB Input 4 2 Output BGBGBB Note In the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
import sys,os,io,time,copy,math from functools import lru_cache if os.path.exists('input.txt'): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def main(): #n=int(input()) #arr=list(map(int,input().split())) n,m=map(int,input().split()) if n<m: for i in range(n): print('GB',end="") for i in range(m-n): print('G',end="") print("") elif n>m: for i in range(m): print('BG',end="") for i in range(n-m): print('B',end="") print("") else: for i in range(n): print('GB',end="") print("") main()
{ "input": [ "4 2\n", "3 3\n" ], "output": [ "BGBGBB\n", "GBGBGB\n" ] }