prob_desc_time_limit
stringclasses
21 values
prob_desc_sample_outputs
stringlengths
5
329
src_uid
stringlengths
32
32
prob_desc_notes
stringlengths
31
2.84k
prob_desc_description
stringlengths
121
3.8k
prob_desc_output_spec
stringlengths
17
1.16k
prob_desc_input_spec
stringlengths
38
2.42k
prob_desc_output_to
stringclasses
3 values
prob_desc_input_from
stringclasses
3 values
lang
stringclasses
5 values
lang_cluster
stringclasses
1 value
difficulty
int64
-1
3.5k
file_name
stringclasses
111 values
code_uid
stringlengths
32
32
prob_desc_memory_limit
stringclasses
11 values
prob_desc_sample_inputs
stringlengths
5
802
exec_outcome
stringclasses
1 value
source_code
stringlengths
29
58.4k
prob_desc_created_at
stringlengths
10
10
tags
listlengths
1
5
hidden_unit_tests
stringclasses
1 value
labels
listlengths
8
8
3 seconds
["14", "6", "0"]
d7d8d91be04f5d9065a0c22e66d11de3
NoteIn the first example: In the second example: Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:
This problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?
Print a single integer — the number of pairs of wires that are intersecting.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.
standard output
standard input
PyPy 3
Python
1,900
train_027.jsonl
19a44d49b3a269a465e6e55b1d0434a4
256 megabytes
["4\n0 0\n1 1\n0 3\n1 2", "4\n0 0\n0 2\n0 4\n2 0", "3\n-1 -1\n1 0\n3 1"]
PASSED
from math import * class slopeC: def __init__(self): self.chil = set() n = int(input()) slopes = {} L = [] for i in range(n): x, y = map(int, input().split()) for l in L: if x != l[0]: slope = (y - l[1]) / (x - l[0]) else: slope = inf s1 = str(l[0]) + '-' + str(l[1]) s2 = str(x) + '-' + str(y) if slope not in slopes: slopes[slope] = [slopeC()] slopes[slope][0].chil.add(s1) slopes[slope][0].chil.add(s2) else: f = 0 for child in slopes[slope]: if s1 in child.chil: f = 1 child.chil.add(s2) break if f == 0: slopes[slope] += [slopeC()] slopes[slope][0].chil.add(s1) slopes[slope][0].chil.add(s2) L += [[x, y]] A = [] P = [0] for s in slopes: A += [(len(slopes[s]))] P += [P[-1] + A[-1]] ans = 0 for i, v in enumerate(A): ans += A[i] * (P[-1] - P[i+1]) print(ans)
1557414300
[ "math", "geometry" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["5"]
0c4bc51e5be9cc642f62d2b3df2bddc4
NoteThe following image represents possible process of removing leaves from the tree:
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?
Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.
In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n,  - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.
standard output
standard input
Python 3
Python
1,600
train_036.jsonl
b2a00fa84d1f4b276c67ca14b2ce5639
256 megabytes
["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"]
PASSED
n=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(n+1)] for i in range(n-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] ans=0 ch=[(1,0,0)] while ch: nom,pre,l=ch.pop() if l>a[nom]: continue ans+=1 for x,c in E[nom]: if x!=pre: ch+=[(x,nom,max(l+c,c))] print(n-ans)
1466181300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["-1 1\n-4 9\n-18 50\n-4 9"]
4dfa99acbe06b314f0f0b934237c66f3
NoteIn the first test case: $$$\frac{-1}{1} + \frac{1}{1} = 0 = \frac{-1 + 1}{1 + 1}$$$.In the second test case: $$$\frac{-4}{2} + \frac{9}{3} = 1 = \frac{-4 + 9}{2 + 3}$$$.In the third test case: $$$\frac{-18}{3} + \frac{50}{5} = 4 = \frac{-18 + 50}{3 + 5}$$$.In the fourth test case: $$$\frac{-4}{6} + \frac{9}{9} = \frac{1}{3} = \frac{-4 + 9}{6 + 9}$$$.
Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form: You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$$$$$ The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \neq (0, 0)$$$. Please help Ivan to solve some equations of this form.
For each test case print two integers $$$x$$$, $$$y$$$ — a possible solution to the equation. It should be satisfied that $$$-10^{18} \leq x, y \leq 10^{18}$$$ and $$$(x, y) \neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq 10^9$$$) — the parameters of the equation.
standard output
standard input
PyPy 3-64
Python
800
train_091.jsonl
8a37a0977957e1619d4bab49069662d6
256 megabytes
["4\n1 1\n2 3\n3 5\n6 9"]
PASSED
import math def lcm(a, b): return (a * b) // math.gcd(a, b) t = int(input()) for _ in range(t): u, v = map(int, input().split(' ')) u *= u v *= v k = lcm(u, v) print(k // v, -(k // u))
1636869900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nNO\nYES"]
f690e6008010dfce1238cc2f0379e52c
NoteFor the first test case, we can travel from node $$$1$$$ to node $$$3$$$, $$$x$$$ changing from $$$0$$$ to $$$1$$$, then we travel from node $$$3$$$ to node $$$2$$$, $$$x$$$ becoming equal to $$$3$$$. Now, we can teleport to node $$$3$$$ and travel from node $$$3$$$ to node $$$4$$$, reaching node $$$b$$$, since $$$x$$$ became equal to $$$0$$$ in the end, so we should answer "YES".For the second test case, we have no moves, since we can't teleport to node $$$b$$$ and the only move we have is to travel to node $$$2$$$ which is impossible since $$$x$$$ wouldn't be equal to $$$0$$$ when reaching it, so we should answer "NO".
You are given a weighted tree with $$$n$$$ vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root.Since trees bore you, you decided to challenge yourself and play a game on the given tree.In a move, you can travel from a node to one of its neighbors (another node it has a direct edge with).You start with a variable $$$x$$$ which is initially equal to $$$0$$$. When you pass through edge $$$i$$$, $$$x$$$ changes its value to $$$x ~\mathsf{XOR}~ w_i$$$ (where $$$w_i$$$ is the weight of the $$$i$$$-th edge). Your task is to go from vertex $$$a$$$ to vertex $$$b$$$, but you are allowed to enter node $$$b$$$ if and only if after traveling to it, the value of $$$x$$$ will become $$$0$$$. In other words, you can travel to node $$$b$$$ only by using an edge $$$i$$$ such that $$$x ~\mathsf{XOR}~ w_i = 0$$$. Once you enter node $$$b$$$ the game ends and you win.Additionally, you can teleport at most once at any point in time to any vertex except vertex $$$b$$$. You can teleport from any vertex, even from $$$a$$$.Answer with "YES" if you can reach vertex $$$b$$$ from $$$a$$$, and "NO" otherwise.Note that $$$\mathsf{XOR}$$$ represents the bitwise XOR operation.
For each test case output "YES" if you can reach vertex $$$b$$$, and "NO" otherwise.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$2 \leq n \leq 10^5$$$), ($$$1 \leq a, b \leq n; a \ne b$$$) — the number of vertices, and the starting and desired ending node respectively. Each of the next $$$n-1$$$ lines denotes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$  — the labels of vertices it connects ($$$1 \leq u_i, v_i \leq n; u_i \ne v_i; 1 \leq w_i \leq 10^9$$$) and the weight of the respective edge. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,700
train_101.jsonl
e8a960ceb05ec5e06169e3d76df70dfa
256 megabytes
["3\n\n5 1 4\n\n1 3 1\n\n2 3 2\n\n4 3 3\n\n3 5 1\n\n2 1 2\n\n1 2 2\n\n6 2 3\n\n1 2 1\n\n2 3 1\n\n3 4 1\n\n4 5 3\n\n5 6 5"]
PASSED
t = int(input()) for _ in range(t): n, st, fi = map(int, input().split()) st -= 1 fi -= 1 g = [[] for i in range(n)] for i in range(n - 1): a, b, w = map(int, input().split()) a -= 1 b -= 1 g[a].append((b, w)) g[b].append((a, w)) hashesSt = [] hashesFi = [] used = [False] * n used[fi] = True stack = [(st, 0)] while stack: ver, hsh = stack.pop() used[ver] = True hashesSt.append(hsh) for to, w in g[ver]: if not used[to]: stack.append((to, hsh ^ w)) used = [False] * n stack = [(fi, 0)] while stack: ver, hsh = stack.pop() used[ver] = True if ver != fi: hashesFi.append(hsh) for to, w in g[ver]: if not used[to]: stack.append((to, hsh ^ w)) print("YES" if not set(hashesSt).isdisjoint(hashesFi) else "NO")
1669041300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nNO\nNO"]
2e8f7f611ba8d417fb7d12fda22c908b
null
You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).
standard output
standard input
Python 3
Python
800
train_003.jsonl
09c9da5d0f2b22710d91c767271ea934
256 megabytes
["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"]
PASSED
t=int(input()) for k in range(t): n=int(input()) a=list(map(int,input().split())) even,odd=0,0 for key in a: if key%2: odd+=1 else: even+=1 if sum(a)%2 or (even and odd): print('YES') else: print('NO')
1580826900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Yes", "Yes", "No"]
068e6bbfe590f4485528e85fa991ff24
NoteThe examples are explained below. Example 1. Example 2. Example 3.
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.You are given two matrices $$$A$$$ and $$$B$$$ of size $$$n \times m$$$, each of which consists of $$$0$$$ and $$$1$$$ only. You can apply the following operation to the matrix $$$A$$$ arbitrary number of times: take any submatrix of the matrix $$$A$$$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $$$0$$$, will be replaced by $$$1$$$, and all corners of the submatrix that contain $$$1$$$, will be replaced by $$$0$$$). You have to answer whether you can obtain the matrix $$$B$$$ from the matrix $$$A$$$. An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question.A submatrix of matrix $$$M$$$ is a matrix which consist of all elements which come from one of the rows with indices $$$x_1, x_1+1, \ldots, x_2$$$ of matrix $$$M$$$ and one of the columns with indices $$$y_1, y_1+1, \ldots, y_2$$$ of matrix $$$M$$$, where $$$x_1, x_2, y_1, y_2$$$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$, where the cell $$$(i,j)$$$ denotes the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column.
Print "Yes" (without quotes) if it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$ using the operations described above, and "No" (without quotes), if it is not possible. You can print each letter in any case (upper or lower).
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$) — the number of rows and the number of columns in matrices $$$A$$$ and $$$B$$$. Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$0 \leq A_{ij} \leq 1$$$). Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$0 \leq B_{ij} \leq 1$$$).
standard output
standard input
Python 3
Python
1,500
train_036.jsonl
02adc0fd24fa584bbf9f3fe5066b4f65
256 megabytes
["3 3\n0 1 0\n0 1 0\n1 0 0\n1 0 0\n1 0 0\n1 0 0", "6 7\n0 0 1 1 0 0 1\n0 1 0 0 1 0 1\n0 0 0 1 0 0 1\n1 0 1 0 1 0 0\n0 1 0 0 1 0 1\n0 1 0 1 0 0 1\n1 1 0 1 0 1 1\n0 1 1 0 1 0 0\n1 1 0 1 0 0 1\n1 0 1 0 0 1 0\n0 1 1 0 1 0 0\n0 1 1 1 1 0 1", "3 4\n0 1 0 1\n1 0 1 0\n0 1 0 1\n1 1 1 1\n1 1 1 1\n1 1 1 1"]
PASSED
n, m = map(int, input().split()) A = [] B = [] for _ in range(n): row = list(map(int, input().split())) A.append(row) for _ in range(n): row = list(map(int, input().split())) B.append(row) flag = 0 for i in range(n): re = 0 for j in range(m): if A[i][j]!=B[i][j]: re += 1 if re%2==1: flag = 1 break if flag==1: print("No") else: for i in range(m): ce = 0 for j in range(n): if A[j][i]!=B[j][i]: ce += 1 if ce%2==1: flag = 1 break if flag==1: print("No") else: print("Yes")
1554550500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\nAG\nAM", "8\nAT\nCH\nCY\nDG\nDO\nER\nIN\nOW", "4\nAD\nAE\nBB\nCC"]
739f51381ed125770e61194b9bc8adb0
NoteIn the first sample, the solution uses two sheets: the first sheet has A on one side and G on the other side; the second sheet has A on one side and M on the other side.The name AA can be spelled using the A side of both sheets. The name GA can be spelled using the G side of the first sheet and the A side of the second sheet. Finally, the name MA can be spelled using the M side of the second sheet and the A side of the first sheet.
Vittorio has three favorite toys: a teddy bear, an owl, and a raccoon. Each of them has a name. Vittorio takes several sheets of paper and writes a letter on each side of every sheet so that it is possible to spell any of the three names by arranging some of the sheets in a row (sheets can be reordered and flipped as needed). The three names do not have to be spelled at the same time, it is sufficient that it is possible to spell each of them using all the available sheets (and the same sheet can be used to spell different names).Find the minimum number of sheets required. In addition, produce a list of sheets with minimum cardinality which can be used to spell the three names (if there are multiple answers, print any).
The first line of the output contains a single integer $$$m$$$ — the minimum number of sheets required. Then $$$m$$$ lines follow: the $$$j$$$-th of these lines contains a string of two uppercase letters of the English alphabet — the letters appearing on the two sides of the $$$j$$$-th sheet. Note that you can print the sheets and the two letters of each sheet in any order.
The first line contains a string $$$t$$$ consisting of uppercase letters of the English alphabet ($$$1\le |t| \le 1000$$$) — the name of the teddy bear. The second line contains a string $$$o$$$ consisting of uppercase letters of the English alphabet ($$$1\le |o| \le 1000$$$) — the name of the owl. The third line contains a string $$$r$$$ consisting of uppercase letters of the English alphabet ($$$1\le |r| \le 1000$$$) — the name of the raccoon. The values $$$|t|$$$, $$$|o|$$$, $$$|r|$$$ denote the length of the three names $$$t$$$, $$$o$$$, $$$r$$$.
standard output
standard input
PyPy 3-64
Python
-1
train_085.jsonl
3cf7a776238434cd1ea41d3cfc1ad9f6
256 megabytes
["AA\nGA\nMA", "TEDDY\nHEDWIG\nRACCOON", "BDC\nCAA\nCE"]
PASSED
class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = self.segfunc(self.tree[k],x) while k > 1: k >>= 1 self.tree[k] = self.segfunc(self.tree[2*k], self.tree[2*k+1]) def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num right = [] while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: right.append(self.tree[r-1]) l >>= 1 r >>= 1 for e in right[::-1]: res = self.segfunc(res,e) return res import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) for _ in range(1): #S = [random.choice("ABC") for i in range(10)] #T = [random.choice("ABC") for i in range(10)] #U = [random.choice("ABC") for i in range(10)] #S = "".join(S) #T = "".join(T) #U = "".join(U) S = input() T = input() U = input() max_match = 0 for q in range(26): ch = chr(q+ord("A")) X = [i for i in range(len(S)) if S[i]==ch] Y = [i for i in range(len(T)) if T[i]==ch] Z = [i for i in range(len(U)) if U[i]==ch] x,y,z = len(X),len(Y),len(Z) """ 0 <= k <= min(x,y) maximize k+min(z,x+y-2*k) """ check = -1 k = -1 for tt in range(min(x,y)+1): tmp = tt + min(x+y-2*tt,z) if tmp > check: k = tt check = tmp max_match += check check = -1 EM = -1 for t in range(max_match+1): tmp = min(t,len(S))+min(t,len(T))+min(t,len(U))-2*t if tmp > check: check = tmp EM = t ST = [] TU = [] US = [] res = [] use_S = [False] * len(S) use_T = [False] * len(T) use_U = [False] * len(U) for q in range(26): ch = chr(q+ord("A")) X = [i for i in range(len(S)) if S[i]==ch] Y = [i for i in range(len(T)) if T[i]==ch] Z = [i for i in range(len(U)) if U[i]==ch] x,y,z = len(X),len(Y),len(Z) """ 0 <= k <= min(x,y) maximize k+min(z,x+y-2*k) """ check = -1 k = -1 for tt in range(min(x,y)+1): tmp = tt + min(x+y-2*tt,z) if tmp > check: k = tt check = tmp def calc(tt): if tt < 0 or tt > min(x,y): return -1 return tt + min(x+y-2*tt,z) assert calc(k-1) <= calc(k) assert calc(k) >= calc(k+1) for _ in range(k): a,b = X.pop(),Y.pop() if EM: EM -= 1 ST.append(ch) use_S[a] = True use_T[b] = True while Z and X and EM: a,c = X.pop(),Z.pop() US.append(ch) use_S[a] = use_U[c] = True EM -= 1 while Z and Y and EM: b,c = Y.pop(),Z.pop() TU.append(ch) use_T[b] = use_U[c] = True EM -= 1 ans = [] X = [S[i] for i in range(len(S)) if not use_S[i]] Y = [T[i] for i in range(len(T)) if not use_T[i]] Z = [U[i] for i in range(len(U)) if not use_U[i]] while X and TU: ans.append(X.pop()+TU.pop()) while Y and US: ans.append(Y.pop()+US.pop()) while Z and ST: ans.append(Z.pop()+ST.pop()) #print(ST,TU,US,X,Y,Z) for ch in ST: X.append(ch) Y.append(ch) for ch in TU: Y.append(ch) Z.append(ch) for ch in US: Z.append(ch) X.append(ch) if len(X) > len(Y): X,Y = Y,X if len(Y) > len(Z): Y,Z = Z,Y ALL = [X,Y,Z] while True: p = [0,1,2] p.sort(key=lambda i:len(ALL[i])) if not ALL[p[1]]: break a = ALL[p[2]].pop() b = ALL[p[1]].pop() ans.append(a+b) for a in ALL[p[2]]: ans.append(a+"A") print(len(ans)) print(*ans,sep="\n") def check(S,res): n = len(res) for i in range(2**n): cnt = [0] * 26 for j in range(n): p = res[j] if i>>j & 1: cnt[ord(p[0])-ord("A")] += 1 else: cnt[ord(p[1])-ord("A")] += 1 for j in range(26): ch = chr(ord("A")+j) if cnt[j] < S.count(ch): break else: return True return False def checker(S,T,U,res): for p in [S,T,U]: if not check(p,res): return False return True #assert checker(S,T,U,ans)
1650798300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["First\n2", "Second"]
f5d9490dc6e689944649820df5f23657
NoteIn the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.
Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. An example of the initial situation at s = "abacaba" A player's move is the sequence of actions: The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available. The player chooses in the string t = t1t2... t|t| character in position i (1 ≤ i ≤ |t|) such that for some positive integer l (0 &lt; i - l; i + l ≤ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|. An example of making action (i = 4) with string s = «abacaba» Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.
If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move — integer i (1 ≤ i ≤ |s|).
The first line contains string s (1 ≤ |s| ≤ 5000). It is guaranteed that string s only contains lowercase English letters.
standard output
standard input
Python 2
Python
2,300
train_017.jsonl
06c42845e9bcb693cb58d286fb6ef6ce
256 megabytes
["abacaba", "abcde"]
PASSED
from sys import stdin def task(): value = stdin.readline() games = [] counter = 0 for i in xrange(1, len(value)-1): if value[i - 1] == value[i + 1]: counter += 1 else: if counter > 0: games.append(counter) counter = 0 if counter > 0: games.append(counter) max_game = max(games) if games else 0 grundi = [0, 1, 1] for n in xrange(3, max_game + 1): s = {grundi[i] ^ grundi[n - i - 3] for i in xrange(0, n // 2 + 1)} s.add(grundi[n - 2]) for i in xrange(n): if i not in s: grundi.append(i) break g = 0 for game in games: g ^= grundi[game] print 'First' if g > 0 else 'Second' def check(n, g): if n < 3: return 0 if g == 0 else -1 else: if grundi[n - 2] ^ g == 0: return 0 for i in xrange(0, n - 2): if g ^ grundi[i] ^ grundi[n - i - 3] == 0: return i + 1 return -1 cache = set() counter = 0 delta = 0 if g > 0: for i in xrange(1, len(value)-1): if value[i - 1] == value[i + 1]: if not delta: delta = i + 1 counter += 1 else: if counter > 0: if counter not in cache: p = check(counter, grundi[counter] ^ g) if p >= 0: print delta + p quit() cache.add(counter) counter = 0 delta = 0 print delta + check(counter, grundi[counter] ^ g) task()
1368968400
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
6 seconds
["98\n128\n219\n229", "3639\n5122\n5162\n5617\n7663\n7806\n7960"]
470ada4754e9601bc7a1548456dab8d7
null
William has two arrays of numbers $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_m$$$. The arrays satisfy the conditions of being convex. Formally an array $$$c$$$ of length $$$k$$$ is considered convex if $$$c_i - c_{i - 1} &lt; c_{i + 1} - c_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k - 1$$$ and $$$c_1 &lt; c_2$$$.Throughout William's life he observed $$$q$$$ changes of two types happening to the arrays: Add the arithmetic progression $$$d, d \cdot 2, d \cdot 3, \dots, d \cdot k$$$ to the suffix of the array $$$a$$$ of length $$$k$$$. The array after the change looks like this: $$$[a_1, a_2, \dots, a_{n - k}, a_{n - k + 1} + d, a_{n - k + 2} + d \cdot 2, \dots, a_n + d \cdot k]$$$. The same operation, but for array $$$b$$$. After each change a matrix $$$d$$$ is created from arrays $$$a$$$ and $$$b$$$, of size $$$n \times m$$$, where $$$d_{i, j}=a_i + b_j$$$. William wants to get from cell ($$$1, 1$$$) to cell ($$$n, m$$$) of this matrix. From cell ($$$x, y$$$) he can only move to cells ($$$x + 1, y$$$) and ($$$x, y + 1$$$). The length of a path is calculated as the sum of numbers in cells visited by William, including the first and the last cells.After each change William wants you to help find out the minimal length of the path he could take.
After each change, output one integer, the minimum length of the path in the constructed matrix.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$2 \le n \le 100, 2 \le m \le 10^5$$$, $$$1 \le q \le 10^5$$$), the sizes of the arrays and the number of changes. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$), the contents of array $$$a$$$. The third line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 10^{12}$$$), the contents of array $$$b$$$. Each of the next $$$q$$$ lines contains three integers $$$type$$$, $$$k$$$ and $$$d$$$ ($$$1 \le type \le 2$$$, if $$$type = 1$$$, then $$$1 \le k \le n$$$ otherwise $$$1 \le k \le m$$$, $$$1 \le d \le 10^3$$$).
standard output
standard input
PyPy 3-64
Python
3,000
train_110.jsonl
b5a01e1e18bd101b7d29c77fd61bdac2
256 megabytes
["5 3 4\n1 2 4 7 11\n5 7 10\n1 3 2\n2 2 5\n1 5 4\n2 1 7", "5 6 7\n4 9 22 118 226\n7 94 238 395 565 738\n2 1 95\n1 4 54\n1 2 5\n1 2 87\n2 6 62\n2 1 143\n1 1 77"]
PASSED
class BIT(object): def __init__(self, n): self.__bit = [0]*(n+1) def add(self, i, val): while i < len(self.__bit): self.__bit[i] += val i += (i & -i) def query(self, i): ret = 0 while i > 0: ret += self.__bit[i] i -= (i & -i) return ret def search(self, val): floor_log2_n = (len(self.__bit)-1).bit_length()-1 pow_i = 2**floor_log2_n total = pos = 0 for _ in reversed(range(floor_log2_n+1)): if pos+pow_i < len(self.__bit) and total+self.__bit[pos+pow_i] < val: total += self.__bit[pos+pow_i] pos += pow_i pow_i >>= 1 return pos def solution(): n, m, q = list(map(int, input().strip().split())) arr = list(map(int, input().strip().split())) brr = list(map(int, input().strip().split())) for i in reversed(range(1, n)): arr[i] -= arr[i-1] for i in reversed(range(1, m)): brr[i] -= brr[i-1] curr = (arr[0]+brr[0])*(n+m-1)+sum(brr[i]*(m-i) for i in range(1, m)) bit1, bit2, bit3 = BIT(m), BIT(m), BIT(m) for i in range(1, m): bit1.add(i, brr[i]) bit1.add(i+1, -brr[i]) bit2.add(i, brr[i]) bit1.add(m, float("inf")) result = [] for _ in range(q): a, b, c = list(map(int, input().strip().split())) if a == 1: for i in range(b): arr[i+(n-b)] += c if b == n: curr += c*(n+m-1) else: if b == m: curr += c*(n+m-1) b -= 1 curr += (b)*(b+1)//2*c bit1.add(m-b, c) bit3.add(m-b, c) bit2.add(m-b, -c*(m-b-1)) ans = curr for i in range(1, n): idx = bit1.search(arr[i]) ans += bit3.query(idx)*idx+bit2.query(idx) ans += arr[i]*(n+m-i-idx-1) result.append(ans) return "\n".join(map(str, result)) print('%s' % solution())
1638110100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0 1 0", "-1", "0 1 3 2 0", "0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0"]
1563061fe7b515531238be320739564a
null
Piegirl found the red button. You have one last chance to change the inevitable end.The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once. Your task is to find any such order and print it. If there is no such order, print -1.
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Input consists of a single integer n (2 ≤ n ≤ 105).
standard output
standard input
Python 3
Python
2,800
train_076.jsonl
1cff4012135320ddba5538a3c9e3ea1f
256 megabytes
["2", "3", "4", "16"]
PASSED
n=int(input()) if n&1: print(-1) else: D,R=[False]*(10**6),[0]*(10**6) i,j=0,0 while True: D[j]=True R[i]=j i+=1 if not D[(j+n)>>1]: j=(j+n)>>1 elif not D[j>>1]: j=j>>1 else: break print(" ".join(str(R[i]) for i in range(n,-1,-1)))
1373734800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2", "545732279"]
91749edcc396819d4172d06e2744b20b
null
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
standard output
standard input
PyPy 2
Python
2,200
train_019.jsonl
ee1195ece0e2f2e10a38e0517a12a6af
256 megabytes
["3 4 2\n2 2\n2 3", "100 100 3\n15 16\n16 15\n99 88"]
PASSED
#from sys import setrecursionlimit as srl import sys if sys.subversion[0] == "PyPy": import io, atexit sys.stdout = io.BytesIO() atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sys.stdin = io.BytesIO(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip() RS = raw_input RI = lambda x=int: map(x,RS().split()) RN = lambda x=int: x(RS()) ''' ...................................................................... ''' mod = 10**9+7 n,m,k = RI() grid = [RI() for i in xrange(k)] grid.sort() grid.append([n,m]) dp = [0]*(k+1) N = 2*max(n,m) fact = [1]*N inv = [1]*N for i in xrange(1,N): fact[i] = (fact[i-1]*i) % mod inv[i] = (inv[i-1]*pow(i,mod-2,mod))%mod def fun(x1,y1,x2,y2): dx = x1-x2 dy = y1-y2 return (fact[dx+dy]*inv[dx]*inv[dy])%mod for i in xrange(k+1): x,y = grid[i] tot = fun(x,y,1,1) for j in xrange(i): if grid[j][0]<=x and grid[j][1]<=y: rem = (dp[j]*fun(x,y,grid[j][0],grid[j][1]))%mod tot = (tot-rem)%mod dp[i] = tot print dp[k]
1437573600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["9\n17\n12\n29\n14\n3\n9"]
4f6a929b40d24c3b64f7ab462a8f39bb
NoteIn first test case the "expansion" of the string is: 'a', 'ac', 'acb', 'acba', 'acbac', 'c', 'cb', 'cba', 'cbac', 'b', 'ba', 'bac', 'a', 'ac', 'c'. The answer can be, for example, 'a', 'ac', 'acb', 'acba', 'acbac', 'b', 'ba', 'bac', 'c'.
Morning desert sun horizonRise above the sands of time...Fates Warning, "Exodus"After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open!Ori was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository.The Gorleks were very fond of the "string expansion" operation. They were also very fond of increasing subsequences.Suppose a string $$$s_1s_2s_3 \ldots s_n$$$ is given. Then its "expansion" is defined as the sequence of strings $$$s_1$$$, $$$s_1 s_2$$$, ..., $$$s_1 s_2 \ldots s_n$$$, $$$s_2$$$, $$$s_2 s_3$$$, ..., $$$s_2 s_3 \ldots s_n$$$, $$$s_3$$$, $$$s_3 s_4$$$, ..., $$$s_{n-1} s_n$$$, $$$s_n$$$. For example, the "expansion" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'. To open the ancient repository, Ori must find the size of the largest increasing subsequence of the "expansion" of the string $$$s$$$. Here, strings are compared lexicographically.Help Ori with this task!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 \ne 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$$$.
For every test case print one non-negative integer — the answer to the problem.
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 5000$$$) — length of the string. The second line of each test case contains a non-empty string of length $$$n$$$, which consists of lowercase latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.
standard output
standard input
PyPy 3
Python
2,500
train_086.jsonl
970b3818ebde76ea2cc49d9e3d2ebefd
512 megabytes
["7\n5\nacbac\n8\nacabacba\n12\naaaaaaaaaaaa\n10\nabacabadac\n8\ndcbaabcd\n3\ncba\n6\nsparky"]
PASSED
import collections import sys input = sys.stdin.readline for _ in range(int(input())): n = int(input()) s = input() maxList = [n - index for index in range(n)] longestCommonPrefix = [0] * (n + 1) for index in range(n - 1, -1, -1): for j in range(index + 1, n): longestCommonPrefix[j] = longestCommonPrefix[j + 1] + 1 if s[index] == s[j] else 0 if s[index + longestCommonPrefix[j]] < s[j + longestCommonPrefix[j]]: delta = maxList[j] - longestCommonPrefix[j] + n - index - maxList[index] if delta > 0: maxList[index] += delta print(max(maxList))
1629988500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1", "0", "13"]
a5d56056fd66713128616bc7c2de8b22
null
Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively "Loves" and "Doesn't love", at that Marina always starts with "Loves". There are n camomiles growing in the field, possessing the numbers of petals equal to a1, a2, ... an. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be "Loves". Help her do that; find the maximal number of petals possible in the bouquet.
Print a single number which is the maximal number of petals in the bouquet, the fortune telling on which would result in "Loves". If there are no such bouquet, print 0 instead. The bouquet may consist of a single flower.
The first line contains an integer n (1 ≤ n ≤ 100), which is the number of flowers growing in the field. The second line contains n integers ai (1 ≤ ai ≤ 100) which represent the number of petals on a given i-th camomile.
standard output
standard input
PyPy 2
Python
1,200
train_046.jsonl
8e19832cb294f891a89fbd7149b649c8
256 megabytes
["1\n1", "1\n2", "3\n5 6 7"]
PASSED
# ///==========Libraries, Constants and Functions=============/// #mkraghav import sys inf = float("inf") mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() def int1():return int(input()) import string import math from itertools import combinations # ///==========MAIN=============/// def main(): n=int(input()) sum=0 mn=105 l=map(int,input().split()) for x in l: sum=sum+x if x%2==1: mn=min(mn,x) if sum%2==0: if mn==105: print(0) else: print(sum-mn) else: print(sum) if __name__ == "__main__": main()
1297440000
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["2\n1 2\n2 2", "-1", "5\n3 1\n1 2\n2 2\n2 3\n3 1", "-1"]
dcb55324681dd1916449570d6bc64e47
NoteAssignment a ^= b denotes assignment a = a ^ b, where operation "^" is bitwise XOR of two integers.
There are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal.Let's have a try. I have created the following task for Topcoder SRM 557 Div1-Hard: you are given n integers x1, x2, ..., xn. You are allowed to perform the assignments (as many as you want) of the following form xi ^= xj (in the original task i and j must be different, but in this task we allow i to equal j). The goal is to maximize the sum of all xi.Now we just change the goal. You are also given n integers y1, y2, ..., yn. You should make x1, x2, ..., xn exactly equal to y1, y2, ..., yn. In other words, for each i number xi should be equal to yi.
If there is no solution, output -1. If there is a solution, then in the first line output an integer m (0 ≤ m ≤ 1000000) – the number of assignments you need to perform. Then print m lines, each line should contain two integers i and j (1 ≤ i, j ≤ n), which denote assignment xi ^= xj. If there are multiple solutions you can print any of them. We can prove that under these constraints if there exists a solution then there always exists a solution with no more than 106 operations.
The first line contains an integer n (1 ≤ n ≤ 10000). The second line contains n integers: x1 to xn (0 ≤ xi ≤ 109). The third line contains n integers: y1 to yn (0 ≤ yi ≤ 109).
standard output
standard input
Python 2
Python
2,700
train_081.jsonl
d37018c83acc201461b7228adcd7ddec
256 megabytes
["2\n3 5\n6 0", "5\n0 0 0 0 0\n1 2 3 4 5", "3\n4 5 6\n1 2 3", "3\n1 2 3\n4 5 6"]
PASSED
n=int(raw_input()) x=map(int,raw_input().split()) y=map(int,raw_input().split()) cnt=0 ans1=[] ans2=[] bit=dict() for i in range(30,-1,-1): for j in range(0,n): if x[j]&1<<i > 0 and x[j] < 1<<i+1: if i not in bit: bit[i] = j else: x[j] ^= x[bit[i]] ans1.append((j,bit[i])) can = 1 for i in range(30,-1,-1): has = 0 for j in range(0,n): if y[j]&1<<i > 0 and y[j] < 1<<i+1: has = 1 if i not in bit: can = 0 else: if j == bit[i]: continue elif y[bit[i]]&1<<i == 0: y[j],y[bit[i]] = y[bit[i]],y[j] ans2.append((j,bit[i])) ans2.append((bit[i],j)) ans2.append((j,bit[i])) else: y[j] ^= y[bit[i]] ans2.append((j,bit[i])) if not can: break if has: for k in range(i,-1,-1): p1 = x[bit[i]]&1<<k p2 = y[bit[i]]&1<<k if p1 == p2: continue else: if k not in bit: can = 0; break else: x[bit[i]] ^= x[bit[k]] ans1.append((bit[i],bit[k])) if not can: print -1 else: for j in range(0,n): if x[j] != y[j]: ans1.append((j,j)) print len(ans1)+len(ans2) for j in range(0, len(ans1)): print ans1[j][0]+1,ans1[j][1]+1 for j in range(len(ans2)-1, -1, -1): print ans2[j][0]+1,ans2[j][1]+1
1411918500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["9", "2", "0", "-1"]
90f08c2c8f7575330639fdd158bc8e6b
NoteIn the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by $$$17$$$.In the second example, Charlie can move a piece from box $$$2$$$ to box $$$3$$$ and a piece from box $$$4$$$ to box $$$5$$$. Each box will be divisible by $$$3$$$.In the third example, each box is already divisible by $$$5$$$.In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy.
This is the harder version of the problem. In this version, $$$1 \le n \le 10^6$$$ and $$$0 \leq a_i \leq 10^6$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problemsChristmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $$$n$$$ boxes of chocolate, numbered from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th box contains $$$a_i$$$ chocolate pieces.Since Bob is a typical nice guy, he will not send Alice $$$n$$$ empty boxes. In other words, at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $$$k &gt; 1$$$ such that the number of pieces in each box is divisible by $$$k$$$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $$$i$$$ and put it into either box $$$i-1$$$ or box $$$i+1$$$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
If there is no way for Charlie to make Alice happy, print $$$-1$$$. Otherwise, print a single integer $$$x$$$ — the minimum number of seconds for Charlie to help Bob make Alice happy.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of chocolate boxes. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the number of chocolate pieces in the $$$i$$$-th box. It is guaranteed that at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive.
standard output
standard input
PyPy 3
Python
2,100
train_011.jsonl
523503f81df7e827fe66eb9c0c8c3908
256 megabytes
["3\n4 8 5", "5\n3 10 2 1 5", "4\n0 5 15 10", "1\n1"]
PASSED
# 素因数分解 def prime_decomposition(n): i = 2 table = [] while i * i <= n: while n % i == 0: n //= i table.append(i) i += 1 if n > 1: table.append(n) return table import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) # かけらを移動させて共通因数を持つようにする su = sum(A) if su == 1: print(-1) exit() primes = sorted(set(prime_decomposition(su))) ans = 10**18 for p in primes: an = 0 half = p >> 1 cnt = 0 for a in A: a %= p cnt += a if cnt <= half: an += cnt else: if cnt < p: an += p - cnt else: cnt -= p if cnt <= half: an += cnt else: an += p - cnt if ans <= an: break else: ans = min(ans, an) print(ans)
1574174100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
0cc73612bcfcd3be142064e2da9e92e3
null
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
standard output
standard input
PyPy 2
Python
1,900
train_005.jsonl
a80874b08b34b1330f099ec32856748b
256 megabytes
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
PASSED
# will you survive without fast IO? # will not stripping save you some time? from collections import deque n, k = map(int, raw_input().split()) g = [[] for i in xrange(n + 1)] par = [0] * (n + 1) deg = [0] * (n + 1) edges = [] idx = 0 for i in xrange(n - 1): u, v = map(int, raw_input().split()) g[u].append(v) g[v].append(u) edges.append((u, v, idx)) idx += 1 deg[u] += 1 deg[v] += 1 deglist = [i for i in xrange(1, n + 1)] deglist.sort(key = lambda x : deg[x], reverse = True) C = deg[deglist[k]] def solve(u): global par, n, C vis = [0] * (n + 1) color = [0] * (n + 1) ans = [0] * (n - 1) vis[u] = 1 col = 0 q = deque([(u, col)]) color[u] = col while q: u, col = q.popleft() for v in g[u]: if vis[v] == 1: continue col += 1 if (col > C): col -= C par[v] = u vis[v] = 1 q.append((v, col)) color[v] = col for u, v, idx in edges: if u != par[v]: u, v = v, u ans[idx] = color[v] return ans ans = solve(1) print C print ' '.join(map(str, ans))
1553006100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["1 1 1\n66 0 61\n5 5 0\n0 1001 1001\n1000000001 0 1000000001"]
f80dea1e07dba355bfbefa4ff65ff45a
null
The elections in which three candidates participated have recently ended. The first candidate received $$$a$$$ votes, the second one received $$$b$$$ votes, the third one received $$$c$$$ votes. For each candidate, solve the following problem: how many votes should be added to this candidate so that he wins the election (i.e. the number of votes for this candidate was strictly greater than the number of votes for any other candidate)?Please note that for each candidate it is necessary to solve this problem independently, i.e. the added votes for any candidate do not affect the calculations when getting the answer for the other two candidates.
For each test case, output in a separate line three integers $$$A$$$, $$$B$$$, and $$$C$$$ ($$$A, B, C \ge 0$$$) separated by spaces — the answers to the problem for the first, second, and third candidate, respectively.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$a$$$, $$$b$$$, and $$$c$$$ ($$$0 \le a,b,c \le 10^9$$$).
standard output
standard input
PyPy 3-64
Python
800
train_093.jsonl
a320cb4bd70d5f2c0faae617e986eae6
256 megabytes
["5\n0 0 0\n10 75 15\n13 13 17\n1000 0 0\n0 1000000000 0"]
PASSED
t = int(input()) for i in range(t): a,b,c = map(int,input().split()) if (a==b==c) == 1: print(1,1,1) elif a>b and a>c: print(0,a-b+1,a-c+1) elif b>c and b>a: print(b-a+1,0,b-c+1) elif c>a and c>b: print(c-a+1,c-b+1,0) elif a==b: if c>a: print(c-a+1,c-b+1,c-c+1) else: print(a-a+1,a-b+1,a-c+1) elif b==c: if a>c: print(b-a+1,a-b+1,a-c+1) else: print(b-a+1,1,1) elif c==a: if c>b: print(c-a+1,c-b+1,1) else: print(b-a+1,0,b-c+1)
1634135700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "6"]
0090979443c294ef6aed7cd09201c9ef
null
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
standard output
standard input
PyPy 2
Python
2,200
train_081.jsonl
d1977b8ab54a2757bb115dd1bf250974
256 megabytes
["a2A", "abacaba"]
PASSED
T = raw_input() P = T + '#' + T[::-1] def compute_prefix_func(P): m = len(P) pi = [0] * m for q in range(1, m): k = pi[q-1] while k > 0 and P[k] != P[q]: k = pi[k-1] if P[k] == P[q]: k += 1 pi[q] = k return pi pi = compute_prefix_func(P) pos = [] l = pi[-1] while l > 0: pos.append(l) l = pi[l-1] K = 0 dp = [0] * (pi[-1] + 1) dp[0] = 0 for i in pos[::-1]: dp[i] = dp[i/2] + 1 K += dp[i] # print i, dp[i] print K
1270136700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["8\n7\n5"]
df2fa3d9e5fdf23656c12416451fcdb9
NoteIn the first test case, one of the optimal solutions is shown below: Each point was moved two times, so the answer $$$2 + 2 + 2 + 2 = 8$$$.In the second test case, one of the optimal solutions is shown below: The answer is $$$3 + 1 + 0 + 3 = 7$$$.In the third test case, one of the optimal solutions is shown below: The answer is $$$1 + 1 + 2 + 1 = 5$$$.
You are given four different integer points $$$p_1$$$, $$$p_2$$$, $$$p_3$$$ and $$$p_4$$$ on $$$\mathit{XY}$$$ grid.In one step you can choose one of the points $$$p_i$$$ and move it in one of four directions by one. In other words, if you have chosen point $$$p_i = (x, y)$$$ you can move it to $$$(x, y + 1)$$$, $$$(x, y - 1)$$$, $$$(x + 1, y)$$$ or $$$(x - 1, y)$$$.Your goal to move points in such a way that they will form a square with sides parallel to $$$\mathit{OX}$$$ and $$$\mathit{OY}$$$ axes (a square with side $$$0$$$ is allowed).What is the minimum number of steps you need to make such a square?
For each test case, print the single integer — the minimum number of steps to make a square.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of four lines. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^9$$$) — coordinates of one of the points $$$p_i = (x, y)$$$. All points are different in one test case.
standard output
standard input
Python 3
Python
null
train_021.jsonl
14dd7aa5015394112e0776c0afefcf6b
256 megabytes
["3\n0 2\n4 2\n2 0\n2 4\n1 0\n2 0\n4 0\n6 0\n1 6\n2 2\n2 5\n4 1"]
PASSED
T = int(input());ans = [0]*T for t in range(T): X,Y = [0]*4,[0]*4;A = [0]*4 for i in range(4):X[i],Y[i] = map(int, input().split());A[i] = [X[i], Y[i]] X.sort(); Y.sort(); A.sort();cnt = 0 for i in range(2): rank = 1 for j in range(4): if A[i][1] < A[j][1]:rank += 1 if rank<=2:cnt += 1 if cnt!=1:ans[t] += min(Y[2]-Y[1], X[2]-X[1])*2 x_min = X[2]-X[1]; x_max = X[3]-X[0];y_min = Y[2]-Y[1]; y_max = Y[3]-Y[0] if x_max<y_min:ans[t] += (X[3]-X[2])+(X[1]-X[0]);ans[t] += (Y[3]-Y[2])+(Y[1]-Y[0])+2*(y_min-x_max) elif y_max<x_min:ans[t] += (X[3]-X[2])+(X[1]-X[0])+2*(x_min-y_max);ans[t] += (Y[3]-Y[2])+(Y[1]-Y[0]) else:ans[t] += (X[3]-X[2])+(X[1]-X[0]);ans[t] += (Y[3]-Y[2])+(Y[1]-Y[0]) print(*ans, sep='\n')
1606746900
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
6 seconds
["5", "25", "793019428", "94810539"]
77443424be253352aaf2b6c89bdd4671
NoteIn the first test, there are three ways to move the token from cell $$$3$$$ to cell $$$1$$$ in one shift: using subtraction of $$$y = 2$$$, or using division by $$$z = 2$$$ or $$$z = 3$$$.There are also two ways to move the token from cell $$$3$$$ to cell $$$1$$$ via cell $$$2$$$: first subtract $$$y = 1$$$, and then either subtract $$$y = 1$$$ again or divide by $$$z = 2$$$.Therefore, there are five ways in total.
Note that the memory limit in this problem is lower than in others.You have a vertical strip with $$$n$$$ cells, numbered consecutively from $$$1$$$ to $$$n$$$ from top to bottom.You also have a token that is initially placed in cell $$$n$$$. You will move the token up until it arrives at cell $$$1$$$.Let the token be in cell $$$x &gt; 1$$$ at some moment. One shift of the token can have either of the following kinds: Subtraction: you choose an integer $$$y$$$ between $$$1$$$ and $$$x-1$$$, inclusive, and move the token from cell $$$x$$$ to cell $$$x - y$$$. Floored division: you choose an integer $$$z$$$ between $$$2$$$ and $$$x$$$, inclusive, and move the token from cell $$$x$$$ to cell $$$\lfloor \frac{x}{z} \rfloor$$$ ($$$x$$$ divided by $$$z$$$ rounded down). Find the number of ways to move the token from cell $$$n$$$ to cell $$$1$$$ using one or more shifts, and print it modulo $$$m$$$. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding).
Print the number of ways to move the token from cell $$$n$$$ to cell $$$1$$$, modulo $$$m$$$.
The only line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 4 \cdot 10^6$$$; $$$10^8 &lt; m &lt; 10^9$$$; $$$m$$$ is a prime number) — the length of the strip and the modulo.
standard output
standard input
PyPy 3
Python
1,900
train_100.jsonl
bbab8ef7c5efe2eb878aa74f4a613178
128 megabytes
["3 998244353", "5 998244353", "42 998244353", "787788 100000007"]
PASSED
import sys from array import array input = sys.stdin.readline def ri(): return [int(i) for i in input().split()] def rs(): return input().split()[0] def main(): t = 1 for _ in range(t): n, m = ri() sum = [0] * (n + 2) # ans[x] + ... + ans[n] sum[n] = 1 sum[n + 1] = 0 last = -1 for x in range(n - 1, 0, -1): extra = sum[x + 1] # jump by subtraction # jump by division for d in range(2, n // x + 1): from_ = x * d to_ = min(x * d + d - 1, n) extra = (extra + sum[from_] - sum[to_ + 1]) % m last = extra sum[x] = (sum[x + 1] + last) % m # print(ans) print(last % m) main()
1629815700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["? C\n\n? CH\n\n? CCHO\n\n! CCHH", "? O\n\n? HHH\n\n! CHHHH\n\n\n? COO\n\n? COOH\n\n? HCCOO\n\n? HH\n\n! HHHCCOOH"]
ecd8c5d7f869cabe35cc9bbdbfb8e00c
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
MisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string $$$p$$$. From the unencrypted papers included, Rin already knows the length $$$n$$$ of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string $$$s$$$ of an arbitrary length into the artifact's terminal, and it will return every starting position of $$$s$$$ as a substring of $$$p$$$.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains $$$\frac{7}{5}$$$ units of energy. For each time Rin inputs a string $$$s$$$ of length $$$t$$$, the artifact consumes $$$\frac{1}{t^2}$$$ units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?
null
null
standard output
standard input
Python 3
Python
3,500
train_014.jsonl
1b991933f1d5f39e3f8b8604bdebd60e
256 megabytes
["1\n4\n\n2 1 2\n\n1 2\n\n0\n\n1", "2\n5\n\n0\n\n2 2 3\n\n1\n8\n\n1 5\n\n1 5\n\n1 3\n\n2 1 2\n\n1"]
PASSED
import sys n, L, minID = None, None, None s = [] def fill(id, c): global n, L, s, minID L -= (s[id] == 'L') s = s[0:id] + c + s[ id +1:] minID = min(minID, id) def query(cmd, str): global n, L, s, minID print(cmd, ''.join(str)) print(cmd, ''.join(str), file=sys.stderr) sys.stdout.flush() if (cmd == '?'): result = list(map(int, input().split())) assert(result[0] != -1) for z in result[1:]: z -= 1 for i in range(len(str)): assert(s[z+i] == 'L' or s[z+i] == str[ i ]) fill(z+i, str[i]) elif (cmd == '!'): correct = int(input()) assert(correct == 1) for _ in range(int(input())): n = int(input()) if n >= 13: ans = [''] * (n + 1) print('? CO') co = list(map(int, input().split()))[1:] print('? CH') ch = list(map(int, input().split()))[1:] print('? CC') cc = list(map(int, input().split()))[1:] for d in co: ans[d] = 'C' ans[d + 1] = 'O' for d in ch: ans[d] = 'C' ans[d + 1] = 'H' for d in cc: ans[d] = 'C' ans[d + 1] = 'C' print('? OO') oo = list(map(int, input().split()))[1:] print('? OH') oh = list(map(int, input().split()))[1:] for d in oo: ans[d] = 'O' ans[d + 1] = 'O' for d in oh: ans[d] = 'O' ans[d + 1] = 'H' for i in range(1, n): if ans[i] == 'O' and ans[i + 1] == '': ans[i + 1] = 'C' for i in range(1, n): if ans[i] == '' and ans[i + 1] == 'O': ans[i] = 'H' for i in range(1, n): if ans[i] == '' and ans[i + 1] == 'H': ans[i] = 'H' for i in range(1, n): if ans[i] == '' and ans[i + 1] == '': ans[i] = 'H' print('? HOC') hoc = list(map(int, input().split()))[1:] for d in hoc: ans[d] = 'H' ans[d + 1] = 'O' ans[d + 2] = 'C' for d in range(2, n): if ans[d] == '': ans[d] = 'H' if ans[1] == '': print('?', 'H' + ''.join(ans[2:-1])) if input()[0] != '0': ans[1] = 'H' else: ans[1] = 'O' if ans[-1] == '': print('?', ''.join(ans[1:-1]) + 'H') if input()[0] != '0': ans[-1] = 'H' else: print('?', ''.join(ans[1:-1]) + 'O') if input()[0] != '0': ans[-1] = 'O' else: ans[-1] = 'C' print('!', ''.join(ans[1:])) kek = input() else: L, minID = n, n s = 'L' * n query('?', "CH") query('?', "CO") query('?', "HC") query('?', "HO") if (L == n): # the string exists in form O...OX...X, with X=C or X=H # or it's completely mono-character query('?', "CCC") if (minID < n): for x in range(minID - 1, -1, -1): fill(x, 'O') else: query('?', "HHH") if (minID < n): for x in range(minID - 1, -1, -1): fill(x, 'O') else: query('?', "OOO") if (minID == n): # obviously n=4 query('?', "OOCC") if (minID == n): fill(0, 'O') fill(1, 'O') fill(2, 'H') fill(3, 'H') if (s[n - 1] == 'L'): t = s[0:n - 1] + 'C' if (t[n - 2] == 'L'): t = t[0:n - 2] + 'C' + t[n - 1:] query('?', t) if (s[n - 1] == 'L'): fill(n - 1, 'H') if (s[n - 2] == 'L'): fill(n - 2, 'H') else: maxID = minID while (maxID < n - 1 and s[maxID + 1] != 'L'): maxID += 1 for i in range(minID - 1, -1, -1): query('?', s[i + 1:i + 2] + s[minID:maxID + 1]) if (minID != i): for x in range(i + 1): fill(x, 'O') break nextFilled = None i = maxID + 1 while i < n: if (s[i] != 'L'): i += 1 continue nextFilled = i while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1 query('?', s[0:i] + s[i - 1]) if (s[i] == 'L'): if (s[i - 1] != 'O'): fill(i, 'O') else: if (nextFilled == n): query('?', s[0:i] + 'C') if (s[i] == 'L'): fill(i, 'H') for x in range(i + 1, nextFilled): fill(x, s[i]) else: for x in range(i, nextFilled): fill(x, s[nextFilled]) i = nextFilled - 1 i += 1 query('!', s)
1579440900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n1\n2\n2"]
ec89860dacb5a11b3a2273d2341b07a1
NoteIn the third case, he can connect two sticks with lengths $$$1$$$ and $$$2$$$ and he will get one stick with length $$$3$$$. So, he will have two sticks with lengths $$$3$$$.In the fourth case, he can connect two sticks with lengths $$$1$$$ and $$$3$$$ and he will get one stick with length $$$4$$$. After that, he will have three sticks with lengths $$$\{2, 4, 4\}$$$, so two sticks have the same length, and one stick has the other length.
A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \le i \le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?
For each test case, print a single integer  — the answer to the problem.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).
standard output
standard input
PyPy 3
Python
800
train_001.jsonl
f4fa89559ce4954c97800c40b63d31d1
256 megabytes
["4\n1\n2\n3\n4"]
PASSED
n=input("") cases=[] for _ in range(int(n)): t=input("") cases.append(int(t)) answers=[] def f(n): if n%2==0: return n//2 else: return (n//2) +1 for case in cases: answers.append(f(case)) for a in answers: print(a)
1593610500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nNO\nYES\nNO\nYES\nNO\nYES\nNO\nNO\nYES"]
d40f0f3b577a1a5cfad2a657d6a1b90a
NoteIn the first test case, the strings are initially $$$s = $$$ "a" and $$$t = $$$ "a". After the first operation the string $$$t$$$ becomes "aaa". Since "a" is already lexicographically smaller than "aaa", the answer for this operation should be "YES".After the second operation string $$$s$$$ becomes "aaa", and since $$$t$$$ is also equal to "aaa", we can't arrange $$$s$$$ in any way such that it is lexicographically smaller than $$$t$$$, so the answer is "NO".After the third operation string $$$t$$$ becomes "aaaaaa" and $$$s$$$ is already lexicographically smaller than it so the answer is "YES".After the fourth operation $$$s$$$ becomes "aaabb" and there is no way to make it lexicographically smaller than "aaaaaa" so the answer is "NO".After the fifth operation the string $$$t$$$ becomes "aaaaaaabcaabcaabca", and we can rearrange the strings to: "bbaaa" and "caaaaaabcaabcaabaa" so that $$$s$$$ is lexicographically smaller than $$$t$$$, so we should answer "YES".
Alperen has two strings, $$$s$$$ and $$$t$$$ which are both initially equal to "a". He will perform $$$q$$$ operations of two types on the given strings: $$$1 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$s$$$. In other words, $$$s := s + \underbrace{x + \dots + x}_{k \text{ times}}$$$. $$$2 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$t$$$. In other words, $$$t := t + \underbrace{x + \dots + x}_{k \text{ times}}$$$. After each operation, determine if it is possible to rearrange the characters of $$$s$$$ and $$$t$$$ such that $$$s$$$ is lexicographically smaller$$$^{\dagger}$$$ than $$$t$$$.Note that the strings change after performing each operation and don't go back to their initial states.$$$^{\dagger}$$$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $$$p$$$ is lexicographically smaller than string $$$q$$$ if there exists a position $$$i$$$ such that $$$p_i &lt; q_i$$$, and for all $$$j &lt; i$$$, $$$p_j = q_j$$$. If no such $$$i$$$ exists, then $$$p$$$ is lexicographically smaller than $$$q$$$ if the length of $$$p$$$ is less than the length of $$$q$$$. For example, $$$\texttt{abdc} &lt; \texttt{abe}$$$ and $$$\texttt{abc} &lt; \texttt{abcd}$$$, where we write $$$p &lt; q$$$ if $$$p$$$ is lexicographically smaller than $$$q$$$.
For each operation, output "YES", if it is possible to arrange the elements in both strings in such a way that $$$s$$$ is lexicographically smaller than $$$t$$$ and "NO" otherwise.
The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$q$$$ $$$(1 \leq q \leq 10^5)$$$ — the number of operations Alperen will perform. Then $$$q$$$ lines follow, each containing two positive integers $$$d$$$ and $$$k$$$ ($$$1 \leq d \leq 2$$$; $$$1 \leq k \leq 10^5$$$) and a non-empty string $$$x$$$ consisting of lowercase English letters — the type of the operation, the number of times we will append string $$$x$$$ and the string we need to append respectively. It is guaranteed that the sum of $$$q$$$ over all test cases doesn't exceed $$$10^5$$$ and that the sum of lengths of all strings $$$x$$$ in the input doesn't exceed $$$5 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
1,500
train_099.jsonl
35f86d32c4db95018faf9b9924f0fb96
256 megabytes
["3\n\n5\n\n2 1 aa\n\n1 2 a\n\n2 3 a\n\n1 2 b\n\n2 3 abca\n\n2\n\n1 5 mihai\n\n2 2 buiucani\n\n3\n\n1 5 b\n\n2 3 a\n\n2 4 paiu"]
PASSED
t = int(input()) for _ in range(t): q = int(input()) s_a_count = 1 t_a_count = 1 other_than_a_t = False other_than_a_s = False for _ in range(q): line = list(map(str, input().rstrip().split())) if line[0] == '2': for char in line[2]: if char != 'a': other_than_a_t = True break else: t_a_count += int(line[1]) else: for char in line[2]: if char != 'a': other_than_a_s = True else: s_a_count += int(line[1]) print('YES' if other_than_a_t or (not other_than_a_s and s_a_count < t_a_count) else 'NO')
1665671700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["11\n20\n3"]
ee32db8e7cdd9561d9215651ff8a262e
NoteIn the first test case: you should take $$$3$$$ swords and $$$3$$$ war axes: $$$3 \cdot 5 + 3 \cdot 6 = 33 \le 33$$$ and your follower — $$$3$$$ swords and $$$2$$$ war axes: $$$3 \cdot 5 + 2 \cdot 6 = 27 \le 27$$$. $$$3 + 3 + 3 + 2 = 11$$$ weapons in total.In the second test case, you can take all available weapons even without your follower's help, since $$$5 \cdot 10 + 5 \cdot 10 \le 100$$$.In the third test case, you can't take anything, but your follower can take $$$3$$$ war axes: $$$3 \cdot 5 \le 19$$$.
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.You decided to rob a town's blacksmith and you take a follower with you. You can carry at most $$$p$$$ units and your follower — at most $$$f$$$ units.In the blacksmith shop, you found $$$cnt_s$$$ swords and $$$cnt_w$$$ war axes. Each sword weights $$$s$$$ units and each war axe — $$$w$$$ units. You don't care what to take, since each of them will melt into one steel ingot.What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?
For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$p$$$ and $$$f$$$ ($$$1 \le p, f \le 10^9$$$) — yours and your follower's capacities. The second line of each test case contains two integers $$$cnt_s$$$ and $$$cnt_w$$$ ($$$1 \le cnt_s, cnt_w \le 2 \cdot 10^5$$$) — the number of swords and war axes in the shop. The third line of each test case contains two integers $$$s$$$ and $$$w$$$ ($$$1 \le s, w \le 10^9$$$) — the weights of each sword and each war axe. It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,700
train_011.jsonl
cf15903dc834983b43574a24cc3a3abf
256 megabytes
["3\n33 27\n6 10\n5 6\n100 200\n10 10\n5 5\n1 19\n1 3\n19 5"]
PASSED
def controller(p, f, cnt_s, cnt_w, s, w): def proc(cap_p, cap_f, cnt, weight): sp, sf = cap_p//weight, cap_f//weight if cnt >= sp + sf: return (0, sp, sf) # if total == 0, then total == sp + sf sp, sf = min(cnt,sp), min(cnt,sf) return (cnt, sp, sf) if s > w: s, w, cnt_s, cnt_w = w, s, cnt_w, cnt_s elif s == w: cnt_s, cnt_w = cnt_s + cnt_w, 0 total, sp, sf = proc(p, f, cnt_s, s) if total == 0: return sp + sf elif cnt_w == 0: return cnt_s pot_p = p - s*sp pot_f = f - s*(cnt_s-sp) total, sp2, sf2 = proc(pot_p, pot_f, cnt_w, w) total = total or sp2 + sf2 total += cnt_s rem = pot_p % w + pot_f % w if rem >= w and cnt_w > sp2 + sf2: for i in range(sp-(cnt_s-sf)): # why not sp+1-(cnt_s-sf)? since first choice outside loop pot_p += s pot_f -= s if pot_p % w + pot_f % w < w: return total + 1 return total def c_in(): import sys, os.path try: file = open(os.path.join(sys.argv[0], r'../in-b.txt')) except: file = sys.stdin n_test_case = int(file.readline()) # print(n_test_case) for i in range(n_test_case): p, f = [int(i) for i in file.readline().split()] cnt_s, cnt_w = [int(i) for i in file.readline().split()] s, w = [int(i) for i in file.readline().split()] inputs = p, f, cnt_s, cnt_w, s, w # print(inputs) print(controller(*inputs)) if __name__ == '__main__': c_in()
1598366100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n0\n1\n0\n2\n1 1\n4\n1 1 0 0"]
eca92beb189c4788e8c4744af1428bc7
NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.
Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ — length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!
For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) — number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even)  — length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$)  — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
standard output
standard input
Python 2
Python
1,100
train_008.jsonl
36e966f0809dc2974f0ff34a42979980
256 megabytes
["4\n2\n1 0\n2\n0 0\n4\n0 1 1 1\n4\n1 1 0 0"]
PASSED
def solve(): n = int(raw_input()) a = map(int, raw_input().split()) c = sum(a) m = n / 2 if n - c >= m: b = [0] * m else: b = [1] * ((m + 1) / 2) * 2 print len(b) for x in b: print x, print T = int(raw_input()) for t in xrange(T): solve()
1599575700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"]
a017393743ae70a4d8a9d9dc40410653
null
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!
Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.
The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.
standard output
standard input
PyPy 3
Python
1,200
train_005.jsonl
7790035c00258e3549f7ea34503da575
64 megabytes
["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"]
PASSED
from sys import stdin lines = list(map(lambda _: _.strip(), stdin.readlines())) max_len = max(list(map(len, lines))) print((max_len + 2) * '*') left = 0 for line in lines: pad = max_len - len(line) if pad % 2 != 0: left_pad = pad // 2 + left left = 1 - left else: left_pad = pad // 2 right_pad = pad - left_pad print('*', left_pad * ' ', line, right_pad * ' ', '*', sep='') print((max_len + 2) * '*')
1269100800
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["3", "2", "-1"]
07600ef3a0e1d216699648b2d17189e8
NoteIn the first sample the tree is split into $$$\{1\},\ \{2\},\ \{3\}$$$.In the second sample the tree is split into $$$\{1,\ 2\},\ \{3\}$$$ or $$$\{1,\ 3\},\ \{2\}$$$.In the third sample it is impossible to split the tree.
You are given a rooted tree on $$$n$$$ vertices, its root is the vertex number $$$1$$$. The $$$i$$$-th vertex contains a number $$$w_i$$$. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than $$$L$$$ vertices and the sum of integers $$$w_i$$$ on each path does not exceed $$$S$$$. Each vertex should belong to exactly one path.A vertical path is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ where $$$v_i$$$ ($$$i \ge 2$$$) is the parent of $$$v_{i - 1}$$$.
Output one number  — the minimum number of vertical paths. If it is impossible to split the tree, output $$$-1$$$.
The first line contains three integers $$$n$$$, $$$L$$$, $$$S$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le L \le 10^5$$$, $$$1 \le S \le 10^{18}$$$) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1 \le w_i \le 10^9$$$) — the numbers in the vertices of the tree. The third line contains $$$n - 1$$$ integers $$$p_2, \ldots, p_n$$$ ($$$1 \le p_i &lt; i$$$), where $$$p_i$$$ is the parent of the $$$i$$$-th vertex in the tree.
standard output
standard input
Python 3
Python
2,400
train_059.jsonl
5112c44c5a4f5f64d2f1154cebd5954f
256 megabytes
["3 1 3\n1 2 3\n1 1", "3 3 6\n1 2 3\n1 1", "1 1 10000\n10001"]
PASSED
def solve(n, l, s, www, children): ans = 0 dp = [{} for _ in range(n)] for v in range(n - 1, -1, -1): cv = children[v] if not cv: dp[v][1] = www[v] continue ans += len(cv) - 1 wv = www[v] if wv > s: return -1 dv = dp[v] for c in cv: for lc, wc in dp[c].items(): if lc == l: continue wt = wc + wv if wt > s: continue if lc + 1 not in dv: dv[lc + 1] = wt else: dv[lc + 1] = min(dv[lc + 1], wt) if not dv: ans += 1 dv[1] = wv return ans + 1 n, l, s = list(map(int, input().split())) www = list(map(int, input().split())) if n == 1: print(-1 if www[0] > s else 1) exit() children = [set() for _ in range(n)] for i, p in enumerate(map(int, input().split())): children[p - 1].add(i + 1) print(solve(n, l, s, www, children))
1538750100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
4.5 seconds
["2 4\n4 10\n1 3"]
55c692d380a4d1c0478ceb7cffde342f
NoteExplanation of the sample:At the first query, the tree consist of root, so we purchase $$$2$$$ tons of gold and pay $$$2 \cdot 2 = 4$$$. $$$3$$$ tons remain in the root.At the second query, we add vertex $$$2$$$ as a son of vertex $$$0$$$. Vertex $$$2$$$ now has $$$3$$$ tons of gold with price $$$4$$$ per one ton.At the third query, a path from $$$2$$$ to $$$0$$$ consists of only vertices $$$0$$$ and $$$2$$$ and since $$$c_0 &lt; c_2$$$ we buy $$$3$$$ remaining tons of gold in vertex $$$0$$$ and $$$1$$$ ton in vertex $$$2$$$. So we bought $$$3 + 1 = 4$$$ tons and paid $$$3 \cdot 2 + 1 \cdot 4 = 10$$$. Now, in vertex $$$0$$$ no gold left and $$$2$$$ tons of gold remain in vertex $$$2$$$.At the fourth query, we add vertex $$$4$$$ as a son of vertex $$$0$$$. Vertex $$$4$$$ now has $$$1$$$ ton of gold with price $$$3$$$.At the fifth query, a path from $$$4$$$ to $$$0$$$ consists of only vertices $$$0$$$ and $$$4$$$. But since no gold left in vertex $$$0$$$ and only $$$1$$$ ton is in vertex $$$4$$$, we buy $$$1$$$ ton of gold in vertex $$$4$$$ and spend $$$1 \cdot 3 = 3$$$. Now, in vertex $$$4$$$ no gold left.
You are given a rooted tree. Each vertex contains $$$a_i$$$ tons of gold, which costs $$$c_i$$$ per one ton. Initially, the tree consists only a root numbered $$$0$$$ with $$$a_0$$$ tons of gold and price $$$c_0$$$ per ton.There are $$$q$$$ queries. Each query has one of two types: Add vertex $$$i$$$ (where $$$i$$$ is an index of query) as a son to some vertex $$$p_i$$$; vertex $$$i$$$ will have $$$a_i$$$ tons of gold with $$$c_i$$$ per ton. It's guaranteed that $$$c_i &gt; c_{p_i}$$$. For a given vertex $$$v_i$$$ consider the simple path from $$$v_i$$$ to the root. We need to purchase $$$w_i$$$ tons of gold from vertices on this path, spending the minimum amount of money. If there isn't enough gold on the path, we buy all we can. If we buy $$$x$$$ tons of gold in some vertex $$$v$$$ the remaining amount of gold in it decreases by $$$x$$$ (of course, we can't buy more gold that vertex has at the moment). For each query of the second type, calculate the resulting amount of gold we bought and the amount of money we should spend.Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program. In standard (if you don't tweak I/O), endl flushes cout in C++ and System.out.println in Java (or println in Kotlin) makes automatic flush as well.
For each query of the second type, print the resulting amount of gold we bought and the minimum amount of money we should spend.
The first line contains three integers $$$q$$$, $$$a_0$$$ and $$$c_0$$$ ($$$1 \le q \le 3 \cdot 10^5$$$; $$$1 \le a_0, c_0 &lt; 10^6$$$) — the number of queries, the amount of gold in the root and its price. Next $$$q$$$ lines contain descriptions of queries; The $$$i$$$-th query has one of two types: "$$$1$$$ $$$p_i$$$ $$$a_i$$$ $$$c_i$$$" ($$$0 \le p_i &lt; i$$$; $$$1 \le a_i, c_i &lt; 10^6$$$): add vertex $$$i$$$ as a son to vertex $$$p_i$$$. The vertex $$$i$$$ will have $$$a_i$$$ tons of gold with price $$$c_i$$$ per one ton. It's guaranteed that $$$p_i$$$ exists and $$$c_i &gt; c_{p_i}$$$. "$$$2$$$ $$$v_i$$$ $$$w_i$$$" ($$$0 \le v_i &lt; i$$$; $$$1 \le w_i &lt; 10^6$$$): buy $$$w_i$$$ tons of gold from vertices on path from $$$v_i$$$ to $$$0$$$ spending the minimum amount of money. If there isn't enough gold, we buy as much as we can. It's guaranteed that vertex $$$v_i$$$ exist. It's guaranteed that there is at least one query of the second type.
standard output
standard input
PyPy 3
Python
2,200
train_085.jsonl
41909de309b27273ee1583a0da8c5cc0
256 megabytes
["5 5 2\n2 0 2\n1 0 3 4\n2 2 4\n1 0 1 3\n2 4 2"]
PASSED
from array import array import math import os import sys input = sys.stdin.buffer.readline q, a0, c0 = map(int, input().split()) mod = pow(10, 9) + 7 n = q + 5 pow2 = [1] for _ in range(20): pow2.append(2 * pow2[-1]) cnt = [0] * n cost = [0] * n cnt[0], cost[0] = a0, c0 dp = array("l", [-1] * (20 * n)) dist = [-1] * n dist[0] = 1 l0 = [-1] * n for i in range(1, q + 1): t = list(map(int, input().split())) if t[0] == 1: p, a, c = t[1], t[2], t[3] cnt[i] = a cost[i] = c j = 0 dp[20 * i] = p while dp[20 * dp[20 * i + j] + j] ^ -1: dp[20 * i + j + 1] = dp[20 * dp[20 * i + j] + j] j += 1 dist[i] = dist[p] + 1 else: v, w = t[1], t[2] if not v: u = 0 x = min(w, cnt[u]) cnt[u] -= x ans = [str(x), str(x * cost[0])] os.write(1, b"%d %d\n" % (x, x * cost[0])) continue d, j, l = 0, v, int(math.log2(dist[v])) + 1 for k in range(l - 1, -1, -1): m = dp[20 * j + k] if cnt[m]: d += pow2[k] j = m u0 = j ans0, ans1, ans2 = 0, 0, 0 for j in range(d, -1, -1): if j ^ d: d0, u, k = j, v, 0 while d0: if d0 & pow2[k]: d0 ^= pow2[k] u = dp[20 * u + k] k += 1 else: u = u0 x = min(w - ans0, cnt[u]) cnt[u] -= x ans0 += x ans1 += x * cost[u] % mod ans2 += x * cost[u] // mod ans2 += ans1 // mod ans1 %= mod if not ans0 ^ w: break ans = [str(ans0), str(ans1 + ans2 * mod)] os.write(1, b"%d %d\n" % (ans0, ans1 + ans2 * mod))
1622817300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["1 6\n2 6\n3 5\n3 6\n4 5", "1 6\n1 7\n2 6\n3 5\n3 6\n4 5\n7 8", "1 3\n2 3\n3 5\n4 5\n5 7\n6 7\n7 12\n8 12\n9 11\n9 12\n10 11", "1 2\n1 4\n3 4"]
61bb5f2b315eddf2e658e3f54d8f43b8
Note Answer for the first sample test. Answer for the second sample test.
It's Petya's birthday party and his friends have presented him a brand new "Electrician-$$$n$$$" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set "Electrician-$$$n$$$" consists of $$$2n - 1$$$ wires and $$$2n$$$ light bulbs. Each bulb has its own unique index that is an integer from $$$1$$$ to $$$2n$$$, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed $$$2i$$$ and $$$2i - 1$$$ turn on if the chain connecting them consists of exactly $$$d_i$$$ wires. Moreover, the following important condition holds: the value of $$$d_i$$$ is never greater than $$$n$$$.Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
Print $$$2n - 1$$$ lines. The $$$i$$$-th of them should contain two distinct integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 2n$$$, $$$a_i \ne b_i$$$) — indices of bulbs connected by a wire. If there are several possible valid answer you can print any of them.
The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the parameter of a construction set that defines the number of bulbs and the number of wires. Next line contains $$$n$$$ integers $$$d_1, d_2, \ldots, d_n$$$ ($$$1 \leq d_i \leq n$$$), where $$$d_i$$$ stands for the number of wires the chain between bulbs $$$2i$$$ and $$$2i - 1$$$ should consist of.
standard output
standard input
Python 3
Python
2,000
train_022.jsonl
2e635e3e95195018a786084468e20aa5
512 megabytes
["3\n2 2 2", "4\n2 2 2 1", "6\n2 2 2 2 2 2", "2\n1 1"]
PASSED
# https://codeforces.com/contest/1214/problem/E n = int(input()) d = map(int, input().split()) d = [[2*i+1, di] for i, di in enumerate(d)] d = sorted(d, key=lambda x:x[1], reverse = True) edge = [] arr = [x[0] for x in d] for i, [x, d_] in enumerate(d): if i + d_ - 1 == len(arr) - 1: arr.append(x+1) edge.append([arr[i + d_ - 1], x+1]) for u, v in zip(d[:-1], d[1:]): edge.append([u[0], v[0]]) ans = '\n'.join([str(u)+' '+str(v) for u, v in edge]) print(ans)
1567587900
[ "math", "trees", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 1 ]
2 seconds
["750000007", "125000003"]
a44cba5685500b16e24b8fba30451bc5
NoteThe answer for the first sample is equal to $$$\frac{14}{8}$$$.The answer for the second sample is equal to $$$\frac{17}{8}$$$.
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $$$T$$$ seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $$$n$$$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $$$t_i$$$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $$$t_i$$$ seconds or $$$t_i + 1$$$ seconds to solve the $$$i$$$-th crossword, equiprobably (with probability $$$\frac{1}{2}$$$ he solves the crossword in exactly $$$t_i$$$ seconds, and with probability $$$\frac{1}{2}$$$ he has to spend an additional second to finish the crossword). All these events are independent.After $$$T$$$ seconds pass (or after solving the last crossword, if he manages to do it in less than $$$T$$$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $$$E$$$ — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $$$E = \sum \limits_{i = 0}^{n} i p_i$$$, where $$$p_i$$$ is the probability that Adilbek will solve exactly $$$i$$$ crosswords. We can represent $$$E$$$ as rational fraction $$$\frac{P}{Q}$$$ with $$$Q &gt; 0$$$. To give the answer, you should print $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
Print one integer — the expected value of the number of crosswords Adilbek solves in $$$T$$$ seconds, expressed in the form of $$$P \cdot Q^{-1} \bmod (10^9 + 7)$$$.
The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 2 \cdot 10^{14}$$$) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 10^9$$$), where $$$t_i$$$ is the time it takes a crossword expert to solve the $$$i$$$-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
standard output
standard input
PyPy 2
Python
2,400
train_001.jsonl
81bda70b1f577dfe53f0cb3c1bd9d668
256 megabytes
["3 5\n2 2 2", "3 5\n2 1 2"]
PASSED
MOD = 10 ** 9 + 7 MAX = 5 * 10 ** 5 fac, ifac, ipow2 = [1] * MAX, [1] * MAX, [1] * MAX for i in range(1, MAX): fac[i] = fac[i - 1] * i % MOD ifac[i] = pow(fac[i], MOD - 2, MOD) ipow2[i] = ipow2[i - 1] * (MOD + 1) // 2 % MOD choose = lambda n, k: fac[n] * ifac[k] % MOD * ifac[n - k] % MOD n, t = map(int, raw_input().split()) a = list(map(int, raw_input().split())) s = 0 p = [1] + [0] * (n + 1) k = cur = 0 for i in range(n): s += a[i] if s > t: break if s + i + 1 <= t: p[i + 1] = 1 continue newk = t - s cur = cur * 2 - choose(i, k) if cur else sum(choose(i + 1, j) for j in range(newk + 1)) if newk < k: cur -= sum(choose(i + 1, x) for x in range(k, newk, -1)) cur %= MOD p[i + 1] = cur * ipow2[i + 1] % MOD k = newk print(sum((p[i] - p[i + 1]) * i % MOD for i in range(1, n + 1)) % MOD)
1563115500
[ "probabilities", "number theory" ]
[ 0, 0, 0, 0, 1, 1, 0, 0 ]
2 seconds
["4\n0\n6\n3\n6"]
ebf0bf949a29eeaba3bcc35091487199
NoteQuestions about the optimal strategy will be ignored.
Alice and Bob play a game. They have a binary string $$$s$$$ (a string such that each character in it is either $$$0$$$ or $$$1$$$). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in $$$s$$$ and delete them.For example, if the string is $$$10110$$$, there are $$$6$$$ possible moves (deleted characters are bold): $$$\textbf{1}0110 \to 0110$$$; $$$1\textbf{0}110 \to 1110$$$; $$$10\textbf{1}10 \to 1010$$$; $$$101\textbf{1}0 \to 1010$$$; $$$10\textbf{11}0 \to 100$$$; $$$1011\textbf{0} \to 1011$$$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $$$10\textbf{11}0 \to 1\textbf{00} \to 1$$$.The game ends when the string becomes empty, and the score of each player is the number of $$$1$$$-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.
For each test case, print one integer — the resulting score of Alice (the number of $$$1$$$-characters deleted by her).
The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case contains exactly one line containing a binary string $$$s$$$ ($$$1 \le |s| \le 100$$$).
standard output
standard input
Python 3
Python
800
train_002.jsonl
e9974cd0511c658c8bd6ff0266080b81
256 megabytes
["5\n01111001\n0000\n111111\n101010101\n011011110111"]
PASSED
t = int(input()) for _ in range(t): s = sorted(input().split('0'), reverse=True)[::2] res = sum(list(map(len, s))) print(res)
1597415700
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["2 1 3", "-1", "2 5 1 3 4"]
f9c6ef39752d1da779e07c27dff918a9
NoteIn the first example, Johnny starts with writing blog number $$$2$$$, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number $$$1$$$, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number $$$3$$$, it has references to blogs number $$$1$$$ and $$$2$$$ so it receives the third topic.Second example: There does not exist any permutation fulfilling given conditions.Third example: First Johnny writes blog $$$2$$$, it receives the topic $$$1$$$. Then he writes blog $$$5$$$, it receives the topic $$$1$$$ too because it doesn't have reference to single already written blog $$$2$$$. Then he writes blog number $$$1$$$, it has reference to blog number $$$2$$$ with topic $$$1$$$, so it receives the topic $$$2$$$. Then he writes blog number $$$3$$$ which has reference to blog $$$2$$$, so it receives the topic $$$2$$$. Then he ends with writing blog number $$$4$$$ which has reference to blog $$$5$$$ and receives the topic $$$2$$$.
Today Johnny wants to increase his contribution. His plan assumes writing $$$n$$$ blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.There are $$$n$$$ different topics, numbered from $$$1$$$ to $$$n$$$ sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most $$$n - 1$$$ neighbors.For example, if already written neighbors of the current blog have topics number $$$1$$$, $$$3$$$, $$$1$$$, $$$5$$$, and $$$2$$$, Johnny will choose the topic number $$$4$$$ for the current blog, because topics number $$$1$$$, $$$2$$$ and $$$3$$$ are already covered by neighbors and topic number $$$4$$$ isn't covered.As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
If the solution does not exist, then write $$$-1$$$. Otherwise, output $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ $$$(1 \leq p_i \leq n)$$$, which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
The first line contains two integers $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ and $$$m$$$ $$$(0 \leq m \leq 5 \cdot 10^5)$$$ — the number of blogs and references, respectively. Each of the following $$$m$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$a \neq b$$$; $$$1 \leq a, b \leq n$$$), which mean that there is a reference between blogs $$$a$$$ and $$$b$$$. It's guaranteed that the graph doesn't contain multiple edges. The last line contains $$$n$$$ integers $$$t_1, t_2, \ldots, t_n$$$, $$$i$$$-th of them denotes desired topic number of the $$$i$$$-th blog ($$$1 \le t_i \le n$$$).
standard output
standard input
PyPy 3
Python
1,700
train_009.jsonl
290a82cd8acafaf3e81dab446a4fb100
256 megabytes
["3 3\n1 2\n2 3\n3 1\n2 1 3", "3 3\n1 2\n2 3\n3 1\n1 1 1", "5 3\n1 2\n2 3\n4 5\n2 1 2 2 1"]
PASSED
'''import os,io input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline I= lambda: list(map(int,input().split()))''' import os,io from sys import stdout input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline I=lambda:list(map(int,input().split())) n,edge=I() go=[[] for _ in range(n+1)] for _ in range(edge): a,b=I() go[a].append(b) go[b].append(a) s=I() arr=[] for i,x in enumerate(list(s)): i+=1 arr.append((x,i)) arr.sort() #count=[set() for _ in range(n+1)] count=[0]*(n+1) gone=[False]*(n+1) ans=[] for topic,blog in arr: gone[blog]=True if count[blog]+1!=topic: print(-1) exit() ans.append(blog) for x in go[blog]: if gone[x]==False and count[x] not in (topic-1,topic): print(-1) exit() count[x]=topic print(' '.join([str(x) for x in ans]))
1591281300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["13 2", "-1", "3 4"]
8e8437c62ea72f01f7e921e99dca931f
null
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)·d, each taken modulo m.
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m. Otherwise, print two integers — the first element of the obtained progression x (0 ≤ x &lt; m) and its difference d (0 ≤ d &lt; m). If there are multiple answers, print any of them.
The first line contains two integers m and n (2 ≤ m ≤ 109 + 7, 1 ≤ n ≤ 105, m is prime) — Timofey's favorite prime module and the length of the sequence. The second line contains n distinct integers a1, a2, ..., an (0 ≤ ai &lt; m) — the elements of the sequence.
standard output
standard input
Python 3
Python
2,600
train_058.jsonl
7bab6dfbf20b5857223dbbe23ec88431
256 megabytes
["17 5\n0 2 4 13 15", "17 5\n0 2 4 13 14", "5 3\n1 2 3"]
PASSED
def solve(n, m, a): if n == 0: return 0, 1 if n == 1: return a[0], 1 d = (a[1]-a[0]) % m if d < 0: d += m st = set(a) cnt = 0 for v in a: cnt += ((v + d) % m) in st cnt = n-cnt d = (d * pow(cnt, m-2, m)) % m now = a[0] while (now + m - d) % m in st: now = (now + m - d) % m for i in range(n): if (now + i*d) % m not in st: return -1, -1 return now, d m, n = map(int, input().split()) a = list(map(int, input().split())) if n * 2 > m: st = set(a) b = [i for i in range(m) if i not in st] f, d = solve(len(b), m, b) f = (f + d * (m-n)) % m else: f, d = solve(n, m, a) if f < 0 or d < 0: print(-1) else: print(f, d) # Made By Mostafa_Khaled
1486042500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["YES\n10 50 60\nYES\n169 39 208\nYES\n28 154 182"]
f10aa45956e930df3df0e23f2592c8f1
NoteIn the first test case: $$$60$$$ — good number; $$$10$$$ and $$$50$$$ — nearly good numbers.In the second test case: $$$208$$$ — good number; $$$169$$$ and $$$39$$$ — nearly good numbers.In the third test case: $$$154$$$ — good number; $$$28$$$ and $$$182$$$ — nearly good numbers.
Nastia has $$$2$$$ positive integers $$$A$$$ and $$$B$$$. She defines that: The integer is good if it is divisible by $$$A \cdot B$$$; Otherwise, the integer is nearly good, if it is divisible by $$$A$$$. For example, if $$$A = 6$$$ and $$$B = 4$$$, the integers $$$24$$$ and $$$72$$$ are good, the integers $$$6$$$, $$$660$$$ and $$$12$$$ are nearly good, the integers $$$16$$$, $$$7$$$ are neither good nor nearly good.Find $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.
For each test case print: "YES" and $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$. "NO" if no answer exists. YES NO If there are multiple answers, print any.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains two integers $$$A$$$ and $$$B$$$ ($$$1 \le A \le 10^6$$$, $$$1 \le B \le 10^6$$$) — numbers that Nastia has.
standard output
standard input
Python 3
Python
1,000
train_099.jsonl
f0205bc518a93d63a5cbb478101adf5d
256 megabytes
["3\n5 3\n13 2\n7 11"]
PASSED
for _ in range(int(input())): a,b=map(int,input().split()) x=a*b*2 y=x-a z=a if y+z==x and y!=z: print('YES') print(y,z,x) else: print('NO')
1620398100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["Mike\nAnn\nAnn\nMike", "Mike\nMike\nMike"]
1e107d9fb8bead4ad942b857685304c4
null
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $$$s$$$ and a number $$$k$$$ ($$$0 \le k &lt; |s|$$$).At the beginning of the game, players are given a substring of $$$s$$$ with left border $$$l$$$ and right border $$$r$$$, both equal to $$$k$$$ (i.e. initially $$$l=r=k$$$). Then players start to make moves one by one, according to the following rules: A player chooses $$$l^{\prime}$$$ and $$$r^{\prime}$$$ so that $$$l^{\prime} \le l$$$, $$$r^{\prime} \ge r$$$ and $$$s[l^{\prime}, r^{\prime}]$$$ is lexicographically less than $$$s[l, r]$$$. Then the player changes $$$l$$$ and $$$r$$$ in this way: $$$l := l^{\prime}$$$, $$$r := r^{\prime}$$$. Ann moves first. The player, that can't make a move loses.Recall that a substring $$$s[l, r]$$$ ($$$l \le r$$$) of a string $$$s$$$ is a continuous segment of letters from s that starts at position $$$l$$$ and ends at position $$$r$$$. For example, "ehn" is a substring ($$$s[3, 5]$$$) of "aaaehnsvz" and "ahz" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $$$s$$$ and $$$k$$$.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $$$s$$$ and determines the winner for all possible $$$k$$$.
Print $$$|s|$$$ lines. In the line $$$i$$$ write the name of the winner (print Mike or Ann) in the game with string $$$s$$$ and $$$k = i$$$, if both play optimally
The first line of the input contains a single string $$$s$$$ ($$$1 \leq |s| \leq 5 \cdot 10^5$$$) consisting of lowercase English letters.
null
null
Python 3
Python
1,300
train_004.jsonl
4cb1087356c162969187cfe58df931d9
256 mebibytes
["abba", "cba"]
PASSED
str = input() min = str[0] print('Mike') for i in range(1, len(str)): if str[i] > min: print('Ann') else: min = str[i] print('Mike')
1568822700
[ "games", "strings" ]
[ 1, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["4\n9\n2\n12\n3\n1"]
2b757fa66ce89046fe18cdfdeafa6660
NoteIn the first test case, one of the optimal solutions is: Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 4$$$ and $$$b = 2$$$. Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 2$$$. Increase $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 3$$$. Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 0$$$ and $$$b = 3$$$.
You have two positive integers $$$a$$$ and $$$b$$$.You can perform two kinds of operations: $$$a = \lfloor \frac{a}{b} \rfloor$$$ (replace $$$a$$$ with the integer part of the division between $$$a$$$ and $$$b$$$) $$$b=b+1$$$ (increase $$$b$$$ by $$$1$$$) Find the minimum number of operations required to make $$$a=0$$$.
For each test case, print a single integer: the minimum number of operations required to make $$$a=0$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$a$$$, $$$b$$$ ($$$1 \le a,b \le 10^9$$$).
standard output
standard input
Python 3
Python
1,000
train_092.jsonl
78a09ee5fffd23419b136d1677624f6c
256 megabytes
["6\n9 2\n1337 1\n1 1\n50000000 4\n991026972 997\n1234 5678"]
PASSED
def count_divs(a, b): count = 0 while a > 0: a = a // b count += 1 return count t = int(input()) for _ in range(t): a, b = map(int, input().split()) b_additions = 0 if b == 1: b = 2 b_additions += 1 prev_res = count_divs(a, b) + b_additions while True: b_additions += 1 b += 1 curr_res = count_divs(a, b) + b_additions if curr_res > prev_res: break prev_res = curr_res print(prev_res)
1613141400
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["Yes\n4 5 16 11 64 44", "Yes\n100 9900", "No"]
d07730b7bbbfa5339ea24162df7a5cab
NoteIn the first example $$$x_1=4$$$ $$$x_1+x_2=9$$$ $$$x_1+x_2+x_3=25$$$ $$$x_1+x_2+x_3+x_4=36$$$ $$$x_1+x_2+x_3+x_4+x_5=100$$$ $$$x_1+x_2+x_3+x_4+x_5+x_6=144$$$ All these numbers are perfect squares.In the second example, $$$x_1=100$$$, $$$x_1+x_2=10000$$$. They are all perfect squares. There're other answers possible. For example, $$$x_1=22500$$$ is another answer.In the third example, it is possible to show, that no such sequence exists.
Chouti is working on a strange math problem.There was a sequence of $$$n$$$ positive integers $$$x_1, x_2, \ldots, x_n$$$, where $$$n$$$ is even. The sequence was very special, namely for every integer $$$t$$$ from $$$1$$$ to $$$n$$$, $$$x_1+x_2+...+x_t$$$ is a square of some integer number (that is, a perfect square).Somehow, the numbers with odd indexes turned to be missing, so he is only aware of numbers on even positions, i.e. $$$x_2, x_4, x_6, \ldots, x_n$$$. The task for him is to restore the original sequence. Again, it's your turn to help him.The problem setter might make mistakes, so there can be no possible sequence at all. If there are several possible sequences, you can output any.
If there are no possible sequence, print "No". Otherwise, print "Yes" and then $$$n$$$ positive integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \le x_i \le 10^{13}$$$), where $$$x_2, x_4, \ldots, x_n$$$ should be same as in input data. If there are multiple answers, print any. Note, that the limit for $$$x_i$$$ is larger than for input data. It can be proved that in case there is an answer, there must be a possible sequence satisfying $$$1 \le x_i \le 10^{13}$$$.
The first line contains an even number $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line contains $$$\frac{n}{2}$$$ positive integers $$$x_2, x_4, \ldots, x_n$$$ ($$$1 \le x_i \le 2 \cdot 10^5$$$).
standard output
standard input
Python 3
Python
1,900
train_010.jsonl
295cae8f4b7e32124a2ccab0c71df4fc
256 megabytes
["6\n5 11 44", "2\n9900", "6\n314 1592 6535"]
PASSED
#!/usr/bin/env python """ This file is part of https://github.com/Cheran-Senthil/PyRival. Copyright 2018 Cheran Senthilkumar all rights reserved, Cheran Senthilkumar <[email protected]> Permission to use, modify, and distribute this software is given under the terms of the MIT License. """ from __future__ import division, print_function import cmath import itertools import math import operator as op # import random import sys from atexit import register from bisect import bisect_left, bisect_right # from collections import Counter, MutableSequence, defaultdict, deque # from copy import deepcopy # from decimal import Decimal # from difflib import SequenceMatcher # from fractions import Fraction # from heapq import heappop, heappush if sys.version_info[0] < 3: # from cPickle import dumps from io import BytesIO as stream # from Queue import PriorityQueue, Queue else: from functools import reduce from io import StringIO as stream from math import gcd # from pickle import dumps # from queue import PriorityQueue, Queue if sys.version_info[0] < 3: class dict(dict): """dict() -> new empty dictionary""" def items(self): """D.items() -> a set-like object providing a view on D's items""" return dict.iteritems(self) def keys(self): """D.keys() -> a set-like object providing a view on D's keys""" return dict.iterkeys(self) def values(self): """D.values() -> an object providing a view on D's values""" return dict.itervalues(self) def gcd(x, y): """gcd(x, y) -> int greatest common divisor of x and y """ while y: x, y = y, x % y return x input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip def sync_with_stdio(sync=True): """Set whether the standard Python streams are allowed to buffer their I/O. Args: sync (bool, optional): The new synchronization setting. """ global input, flush if sync: flush = sys.stdout.flush else: sys.stdin = stream(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip('\r\n') sys.stdout = stream() register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) def memodict(f): """ Memoization decorator for a function taking a single argument. """ class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ @memodict def all_factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1, 2 if n % 2 else 1) if n % i == 0))) def main(): n = int(input()) x = list(map(int, input().split(' '))) a, b = 0, 0 f = all_factors(x[0]) for fi in f: if (fi + (x[0] // fi)) % 2 == 0: na = (fi + (x[0] // fi)) // 2 nb = fi - na if fi > na else (x[0] // fi) - na if (a == 0) or (b == 0): a, b = na, nb else: if na < a: a, b = na, nb if (a == 0) or (b == 0): print('No') return res = [b*b, x[0]] pref_sum = sum(res) for i in range(1, n // 2): a, b = 0, 0 pref_sum += x[i] f = all_factors(x[i]) for fi in f: if (fi + (x[i] // fi)) % 2 == 0: na = (fi + (x[i] // fi)) // 2 nb = fi - na if fi > na else (x[i] // fi) - na if na*na > pref_sum: if (a == 0) or (b == 0): a, b = na, nb else: if na < a: a, b = na, nb if (a == 0) or (b == 0): print('No') return res.append(a*a - pref_sum) pref_sum += res[-1] res.append(x[i]) print('Yes') print(*res) if __name__ == '__main__': sync_with_stdio() main()
1544970900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["5\n9\n0\n117"]
f760f108c66f695e1e51dc6470d29ce7
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,300
train_083.jsonl
cd8b9a9239ea0a48ac46b570813b99fb
256 megabytes
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
PASSED
import sys input = sys.stdin.readline MOD = 998244353 t=int(input()) for _ in range(t): n = int(input()) A = list(map(int, input().split())) cnt = {} ans = 0 for l in range(n - 1, -1, -1): cnt2 = {} a = A[l] for k, v in cnt.items(): tmp = (a + k - 1) // k # k: y ; tmp : K or ceil(ar[i]/y) ; x = a // tmp if x in cnt2: cnt2[x] += v else: cnt2[x] = v ans += (tmp - 1) * (l + 1) * v ans %= MOD cnt = cnt2 if a in cnt: cnt[a] += 1 else: cnt[a] = 1 print(ans)
1635604500
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["YES\n8 10 8", "NO"]
15aa3adb14c17023f71eec11e1c32efe
null
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i &lt; m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on ​​the scales or to say that it can't be done.
In the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers — the weights' weights in the order you put them on the scales. If there are multiple solutions, you can print any of them.
The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i ≥ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≤ m ≤ 1000).
standard output
standard input
Python 3
Python
1,700
train_001.jsonl
a7578778b2b485fe53759e7fdf156656
256 megabytes
["0000000101\n3", "1000000000\n2"]
PASSED
def solve(a, b, m, M, weights, last, solution): # print(a,b,m,M,weights, solution) if (a-b > 10): return False if m == M: print("YES") print(*solution) return True for w in weights: if w != last and b+w > a: solution[m] = w if (solve(b+w, a, m+1, M, weights, w, solution)): return True return False import sys sys.setrecursionlimit(1500) w = input() m = int(input()) weights = [] for i in range(1, 11): if w[i-1] == '1': weights.append(i) weights.sort(reverse=True) solution = [0 for x in range(0,m)] if not solve(0, 0, 0, m, weights, -1, solution): print("NO")
1377531000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["WIN", "WIN", "LOSE"]
d66c7774acb7e4b1f5da105dfa5c1d36
NoteIn the first example, there are 3 possible cells for the first city to reclaim: (2, 1), (3, 1), or (3, 2). The first two possibilities both lose, as they leave exactly one cell for the other city. However, reclaiming the cell at (3, 2) leaves no more cells that can be reclaimed, and therefore the first city wins. In the third example, there are no cells that can be reclaimed.
In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land.The river area can be represented by a grid with r rows and exactly two columns — each cell represents a rectangular area. The rows are numbered 1 through r from top to bottom, while the columns are numbered 1 and 2.Initially, all of the cells are occupied by the river. The plan is to turn some of those cells into land one by one, with the cities alternately choosing a cell to reclaim, and continuing until no more cells can be reclaimed.However, the river is also used as a major trade route. The cities need to make sure that ships will still be able to sail from one end of the river to the other. More formally, if a cell (r, c) has been reclaimed, it is not allowed to reclaim any of the cells (r - 1, 3 - c), (r, 3 - c), or (r + 1, 3 - c).The cities are not on friendly terms, and each city wants to be the last city to reclaim a cell (they don't care about how many cells they reclaim, just who reclaims a cell last). The cities have already reclaimed n cells. Your job is to determine which city will be the last to reclaim a cell, assuming both choose cells optimally from current moment.
Output "WIN" if the city whose turn it is to choose a cell can guarantee that they will be the last to choose a cell. Otherwise print "LOSE".
The first line consists of two integers r and n (1 ≤ r ≤ 100, 0 ≤ n ≤ r). Then n lines follow, describing the cells that were already reclaimed. Each line consists of two integers: ri and ci (1 ≤ ri ≤ r, 1 ≤ ci ≤ 2), which represent the cell located at row ri and column ci. All of the lines describing the cells will be distinct, and the reclaimed cells will not violate the constraints above.
standard output
standard input
Python 3
Python
2,100
train_002.jsonl
9fd1ed24d0de81efd4964e6f88630e77
256 megabytes
["3 1\n1 1", "12 2\n4 1\n8 1", "1 1\n1 2"]
PASSED
r,n = [int(x) for x in input().split()] cells = [[int(x) for x in input().split()] for i in range(n)] cells.sort() #print(cells) out = False res = {True:"WIN",False:"LOSE"} if len(cells) == 0: print(res[r%2 == 1]) else: out = False #print(cells[0][0] > 1) #print(cells[-1][0] < r) for i in range(1,n): out ^= ((cells[i][0]-cells[i-1][0]-1)%2) ^ (cells[i][1] != cells[i-1][1]) dif = abs((cells[0][0]-1)-(r-cells[-1][0])) #print(out,dif) hi,lo = max(cells[0][0]-1,r-cells[-1][0]),min(cells[0][0]-1,r-cells[-1][0]) #print(out,dif,lo,hi) if lo > 1: if dif == 0: print(res[out]) elif dif == 1 and lo % 2 == 0: print(res[not out]) else: print(res[True]) elif lo == 0: if hi == 0: print(res[out]) elif hi == 1: print(res[not out]) else: print(res[True]) elif lo == 1: if hi == 1: print(res[out]) else: print(res[True])
1375549200
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
3 seconds
["0 2\n2 4\n4 6", "0 2\n2 10"]
3088bbe6ff34570ff798d6e3735deda3
NoteIn the first example, it is possible to make all segments equal. Viva la revolucion! In the second example, citizens live close to the capital, so the length of the shortest segment is 2 and the length of the longest segment is 8.
A revolution has recently happened in Segmentland. The new government is committed to equality, and they hired you to help with land redistribution in the country.Segmentland is a segment of length $$$l$$$ kilometers, with the capital in one of its ends. There are $$$n$$$ citizens in Segmentland, the home of $$$i$$$-th citizen is located at the point $$$a_i$$$ kilometers from the capital. No two homes are located at the same point. Each citizen should receive a segment of positive length with ends at integer distances from the capital that contains her home. The union of these segments should be the whole of Segmentland, and they should not have common points besides their ends. To ensure equality, the difference between the lengths of the longest and the shortest segments should be as small as possible.
Output $$$n$$$ pairs of numbers $$$s_i, f_i$$$ ($$$0 \leq s_i &lt; f_i \leq l$$$), one pair per line. The pair on $$$i$$$-th line denotes the ends of the $$$[s_i, f_i]$$$ segment that $$$i$$$-th citizen receives. If there are many possible arrangements with the same difference between the lengths of the longest and the shortest segments, you can output any of them.
The first line of the input contains two integers $$$l$$$ and $$$n$$$ ($$$2 \leq l \leq 10^9; 1 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 &lt; a_1 &lt; a_2 &lt; \dots &lt; a_n &lt; l$$$).
standard output
standard input
PyPy 3-64
Python
2,500
train_091.jsonl
f663c16730040e6b6c3e71fab5722df6
512 megabytes
["6 3\n1 3 5", "10 2\n1 2"]
PASSED
import io import os import heapq from collections import deque, Counter FILE_INPUT_MODE = 0 # 0 for BytesIO, 1 for input.txt, -1 for stdin, input() if FILE_INPUT_MODE >= 0: if FILE_INPUT_MODE == 1: CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) FD = os.open(f"{CURRENT_DIR}\input.txt", os.O_RDONLY) elif FILE_INPUT_MODE == 0: FD = 0 DATA = io.BytesIO(os.read(FD, os.fstat(FD).st_size)) if FD != 0: os.close(FD) def input(): return DATA.readline().decode().rstrip('\r\n') def solve(): def check_max(x): nonlocal n, a, l cur = a[1] for i in range(1, n): if cur > x: return False cur = max(a[i + 1] - a[i] + cur - x, 0) return cur + l - a[n] <= x def check_min(x): nonlocal n, a, l cur = a[1] for i in range(1, n): if cur + a[i + 1] - a[i] < x: return False cur = min(cur + a[i + 1] - a[i] - x, a[i + 1] - a[i]) return True l, n = [int(word) for word in input().split()] a = [int(word) for word in input().split()] a = [0] + a + [l] left = 0 right = l while left + 1 < right: mid = (left + right) // 2 if check_max(mid): right = mid else: left = mid hi = right left = 0 right = l + 1 while left + 1 < right: mid = (left + right) // 2 if check_min(mid): left = mid else: right = mid lo = left graph = [[] for i in range(n + 1)] d = [float('inf') for i in range(n + 1)] for i in range(0, n): graph[i].append((i + 1, hi)) graph[i + 1].append((i, -lo)) for i in range(1, n): graph[0].append((i, a[i + 1])) graph[i].append((n, l - a[i])) graph[0].append((n, l)) d[0] = 0 q = deque([0]) # vis = {0} while len(q) != 0: u = q.popleft() # vis.remove(u) for v, cost in graph[u]: if d[u] + cost < d[v]: d[v] = d[u] + cost # if v not in vis: # vis.add(v) q.append(v) ans = [] for i in range(1, len(d)): ans.append(f"{d[i - 1]} {d[i]}") return "\n".join(ans) def main(): print(solve()) if __name__ == "__main__": main()
1649837100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["0 0 1 2 0 1 \n0 0 \n0 0 2 1 1 0"]
94f1b5a8dfd54bcc1a4150414a48c6dd
null
There are $$$n$$$ cities in Berland. The city numbered $$$1$$$ is the capital. Some pairs of cities are connected by a one-way road of length 1.Before the trip, Polycarp for each city found out the value of $$$d_i$$$ — the shortest distance from the capital (the $$$1$$$-st city) to the $$$i$$$-th city.Polycarp begins his journey in the city with number $$$s$$$ and, being in the $$$i$$$-th city, chooses one of the following actions: Travel from the $$$i$$$-th city to the $$$j$$$-th city if there is a road from the $$$i$$$-th city to the $$$j$$$-th and $$$d_i &lt; d_j$$$; Travel from the $$$i$$$-th city to the $$$j$$$-th city if there is a road from the $$$i$$$-th city to the $$$j$$$-th and $$$d_i \geq d_j$$$; Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action $$$0$$$ or $$$1$$$ time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. For example, if $$$n = 6$$$ and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): $$$2 \rightarrow 5 \rightarrow 1 \rightarrow 2 \rightarrow 5$$$; $$$3 \rightarrow 6 \rightarrow 2$$$; $$$1 \rightarrow 3 \rightarrow 6 \rightarrow 2 \rightarrow 5$$$. Polycarp wants for each starting city $$$i$$$ to find out how close he can get to the capital. More formally: he wants to find the minimal value of $$$d_j$$$ that Polycarp can get from the city $$$i$$$ to the city $$$j$$$ according to the rules described above.
For each test case, on a separate line output $$$n$$$ numbers, the $$$i$$$-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) and $$$m$$$ ($$$1 \leq m \leq 2 \cdot 10^5$$$) — number of cities and roads, respectively. This is followed by $$$m$$$ lines describing the roads. Each road is characterized by two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n, u \ne v$$$) — the numbers of cities connected by a one-way road. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$. It is guaranteed that for each pair of different cities $$$(u, v)$$$ there is at most one road from $$$u$$$ to $$$v$$$ (but a pair of roads from $$$u$$$ to $$$v$$$ and from $$$v$$$ to $$$u$$$ — is valid). It is guaranteed that there is a path from the capital to all cities.
standard output
standard input
PyPy 3-64
Python
2,100
train_090.jsonl
ec81a48098744f3939ece12727ce81d5
256 megabytes
["3\n\n6 7\n1 2\n1 3\n2 5\n2 4\n5 1\n3 6\n6 2\n\n2 2\n1 2\n2 1\n\n6 8\n1 2\n1 5\n2 6\n6 1\n2 3\n3 4\n4 2\n5 4"]
PASSED
import sys, math #sys.setrecursionlimit(10**6) INF = float('inf') mod = 10**9 + 7 #mod = 998244353 input = lambda: sys.stdin.readline().rstrip() li = lambda: list(map(int, input().split())) from collections import deque def bfs(start): queue = deque([start]) seen = [INF] * N seen[start] = 0 while queue: x = queue.popleft() for y in G[x]: if seen[y] < INF: continue seen[y] = seen[x] + 1 queue.append(y) return seen t = int(input()) output = [] for _ in range(t): input() N, M = li() AB = [li() for _ in range(M)] G = [[] for _ in range(N)] for i in range(M): a, b = AB[i] a -= 1; b -= 1 G[a].append(b) dist = bfs(0) ans = bfs(0) for i in range(N): for j in G[i]: ans[i] = min(ans[i], dist[j]) G2 = [[] for _ in range(N)] rG2 = [[] for _ in range(N)] for i in range(M): a, b = AB[i] a -= 1; b -= 1 if dist[a] < dist[b]: G2[a].append(b) rG2[b].append(a) dq = deque() deg = [0] * N for i in range(N): if len(G2[i]) == 0: dq.append(i) deg[i] = len(G2[i]) seen = [0] * N while dq: x = dq.popleft() for y in G2[x]: ans[x] = min(ans[x], ans[y]) for y in rG2[x]: deg[y] -= 1 if not deg[y]: dq.append(y) output.append(ans) for o in output: print(*o)
1609770900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2\n1 3 2 4\n3\n1 2 3 4 5 6\n3\n6 5 4 3 2 1"]
152aba87aaf14d1841f6622dc66051af
NoteFor the first test case, permutation $$$a = [1,3,2,4]$$$ and threshold $$$k = 2$$$ will produce sequence $$$b$$$ as follows. When $$$i = 1$$$, $$$x = a_i = 1 \leq k$$$, there is no $$$a_j$$$ ($$$1 \leq j &lt; i$$$) that $$$a_j &gt; k$$$. Therefore, $$$b_1 = n + 1 = 5$$$. When $$$i = 2$$$, $$$x = a_i = 3 &gt; k$$$, the last element $$$a_j$$$ that $$$a_j \leq k$$$ is $$$a_1$$$. Therefore, $$$b_3 = a_1 = 1$$$. When $$$i = 3$$$, $$$x = a_i = 2 \leq k$$$, the last element $$$a_j$$$ that $$$a_j &gt; k$$$ is $$$a_2$$$. Therefore, $$$b_2 = a_2 = 3$$$. When $$$i = 4$$$, $$$x = a_i = 4 &gt; k$$$, the last element $$$a_j$$$ that $$$a_j \leq k$$$ is $$$a_3$$$. Therefore, $$$b_4 = a_3 = 2$$$. Finally, we obtain sequence $$$b = [5,3,1,2]$$$. For the second test case, permutation $$$a = [1,2,3,4,5,6]$$$ and threshold $$$k = 3$$$ will produce sequence $$$b$$$ as follows. When $$$i = 1, 2, 3$$$, $$$a_i \leq k$$$, there is no $$$a_j$$$ ($$$1 \leq j &lt; i$$$) that $$$a_j &gt; k$$$. Therefore, $$$b_1 = b_2 = b_3 = n + 1 = 7$$$. When $$$i = 4, 5, 6$$$, $$$a_i &gt; k$$$, the last element $$$a_j$$$ that $$$a_j \leq k$$$ is $$$a_3$$$. Therefore, $$$b_4 = b_5 = b_6 = a_3 = 3$$$. Finally, we obtain sequence $$$b = [7,7,7,3,3,3]$$$. For the third test case, permutation $$$a = [6,5,4,3,2,1]$$$ and threshold $$$k = 3$$$ will produce sequence $$$b$$$ as follows. When $$$i = 1, 2, 3$$$, $$$a_i &gt; k$$$, there is no $$$a_j$$$ ($$$1 \leq j &lt; i$$$) that $$$a_j \leq k$$$. Therefore, $$$b_4 = b_5 = b_6 = 0$$$. When $$$i = 4, 5, 6$$$, $$$a_i \leq k$$$, the last element $$$a_j$$$ that $$$a_j &gt; k$$$ is $$$a_3$$$. Therefore, $$$b_1 = b_2 = b_3 = a_3 = 4$$$. Finally, we obtain sequence $$$b = [4,4,4,0,0,0]$$$.
Given a permutation $$$a_1, a_2, \dots, a_n$$$ of integers from $$$1$$$ to $$$n$$$, and a threshold $$$k$$$ with $$$0 \leq k \leq n$$$, you compute a sequence $$$b_1, b_2, \dots, b_n$$$ as follows. For every $$$1 \leq i \leq n$$$ in increasing order, let $$$x = a_i$$$. If $$$x \leq k$$$, set $$$b_{x}$$$ to the last element $$$a_j$$$ ($$$1 \leq j &lt; i$$$) that $$$a_j &gt; k$$$. If no such element $$$a_j$$$ exists, set $$$b_{x} = n+1$$$. If $$$x &gt; k$$$, set $$$b_{x}$$$ to the last element $$$a_j$$$ ($$$1 \leq j &lt; i$$$) that $$$a_j \leq k$$$. If no such element $$$a_j$$$ exists, set $$$b_{x} = 0$$$. Unfortunately, after the sequence $$$b_1, b_2, \dots, b_n$$$ has been completely computed, the permutation $$$a_1, a_2, \dots, a_n$$$ and the threshold $$$k$$$ are discarded. Now you only have the sequence $$$b_1, b_2, \dots, b_n$$$. Your task is to find any possible permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ that produce the sequence $$$b_1, b_2, \dots, b_n$$$. It is guaranteed that there exists at least one pair of permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ that produce the sequence $$$b_1, b_2, \dots, b_n$$$.A permutation of integers from $$$1$$$ to $$$n$$$ is a sequence of length $$$n$$$ which contains all integers from $$$1$$$ to $$$n$$$ exactly once.
For each test case, output the threshold $$$k$$$ ($$$0 \leq k \leq n$$$) in the first line, and then output the permutation $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) in the second line such that the permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ produce the sequence $$$b_1, b_2, \dots, b_n$$$. If there are multiple solutions, you can output any of them.
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the length of the permutation $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq n+1$$$), indicating the elements of the sequence $$$b$$$. It is guaranteed that there exists at least one pair of permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ that produce the sequence $$$b_1, b_2, \dots, b_n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,900
train_103.jsonl
3a5d1f990fe376dad986c5bd1509379b
512 megabytes
["3\n\n4\n\n5 3 1 2\n\n6\n\n7 7 7 3 3 3\n\n6\n\n4 4 4 0 0 0"]
PASSED
# def dfs(node, stack, next, visited): # if node == -1 or node in visited: # return # visited.add(node) # # print(node, next) # dfs(next[node], stack, next, visited) # stack.append(node) import sys from collections import defaultdict # sys.setrecursionlimit(200000) def dfs(node, parents, stack): # print("node", node) dStack = [node] while len(dStack) > 0: # print(dStack) e = dStack.pop() stack.append(e) noParents = [] withParents = [] for p in parents[e]: if len(parents[p]) == 0: noParents.append(p) else: withParents.append(p) # print(noParents + withParents) for p in withParents + noParents: dStack.append(p) t = int(input()) for _ in range(t): n = int(input()) b = [int(e)-1 for e in input().split(' ')] next = [-1]*n parent = defaultdict(list) left = -1 right = n-1 for x, bx in enumerate(b): if bx == -1: right = min(x-1, right) continue if bx == n: left = max(x, left) continue if x < bx: left = max(x, left) right = min(bx-1, right) else: left = max(bx, left) right = min(x-1, right) next[x] = bx parent[bx].append(x) k = left+1 visited = set() start = None # print(parent, next) for i in range(n): if len(parent[i]) != 0 and next[i] == -1: start = i stack = [] # print(start) if start is not None: dfs(start, parent, stack) # print(stack) # for i in range(n): # if next[i] == -1 or i in visited: # continue # dfs(i, stack, next, visited) add = [] for i in range(n): if len(parent[i]) == 0 and next[i] == -1: add.append(i) print(k) print(' '.join([str(e+1) for e in add+stack]))
1664548500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["12.566370614359172464", "21.991148575128551812"]
1d547a38250c7780ddcf10674417d5ff
NoteIn the first sample snow will be removed from that area:
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.
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 .
The first line of the input contains three integers — the number of vertices of the polygon n (), 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.
standard output
standard input
Python 3
Python
1,900
train_020.jsonl
8091f88eb26abb4602aae9807a65d173
256 megabytes
["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"]
PASSED
def dot_product(v1, v2): return v1.x * v2.x + v1.y * v2.y class vector: def __init__(self, x, y): self.x = x self.y = y def length(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def cross_product(self, v): return self.x * v.y - self.y * v.x class line: def __init__(self, a, b): self.a = a self.b = b def distance(self, p): return abs(vector(p.x - self.a.x, p.y - self.a.y).cross_product(vector(p.x - self.b.x, p.y - self.b.y)) / vector(self.a.x - self.b.x, self.a.y - self.b.y).length()) class ray: def __init__(self, a, b): self.a = a self.b = b def distance(self, p): if dot_product(vector(self.b.x - self.a.x, self.b.y - self.a.y), vector(p.x - self.a.x, p.y - self.a.y)) >= 0: return line(self.a, self.b).distance(p) return vector(self.a.x - p.x, self.a.y - p.y).length() class segment: def __init__(self, a, b): self.a = a self.b = b def min_distance(self, p): if dot_product(vector(self.b.x - self.a.x, self.b.y - self.a.y), vector(p.x - self.a.x, p.y - self.a.y)) >= 0: return ray(self.b, self.a).distance(p) return vector(self.a.x - p.x, self.a.y - p.y).length() def max_distance(self, p): return max(vector(self.a.x - p.x, self.a.y - p.y).length(), vector(self.b.x - p.x, self.b.y - p.y).length()) n, x, y = map(int, input().split()) p = vector(x, y) min_r = 2000000 max_r = 0 a = [[] for i in range(n + 1)] for i in range(n): a[i] = list(map(int, input().split())) a[i] = vector(a[i][0], a[i][1]) a[n] = a[0] for i in range(n): s = segment(a[i], a[i + 1]) min_r = min(min_r, s.min_distance(p)) max_r = max(max_r, s.max_distance(p)) pi = 3.141592653589 print(pi * max_r ** 2 - pi * min_r ** 2)
1452789300
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
5 seconds
["10110"]
3c058688183e5cd7dd91ae592ccd8048
NoteThe original scheme from the example (before the input is changed):Green indicates bits '1', yellow indicates bits '0'.If Natasha changes the input bit $$$2$$$ to $$$0$$$, then the output will be $$$1$$$.If Natasha changes the input bit $$$3$$$ to $$$0$$$, then the output will be $$$0$$$.If Natasha changes the input bit $$$6$$$ to $$$1$$$, then the output will be $$$1$$$.If Natasha changes the input bit $$$8$$$ to $$$0$$$, then the output will be $$$1$$$.If Natasha changes the input bit $$$9$$$ to $$$0$$$, then the output will be $$$0$$$.
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $$$1$$$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.There are four types of logical elements: AND ($$$2$$$ inputs), OR ($$$2$$$ inputs), XOR ($$$2$$$ inputs), NOT ($$$1$$$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.For each input, determine what the output will be if Natasha changes this input.
Print a string of characters '0' and '1' (without quotes) — answers to the problem for each input in the ascending order of their vertex indices.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$) — the number of vertices in the graph (both inputs and elements). The $$$i$$$-th of the next $$$n$$$ lines contains a description of $$$i$$$-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows ($$$0$$$ or $$$1$$$), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have $$$2$$$ inputs, whereas "NOT" has $$$1$$$ input. The vertices are numbered from one. It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex $$$1$$$.
standard output
standard input
PyPy 3
Python
2,000
train_017.jsonl
fe5fe577e4accb9887353a67d3e7d5ef
256 megabytes
["10\nAND 9 4\nIN 1\nIN 1\nXOR 6 5\nAND 3 7\nIN 0\nNOT 10\nIN 1\nIN 1\nAND 2 8"]
PASSED
# https://codeforces.com/problemset/problem/1010/D # TLE import sys input=sys.stdin.readline def handle(type_, val_, u, g, S): if type_ == 'NOT': S.append(g[u][0]) else: v1, v2 = g[u] val1, val2 = Val[v1], Val[v2] if oper[type_](1-val1, val2) != val_: S.append(v1) if oper[type_](val1, 1-val2) != val_: S.append(v2) def xor_(a, b): return a ^ b def or_(a, b): return a | b def not_(a): return 1^a def and_(a, b): return a&b g={} # {key: [type, val]} def push(d, u, v): if u not in d: d[u]=[] d[u].append(v) n = int(input()) Val = [None]*n Type = ['']*n for i in range(n): arr = input().split() if len(arr)==2: if arr[0]=='IN': Type[i] = 'IN' Val[i] = int(arr[1]) else: Type[i]=arr[0] push(g, i, int(arr[1])-1) else: type_, v1, v2 = arr[0], int(arr[1]), int(arr[2]) Type[i]=type_ push(g, i, v1-1) push(g, i, v2-1) oper={} oper['XOR']=xor_ oper['OR']=or_ oper['NOT']=not_ oper['AND']=and_ S=[0] i=0 while i<len(S): u=S[i] if u in g: for v in g[u]: S.append(v) i+=1 for u in S[::-1]: if u in g: type_ = Type[u] if len(g[u])==1: val_ = Val[g[u][0]] Val[u] = oper[type_](val_) else: val_1, val_2 = Val[g[u][0]], Val[g[u][1]] Val[u] = oper[type_](val_1, val_2) ans= [0]*n S = [0] i = 0 while i<len(S): u=S[i] if u in g: type_, val_ = Type[u], Val[u] handle(type_, val_, u, g, S) i+=1 root_val = Val[0] ans = [root_val]*n for x in S: if Type[x]=='IN': ans[x]=1-ans[x] print(''.join([str(ans[x]) for x in range(n) if Type[x]=='IN'] ))
1532617500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["3 4 6 5 7", "-1", "3 4 5 2 1 4 3 2"]
c207550a5a74098c1d50407d12a2baec
NoteThe first example is explained is the problem statement.In the third example, for $$$a = [3, 4, 5, 2, 1, 4, 3, 2]$$$, a possible permutation $$$p$$$ is $$$[7, 1, 5, 4, 3, 2, 6]$$$. In that case, Neko would have constructed the following arrays: $$$b = [3, 4, 2, 1, 1, 3, 2]$$$ $$$c = [4, 5, 5, 2, 4, 4, 3]$$$ $$$b' = [2, 3, 1, 1, 2, 4, 3]$$$ $$$c' = [3, 4, 4, 2, 5, 5, 4]$$$
A permutation of length $$$k$$$ is a sequence of $$$k$$$ integers from $$$1$$$ to $$$k$$$ containing each integer exactly once. For example, the sequence $$$[3, 1, 2]$$$ is a permutation of length $$$3$$$.When Neko was five, he thought of an array $$$a$$$ of $$$n$$$ positive integers and a permutation $$$p$$$ of length $$$n - 1$$$. Then, he performed the following: Constructed an array $$$b$$$ of length $$$n-1$$$, where $$$b_i = \min(a_i, a_{i+1})$$$. Constructed an array $$$c$$$ of length $$$n-1$$$, where $$$c_i = \max(a_i, a_{i+1})$$$. Constructed an array $$$b'$$$ of length $$$n-1$$$, where $$$b'_i = b_{p_i}$$$. Constructed an array $$$c'$$$ of length $$$n-1$$$, where $$$c'_i = c_{p_i}$$$. For example, if the array $$$a$$$ was $$$[3, 4, 6, 5, 7]$$$ and permutation $$$p$$$ was $$$[2, 4, 1, 3]$$$, then Neko would have constructed the following arrays: $$$b = [3, 4, 5, 5]$$$ $$$c = [4, 6, 6, 7]$$$ $$$b' = [4, 5, 3, 5]$$$ $$$c' = [6, 7, 4, 6]$$$ Then, he wrote two arrays $$$b'$$$ and $$$c'$$$ on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays $$$b'$$$ and $$$c'$$$ written on it. However he can't remember the array $$$a$$$ and permutation $$$p$$$ he used.In case Neko made a mistake and there is no array $$$a$$$ and permutation $$$p$$$ resulting in such $$$b'$$$ and $$$c'$$$, print -1. Otherwise, help him recover any possible array $$$a$$$.
If Neko made a mistake and there is no array $$$a$$$ and a permutation $$$p$$$ leading to the $$$b'$$$ and $$$c'$$$, print -1. Otherwise, print $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$), denoting the elements of the array $$$a$$$. If there are multiple possible solutions, print any of them.
The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of elements in array $$$a$$$. The second line contains $$$n-1$$$ integers $$$b'_1, b'_2, \ldots, b'_{n-1}$$$ ($$$1 \leq b'_i \leq 10^9$$$). The third line contains $$$n-1$$$ integers $$$c'_1, c'_2, \ldots, c'_{n-1}$$$ ($$$1 \leq c'_i \leq 10^9$$$).
standard output
standard input
Python 3
Python
2,400
train_032.jsonl
add9735b040cd0cbdb11429468c7c618
256 megabytes
["5\n4 5 3 5\n6 7 4 6", "3\n2 4\n3 2", "8\n2 3 1 1 2 4 3\n3 4 4 2 5 5 4"]
PASSED
class multiset: def __init__(self): self.contenido = dict() self.len = 0 def add(self, x): self.contenido[x] = self.contenido.get(x, 0)+1 self.len += 1 def remove(self, x): valor = self.contenido.get(x, 1)-1 if valor == 0: del self.contenido[x] else: self.contenido[x] = valor self.len -= 1 def pop(self): x = next(iter(self.contenido.keys())) self.remove(x) return x def __len__(self): return self.len def __str__(self): return str(self.contenido) n = int(input()) b = [int(a) for a in input().split()] c = [int(a) for a in input().split()] for x, y in zip(b, c): if x > y: print(-1) exit() trad = dict() contador = 0 for a in b+c: if not a in trad: trad[a] = contador contador += 1 v = [multiset() for _ in range(contador)] auxb = [trad[a] for a in b] auxc = [trad[a] for a in c] for x, y in zip(auxb, auxc): v[x].add(y) v[y].add(x) impares = [] for i, a in enumerate(v): if len(a)%2: impares.append(i) primero = 0 if len(impares) == 2: primero = impares[0] elif len(impares) != 0: print(-1) exit() stack = [primero] sol = [] while len(stack): p = stack[-1] if len(v[p]) == 0: sol.append(p) stack.pop() else: h = v[p].pop() v[h].remove(p) stack.append(h) tradaux = {v: k for k, v in trad.items()} if len(sol) != n: print(-1) exit() for i in sol: print(tradaux[i])
1556116500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["9\n8\n11\n8\n8\n8\n9"]
bab40fe0052e2322116c084008c43366
null
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge. The edges are numbered from 1 to m in order of their appearing in input.
First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph. Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.
standard output
standard input
Python 3
Python
2,100
train_019.jsonl
549fb73b0a26d7b8bd5feed1366e110c
256 megabytes
["5 7\n1 2 3\n1 3 1\n1 4 5\n2 3 2\n2 5 3\n3 4 2\n4 5 4"]
PASSED
def find(u): if u == par[u] : return u par[u] = find(par[u]) return par[u] def union(u,v): if len(ev[u]) < len(ev[v]): u, v = v, u par[v] = u for j in ev[v] & ev[u]: ans[j] -= w ev[u] ^= ev[v] n, m = map(int, input().split()) ev = [set() for _ in range(n + 1)] ans,d = [0] * m, [] for i in range(m): u, v, w = map(int, input().split()) d.append((w, u, v)) ev[u].add(i) ev[v].add(i) ans[i] = w par = [i for i in range(n + 1)] g = 0 d.sort() for w, u, v in d: u,v = find(u), find(v) if u != v: g += w union(u,v) for i in range(m): ans[i] += g print(*ans)
1450537200
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["1907", "Impossible", "Infinity", "1897"]
2a4c24341231cabad6021697f15d953a
NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating: Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7. With rating 1894 Limak is in the division 2. His rating increases by 5. Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".
If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.
standard output
standard input
Python 3
Python
1,600
train_007.jsonl
9a738dc403b7b18c118fab0db75e8231
256 megabytes
["3\n-7 1\n5 2\n8 2", "2\n57 1\n22 2", "1\n-5 1", "4\n27 2\n13 1\n-50 1\n8 2"]
PASSED
s, t = -10 ** 8, 10 ** 8 for i in range(int(input())): c, d = map(int, input().split()) if d == 1: s = max(s, 1900) else: t = min(t, 1899) # print(s,t) if s > t: print('Impossible') exit() s, t = s + c, t + c print('Infinity' if t > 5 * 10 ** 7 else t)
1483107300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["&lt;", "&gt;", "=", "&gt;", "&gt;"]
fd63aeefba89bef7d16212a0d9e756cd
null
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().
Print the symbol "&lt;" if a &lt; b and the symbol "&gt;" if a &gt; b. If the numbers are equal print the symbol "=".
The first line contains a non-negative integer a. The second line contains a non-negative integer b. The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.
standard output
standard input
Python 3
Python
900
train_001.jsonl
ce0dcff71efaed247f00b7c787a821e2
256 megabytes
["9\n10", "11\n10", "00012345\n12345", "0123\n9", "0123\n111"]
PASSED
def main(): a = input() b = input() boolean = False index_to_start_a = 0 index_to_start_b = 0 while index_to_start_a < len(a) and a[index_to_start_a] == "0": index_to_start_a += 1 while index_to_start_b < len(b) and b[index_to_start_b] == "0": index_to_start_b += 1 a = a[index_to_start_a:] b = b[index_to_start_b:] length_a = len(a) length_b = len(b) if length_a > length_b: print(">") elif length_a < length_b: print("<") else: for k in range(length_a): if a[k] > b[k]: print(">") boolean = True break if a[k] < b[k]: print("<") boolean = True break if not boolean: print("=") main()
1452524400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["0 1 2", "-10 -9 -8 -7 -6", "Incorrect sequence"]
d42e599073345659188ffea3b2cdd4c7
null
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1  +  a2 ...  +  ak,  a2  +  a3  +  ...  +  ak + 1,  ...,  an - k + 1  +  an - k + 2  +  ...  +  an), then those numbers will form strictly increasing sequence.For example, for the following sample: n = 5,  k = 3,  a = (1,  2,  4,  5,  6) the sequence of numbers will look as follows: (1  +  2  +  4,  2  +  4  +  5,  4  +  5  +  6) = (7,  11,  15), that means that sequence a meets the described property. Obviously the sequence of sums will have n - k + 1 elements.Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes). Otherwise, print n integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains n space-separated elements ai (1 ≤ i ≤ n). If ai  =  ?, then the i-th element of Arthur's sequence was replaced by a question mark. Otherwise, ai ( - 109 ≤ ai ≤ 109) is the i-th element of Arthur's sequence.
standard output
standard input
Python 3
Python
2,200
train_051.jsonl
17fb8fd4f95f32c53197a814d30f60bf
256 megabytes
["3 2\n? 1 2", "5 1\n-10 -9 ? -7 -6", "5 3\n4 6 7 2 9"]
PASSED
INF = 1 << 60 Q = 1 << 58 def solve(): ans = [0] * n for i in range(k): b = [-INF] b.extend(a[i:n:k]) m = len(b) b.append(INF) lb = -INF p, q = 1, 0 while p < m: while b[p] == Q: p += 1 l = p - q - 1 lb = b[q] + 1 for j in range(q + 1, p): b[j] = lb lb += 1 if b[p] < lb: return None if lb < 0: if b[p] > 0: lb = min((l - 1) // 2, b[p] - 1) elif b[p] <= 0: lb = b[p] - 1 for j in range(p - 1, q, -1): b[j] = lb lb -= 1 q = p p = q + 1 ans[i:n:k] = b[1:m] return ans n, k = [int(x) for x in input().split()] a = [Q if x == '?' else int(x) for x in input().split()] ans = solve() if ans is None: print('Incorrect sequence') else: print(*ans)
1424795400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["Lose Win Win Loop\nLoop Win Win Win", "Win Win Win Win Win Win Win\nLose Win Lose Lose Win Lose Lose"]
7c6b04687b4e608be1fd7d04abb015ee
null
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s1 with k1 elements and Morty's is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.
In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.
The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game. The second line contains integer k1 followed by k1 distinct integers s1, 1, s1, 2, ..., s1, k1 — Rick's set. The third line contains integer k2 followed by k2 distinct integers s2, 1, s2, 2, ..., s2, k2 — Morty's set 1 ≤ ki ≤ n - 1 and 1 ≤ si, 1, si, 2, ..., si, ki ≤ n - 1 for 1 ≤ i ≤ 2.
standard output
standard input
PyPy 2
Python
2,000
train_010.jsonl
9ba2f72823c716184674b48e2f5e3236
256 megabytes
["5\n2 3 2\n3 1 2 3", "8\n4 6 2 3 4\n2 3 6"]
PASSED
#!/usr/bin/env python3 from __future__ import absolute_import from sys import stdin,stdout from itertools import imap def ri(): return imap(int, raw_input().split()) n = int(raw_input()) a = list(ri()) b = list(ri()) a = a[1:] b = b[1:] T = [[-1 for i in xrange(2)] for j in xrange(n)] T[0][0] = 1 T[0][1] = 0 for j in xrange(10**9): c = 0 for i in xrange(n-1, -1, -1): #T[i][0] flag = 0 for k in a: ii = (i+k)%n if ii == 0 or T[ii][1] == 0: if T[i][0] !=0: c = 1 T[i][0] = 0 break if T[ii][1] != 1: flag = 1 else: if flag == 0: if T[i][0] !=1: c = 1 T[i][0] = 1 flag = 0 for k in b: ii = (i+k)%n if ii == 0 or T[ii][0] == 1: if T[i][1] !=1: c = 1 T[i][1] = 1 break if T[ii][0] != 0: flag = 1 else: if flag == 0: if T[i][1] !=0: c = 1 T[i][1] = 0 if c == 0: break ansa = [u"Win", u"Lose", u"Loop"] ansb = [u"Lose", u"Win", u"Loop"] aa = [ansa[T[i][0]] for i in xrange(1, n)] bb = [ansb[T[i][1]] for i in xrange(1, n)] print u" ".join(aa) print u" ".join(bb)
1490281500
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["2", "1", "6"]
393ed779ea3ca8fdb63e8de1293eecd3
NoteIn the first sample the superior subarrays are (0, 1) and (3, 2).Subarray (0, 1) is superior, as a0 ≥ a0, a0 ≥ a1, a0 ≥ a2, a0 ≥ a3, a0 ≥ a0, ...Subarray (3, 2) is superior a3 ≥ a3, a0 ≥ a0, a3 ≥ a1, a0 ≥ a2, a3 ≥ a3, ...In the third sample any pair of (l, s) corresponds to a superior subarray as all the elements of an array are distinct.
You are given an infinite periodic array a0, a1, ..., an - 1, ... with the period of length n. Formally, . A periodic subarray (l, s) (0 ≤ l &lt; n, 1 ≤ s &lt; n) of array a is an infinite periodic array with a period of length s that is a subsegment of array a, starting with position l.A periodic subarray (l, s) is superior, if when attaching it to the array a, starting from index l, any element of the subarray is larger than or equal to the corresponding element of array a. An example of attaching is given on the figure (top — infinite array a, bottom — its periodic subarray (l, s)): Find the number of distinct pairs (l, s), corresponding to the superior periodic arrays.
Print a single integer — the sought number of pairs.
The first line contains number n (1 ≤ n ≤ 2·105). The second line contains n numbers a0, a1, ..., an - 1 (1 ≤ ai ≤ 106), separated by a space.
standard output
standard input
PyPy 2
Python
2,400
train_054.jsonl
b4ed419ee263930a37c82b6eba4a43dc
256 megabytes
["4\n7 1 2 3", "2\n2 1", "3\n1 1 1"]
PASSED
# -*- coding: utf-8 -*- import fractions from collections import defaultdict if __name__ == '__main__': n = int(raw_input()) a = map(int, raw_input().split()) a *= 2 inf = min(a) - 1 a[-1] = inf result = 0 numbers_by_gcd = defaultdict(list) for i in xrange(1, n): numbers_by_gcd[fractions.gcd(i, n)].append(i) for d in xrange(1, n): if n % d != 0: continue m = [inf] * d for i in xrange(n): if a[i] > m[i % d]: m[i % d] = a[i] l = 0 r = 0 while l < n: if a[r] < m[r % d]: for i in numbers_by_gcd[d]: if i > r - l: break result += min(r - i, n - 1) - l + 1 l = r + 1 r += 1 print result
1443890700
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["12\n37\n1000000\n5000349985"]
e092d58ac58e1e41d17be946128234e5
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_090.jsonl
6208916751285f37a1001de34997ea92
256 megabytes
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
PASSED
import sys,math input=sys.stdin.readline for _ in range(int(input())): #n=int(input()) n,k=map(int,input().split()) l=list(map(int,input().split())) if n==1: print(l[0]+(k-1)) elif k>=n: ans=sum(l)+((n*(n-1))//2)+n*(k-n) print(ans) else: s=0 for i in range(k): s=s+l[i] x=s for i in range(k,n): x=x-l[i-k]+l[i] s=max(s,x) print(s+((k*(k-1))//2))
1654266900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["acac\nabc\n-1\nabaabaaab"]
6c51676bc12bce8ba6e36b64357ef9f0
NoteIn 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$$$.
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 \ne 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$$$.
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.
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10\,000$$$) — the number of test cases. The next $$$2 \cdot 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 \le k \le n \le 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$$$.
standard output
standard input
Python 3
Python
2,000
train_105.jsonl
8ba251a60d9717dec38f8ef15195c242
256 megabytes
["4\n4 2\nabcd\n3 1\nabc\n4 3\naaaa\n9 3\nabaabaaaa"]
PASSED
import threading import sys threading.stack_size(16*2048*2048) sys.setrecursionlimit(100010) def getnext(index,fre,k,s,flag): if sum(fre)>len(s)-index: return "ERROR" # print(index,fre,pre,flag) if index==len(s): return "" cur = ord(s[index])-97 if not flag: nexts = "" spare = (len(s)-index-sum(fre)) if spare%k==0: nexts += 'a'*(spare//k*k) for j in range(26): if fre[j]>0: nexts += chr(j+97)*fre[j] return nexts nexts = "ERROR" for j in range(cur,26): if j>cur and flag: flag = False fre[j] -= 1 if fre[j]<0: fre[j]+=k temp = getnext(index+1,fre,k,s,flag) if temp!="ERROR": nexts = chr(j+97)+temp return nexts fre[j] += 1 if fre[j]==k: fre[j] = 0 #print(index,fre,nexts) return nexts def main(): T = int(input()) t = 1 while t<=T: n,k = list(map(int,input().split())) s = input() if n%k>0: print(-1) t += 1 continue fre = [0]*26 ans = getnext(0,fre,k,s,True) print(ans) t += 1 threading.Thread(target=main).start()
1615039500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n4"]
a0e738765161bbbfe8e7c5abaa066b0d
NoteFor the first case, the game is as follows: Mr. Chanek takes one coin. The opponent takes two coins. Mr. Chanek takes one coin. The opponent takes one coin. For the second case, the game is as follows: Mr. Chanek takes three coins. The opponent takes one coin. Mr. Chanek takes one coin. The opponent takes one coin.
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $$$N$$$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.
$$$T$$$ lines, each line is the answer requested by Mr. Chanek.
The first line contains a single integer $$$T$$$ $$$(1 \le T \le 10^5)$$$ denotes the number of test cases. The next $$$T$$$ lines each contain a single integer $$$N$$$ $$$(1 \le N \le 10^{18})$$$.
standard output
standard input
PyPy 3
Python
1,400
train_043.jsonl
ddb979e14439371630e5f5c4f12b64f2
256 megabytes
["2\n5\n6"]
PASSED
import os,io input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def fnxn(n): n1 = n ans = 0 while n: if n in dp: ans += dp[n] n = 0 elif n%4 == 0: ans += 1 n -= 2 elif n%2 == 0: n//=2 ans += n n -= 1 else: ans += 1 n -= 1 dp[n1] = ans return ans cases = int(input()) dp = {1:1,2:1,3:2,4:3} for t in range(cases): n = int(input()) if n%2 == 0: print(fnxn(n)) else: print(n-fnxn(n-1))
1601182800
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["36", "1728"]
9a5bd9f937da55c3d26d5ecde6e50280
NoteIn the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.
Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.
Print one integer — the product of all divisors of n modulo 109 + 7.
The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n. The second line contains m primes numbers pi (2 ≤ pi ≤ 200 000).
standard output
standard input
Python 2
Python
2,000
train_020.jsonl
ad569439ed16862257ace1348c875c40
256 megabytes
["2\n2 3", "3\n2 3 2"]
PASSED
from collections import Counter from operator import __mul__ mod = 10 ** 9 + 7 n = input() p = map(int, raw_input().split()) p = Counter(p) prod = 1 exp = 1 perfsq=1 fl=0 for x,a in p.items(): if(a%2==1): fl=1 if(fl): for x,a in p.items(): exp*=(a+1) prod *= pow(x,(a),mod) prod%=mod print pow(prod,exp/2,mod) else: for x,a in p.items(): exp*=(a+1) prod *= pow(x,a/2,mod) prod%=mod print pow(prod,exp,mod)
1452261900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["0\n11\n4\n4\n17\n60"]
28277036765f76f20c327ab2fda6c43b
NoteIn the first test case, we shall not perform any operations as $$$S$$$ is already equal to $$$T$$$, which is the set $$$\{1, 2, 3, 4, 5, 6\}$$$.In the second test case, initially, $$$S = \{1, 2, 3, 4, 5, 6, 7\}$$$, and $$$T = \{1, 2, 4, 7\}$$$. We shall perform the following operations: Choose $$$k=3$$$, then delete $$$3$$$ from $$$S$$$. Choose $$$k=3$$$, then delete $$$6$$$ from $$$S$$$. Choose $$$k=5$$$, then delete $$$5$$$ from $$$S$$$. The total cost is $$$3+3+5 = 11$$$. It can be shown that this is the smallest cost possible.In the third test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{\}$$$ (empty set). We shall perform $$$4$$$ operations of $$$k=1$$$ to delete $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$.In the fourth test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{3\}$$$. We shall perform two operations with $$$k=1$$$ to delete $$$1$$$ and $$$2$$$, then perform one operation with $$$k=2$$$ to delete $$$4$$$.
You are given a set $$$S$$$, which contains the first $$$n$$$ positive integers: $$$1, 2, \ldots, n$$$.You can perform the following operation on $$$S$$$ any number of times (possibly zero): Choose a positive integer $$$k$$$ where $$$1 \le k \le n$$$, such that there exists a multiple of $$$k$$$ in $$$S$$$. Then, delete the smallest multiple of $$$k$$$ from $$$S$$$. This operation requires a cost of $$$k$$$. You are given a set $$$T$$$, which is a subset of $$$S$$$. Find the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$. We can show that such a transformation is always possible.
For each test case, output one non-negative integer — the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$.
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The description of the test cases follows. The first line contains a single positive integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a binary string of length $$$n$$$, describing the set $$$T$$$. The $$$i$$$-th character of the string is '1' if and only if $$$i$$$ is an element of $$$T$$$, and '0' otherwise. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
1,200
train_097.jsonl
ab73b67c320fde1ef1bd893b033ad756
256 megabytes
["6\n\n6\n\n111111\n\n7\n\n1101001\n\n4\n\n0000\n\n4\n\n0010\n\n8\n\n10010101\n\n15\n\n110011100101100"]
PASSED
# func.cache_clear() func.cache_info() no imports # from fractions import Fraction import time # list.sort(key = lambda x: (-x[0], -x[1])) # words.sort(key = lambda x: len(x)) sorts based on length or words.sort(key=len) # d.get(key, num) if key in d then it gives the val for that key else gives the number you have given in place of num # import itertools # XYR = [tuple(map(int, input().split())) for _ in range(n)] import os import sys from io import BytesIO, IOBase # g=defaultdict(lambda :[]) or g=defaultdict(list) # from types import GeneratorType """ IMPORTS -> """ import random # from functools import lru_cache # from array import array as arr # from math import ceil, gcd, log2, sqrt # from bisect import bisect_right, bisect_left, insort, insort_left, insort_right # from queue import PriorityQueue as PQ # from heapq import heapify, heappop, heappush, heappushpop, nlargest, heapreplace, nsmallest # from collections import OrderedDict, defaultdict, deque, Counter # sys.setrecursionlimit(int(1e8)) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) def wrap(x): return x ^ rand # from typing import Generic, Iterable, Iterator, TypeVar, Union, List # T = TypeVar('T') # class SortedMultiset(Generic[T]): # BUCKET_RATIO = 50 # REBUILD_RATIO = 500 # # def _build(self, a=None) -> None: # "Evenly divide `a` into buckets." # if a is None: a = list(self) # size = self.size = len(a) # bucket_size = int(ceil(sqrt(size / self.BUCKET_RATIO))) # self.a = [a[size * i // bucket_size: size * (i + 1) // bucket_size] for i in range(bucket_size)] # # def __init__(self, a: Iterable[T] = []) -> None: # "Make a new SortedMultiset from iterable. / O(N) if sorted / O(N log N)" # a = list(a) # if not all(a[i] <= a[i + 1] for i in range(len(a) - 1)): # a = sorted(a) # self._build(a) # # def __iter__(self) -> Iterator[T]: # for i in self.a: # for j in i: yield j # # def __reversed__(self) -> Iterator[T]: # for i in reversed(self.a): # for j in reversed(i): yield j # # def __len__(self) -> int: # return self.size # # def __repr__(self) -> str: # return "SortedMultiset" + str(self.a) # # def __str__(self) -> str: # s = str(list(self)) # return "{" + s[1: len(s) - 1] + "}" # # def _find_bucket(self, x: T) -> List[T]: # "Find the bucket which should contain x. self must not be empty." # for a in self.a: # if x <= a[-1]: return a # return a # # def __contains__(self, x: T) -> bool: # if self.size == 0: return False # a = self._find_bucket(x) # i = bisect_left(a, x) # return i != len(a) and a[i] == x # # def count(self, x: T) -> int: # "Count the number of x." # return self.index_right(x) - self.index(x) # # def add(self, x: T) -> None: # "Add an element. / O(√N)" # if self.size == 0: # self.a = [[x]] # self.size = 1 # return # a = self._find_bucket(x) # insort(a, x) # self.size += 1 # if len(a) > len(self.a) * self.REBUILD_RATIO: # self._build() # # def discard(self, x: T) -> bool: # "Remove an element and return True if removed. / O(√N)" # if self.size == 0: return False # a = self._find_bucket(x) # i = bisect_left(a, x) # if i == len(a) or a[i] != x: return False # a.pop(i) # self.size -= 1 # if len(a) == 0: self._build() # return True # # def lt(self, x: T) -> Union[T, None]: # "Find the largest element < x, or None if it doesn't exist." # for a in reversed(self.a): # if a[0] < x: # return a[bisect_left(a, x) - 1] # # def le(self, x: T) -> Union[T, None]: # "Find the largest element <= x, or None if it doesn't exist." # for a in reversed(self.a): # if a[0] <= x: # return a[bisect_right(a, x) - 1] # # def gt(self, x: T) -> Union[T, None]: # "Find the smallest element > x, or None if it doesn't exist." # for a in self.a: # if a[-1] > x: # return a[bisect_right(a, x)] # # def ge(self, x: T) -> Union[T, None]: # "Find the smallest element >= x, or None if it doesn't exist." # for a in self.a: # if a[-1] >= x: # return a[bisect_left(a, x)] # # def __getitem__(self, x: int) -> T: # "Return the x-th element, or IndexError if it doesn't exist." # if x < 0: x += self.size # if x < 0: raise IndexError # for a in self.a: # if x < len(a): return a[x] # x -= len(a) # raise IndexError # # def index(self, x: T) -> int: # "Count the number of elements < x." # ans = 0 # for a in self.a: # if a[-1] >= x: # return ans + bisect_left(a, x) # ans += len(a) # return ans # # def index_right(self, x: T) -> int: # "Count the number of elements <= x." # ans = 0 # for a in self.a: # if a[-1] > x: # return ans + bisect_right(a, x) # ans += len(a) # return ans # class DefaultDict: # def __init__(self, default=None): # self.default = default # self.x = random.randrange(1 << 63) # self.dd = defaultdict(default) # # def __repr__(self): # return "{"+", ".join(f"{k ^ self.x}: {v}" for k, v in self.dd.items())+"}" # # def __eq__(self, other): # checks if eq or not # for k in set(self) | set(other): # if self[k] != other[k]: return False # return True # # def __or__(self, other): # res = DefaultDict(self.default) # for k, v in self.dd: res[k] = v # for k, v in other.dd: res[k] = v # return res # # def __len__(self): # return len(self.dd) # # def __getitem__(self, item): # return self.dd[item ^ self.x] # # def __setitem__(self, key, value): # self.dd[key ^ self.x] = value # # self.dd[key ^ self.x].append(value) if list # # def __delitem__(self, key): # del self.dd[key ^ self.x] # # def __contains__(self, item): # return item ^ self.x in self.dd # # def items(self): # for k, v in self.dd.items(): yield (k ^ self.x, v) # # def keys(self): # for k in self.dd: yield k ^ self.x # # def values(self): # for v in self.dd.values(): yield v # # def __iter__(self): # for k in self.dd: yield k ^ self.x # # # class counter(DefaultDict): # def __init__(self, aa=[]): # super().__init__(int) # for a in aa: self.dd[a ^ self.x] += 1 # # def __add__(self, other): # res = Counter() # for k in set(self) | set(other): # v = self[k]+other[k] # if v > 0: res[k] = v # return res # # def __sub__(self, other): # res = Counter() # for k in set(self) | set(other): # v = self[k]-other[k] # if v > 0: res[k] = v # return res # # def __and__(self, other): # res = Counter() # for k in self: # v = min(self[k], other[k]) # if v > 0: res[k] = v # return res # # def __or__(self, other): # res = Counter() # for k in set(self) | set(other): # v = max(self[k], other[k]) # if v > 0: res[k] = v # return res # # # class Set: # def __init__(self, aa=[]): # self.x = random.randrange(1, 1 << 63) # self.st = set() # for a in aa: self.st.add(a ^ self.x) # # def __repr__(self): # return "{"+", ".join(str(k ^ self.x) for k in self.st)+"}" # # def __len__(self): # return len(self.st) # # def add(self, item): # self.st.add(item ^ self.x) # # def discard(self, item): # self.st.discard(item ^ self.x) # # def __contains__(self, item): # return item ^ self.x in self.st # # def __iter__(self): # for k in self.st: yield k ^ self.x # # def pop(self): # return self.st.pop() ^ self.x # # def __or__(self, other): # res = Set(self) # for a in other: res.add(a) # return res # # def __and__(self, other): # res = Set() # for a in self: # if a in other: res.add(a) # for a in other: # if a in self: res.add(a) # return res # # # from RE gives AC or TLE but use dp in lru no dp # def bootstrap(f, stack=[]): # def wrappedfunc(*args, **kwargs): # if stack: # return f(*args, **kwargs) # else: # to = f(*args, **kwargs) # while True: # if type(to) is GeneratorType: # stack.append(to) # to = next(to) # else: # stack.pop() # if not stack: # break # to = stack[-1].send(to) # return to # # return wrappedfunc class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) ss = lambda: sys.stdin.readline().rstrip("\r\n") ip = lambda: int(sys.stdin.readline().rstrip("\r\n")) ips = lambda: map(int, sys.stdin.readline().rstrip("\r\n").split()) ll = lambda: list(map(int, sys.stdin.readline().rstrip("\r\n").split())) sss = lambda: map(str, sys.stdin.readline().rstrip("\r\n").split()) ls = lambda: list(map(str, sys.stdin.readline().rstrip("\r\n").split())) yn = ['No', 'Yes'] YN = ['NO', 'YES'] YY = "YES" NN = "NO" yy = "Yes" nn = "No" rand = random.randrange(1 << 63) letter_val = {chr(97 + i): i for i in range(26)} val_letter = {i: chr(97 + i) for i in range(26)} bigm = int(1e12) mod1 = int(1e9 + 7) mod2 = int(1e9 + 9) mod3 = 998244353 big = sys.maxsize def prog_name(): n = ip() s = ss() final = 0 arr = [False] * (n + 1) # python same code is TLE for i in range(1, n + 1): if s[i - 1] == '0': for j in range(i, n + 1, i): if s[j - 1] == '1': break else: if not arr[j]: final += i arr[j] = True print(final) # print() def main(): # Testcase = 1 Testcase = ip() begin = time.time() for unique in range(Testcase): # print("Case #"+str(unique+1)+":", end = " ") # print("Case #{}: {}".format(unique + 1, prog_name())) # print("Case #{}".format(unique + 1) + ':', end = " ") prog_name() end = time.time() # print(end - begin) if __name__ == "__main__": main()
1663934700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2.500000000000", "8.965874696353"]
de8c909d6ca4f3b2f885fc60be246458
null
Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≤ d &lt; l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.The car can enter Bercouver at any speed.
Print the answer with at least five digits after the decimal point.
The first line of the input file contains two integer numbers a and v (1 ≤ a, v ≤ 10000). The second line contains three integer numbers l, d and w (2 ≤ l ≤ 10000; 1 ≤ d &lt; l; 1 ≤ w ≤ 10000).
standard output
standard input
Python 2
Python
2,100
train_037.jsonl
a29722ae1c580779256ef761736a41cb
64 megabytes
["1 1\n2 1 3", "5 70\n200 170 40"]
PASSED
import math def getfloats(): return map(float, raw_input().split()) def calc(v0, v, a, x): t = (v - v0) / a x0 = v0 * t + 0.5 * a * t * t if x0 > x: return (x, (math.sqrt(v0 * v0 + 2 * a * x) - v0) / a) return (x0, t) def go(v0, v, a, x): x0, t = calc(v0, v, a, x) return t + (x - x0) / v a, v = getfloats() l, d, w = getfloats() if w > v: w = v x, t = calc(0, w, a, d) if x == d: print go(0, v, a, l) else: print t + go(w, v, a, (d - x) * 0.5) * 2 + go(w, v, a, l - d)
1269100800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["9\n4\n6"]
d458a65b351b2ba7f9891178ef1b64a1
NoteInitially, the permutation has the form $$$[1, 2, 3, 4]$$$. Queries processing is as follows: $$$2 + 3 + 4 = 9$$$; $$$[1, 2, 3, 4] \rightarrow [1, 2, 4, 3] \rightarrow [1, 3, 2, 4] \rightarrow [1, 3, 4, 2]$$$; $$$1 + 3 = 4$$$; $$$4 + 2 = 6$$$
A permutation is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ — are permutations, and $$$[1, 1]$$$, $$$[4, 3, 1]$$$, $$$[2, 3, 4]$$$ — no.Permutation $$$a$$$ is lexicographically smaller than permutation $$$b$$$ (they have the same length $$$n$$$), if in the first index $$$i$$$ in which they differ, $$$a[i] &lt; b[i]$$$. For example, the permutation $$$[1, 3, 2, 4]$$$ is lexicographically smaller than the permutation $$$[1, 3, 4, 2]$$$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation $$$a$$$ of length $$$n$$$ — is the lexicographically smallest permutation $$$b$$$ of length $$$n$$$ that lexicographically larger than $$$a$$$. For example: for permutation $$$[2, 1, 4, 3]$$$ the next permutation is $$$[2, 3, 1, 4]$$$; for permutation $$$[1, 2, 3]$$$ the next permutation is $$$[1, 3, 2]$$$; for permutation $$$[2, 1]$$$ next permutation does not exist. You are given the number $$$n$$$ — the length of the initial permutation. The initial permutation has the form $$$a = [1, 2, \ldots, n]$$$. In other words, $$$a[i] = i$$$ ($$$1 \le i \le n$$$).You need to process $$$q$$$ queries of two types: $$$1$$$ $$$l$$$ $$$r$$$: query for the sum of all elements on the segment $$$[l, r]$$$. More formally, you need to find $$$a[l] + a[l + 1] + \ldots + a[r]$$$. $$$2$$$ $$$x$$$: $$$x$$$ times replace the current permutation with the next permutation. For example, if $$$x=2$$$ and the current permutation has the form $$$[1, 3, 4, 2]$$$, then we should perform such a chain of replacements $$$[1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]$$$. For each query of the $$$1$$$-st type output the required sum.
For each query of the $$$1$$$-st type, output on a separate line one integer — the required sum.
The first line contains two integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$), where $$$n$$$ — the length of the initial permutation, and $$$q$$$ — the number of queries. The next $$$q$$$ lines contain a single query of the $$$1$$$-st or $$$2$$$-nd type. The $$$1$$$-st type query consists of three integers $$$1$$$, $$$l$$$ and $$$r$$$ $$$(1 \le l \le r \le n)$$$, the $$$2$$$-nd type query consists of two integers $$$2$$$ and $$$x$$$ $$$(1 \le x \le 10^5)$$$. It is guaranteed that all requests of the $$$2$$$-nd type are possible to process.
standard output
standard input
Python 3
Python
2,400
train_060.jsonl
6478e5dee9b10bb9397ba3050edade76
256 megabytes
["4 4\n1 2 4\n2 3\n1 1 2\n1 3 4"]
PASSED
import io,os;from math import *;input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline manual = 20;n,Q = map(int,input().split());after = min(manual, n);before = n -after;ind = 0 def unrankperm(i): unused = [i+1 for i in range(after)];r = [] for j in range(after)[::-1]:use = i // factorial(j);r.append(unused[use]);del unused[use];i -= use * factorial(j) return r p = unrankperm(ind) for _ in range(Q): q = list(map(int,input().split())) if q[0] == 1: l,r = q[1:];amt = 0 if l <= before:amt += (r * (r + 1) // 2 if r <= before else before * (before + 1) // 2);amt -= l * (l - 1) // 2;l = before + 1 if r > before:amt += sum(p[l-1-before:r-before]) + (r - l + 1) * (before) print(amt) else:ind += q[1];p = unrankperm(ind)
1604327700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["54\n56"]
9089fb2547751ca140a65f03fe78c916
NoteIn the first test case, one of optimal solutions is four paths $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 4$$$, $$$1 \to 4$$$, here $$$c=[4,2,2,2,2]$$$. The value equals to $$$4\cdot 6+ 2\cdot 2+2\cdot 1+2\cdot 5+2\cdot 7=54$$$.In the second test case, one of optimal solution is three paths $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 4$$$, here $$$c=[3,2,2,1,2]$$$. The value equals to $$$3\cdot 6+ 2\cdot 6+2\cdot 1+1\cdot 4+2\cdot 10=56$$$.
You are given a rooted tree consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, and the root is the vertex $$$1$$$. You are also given a score array $$$s_1, s_2, \ldots, s_n$$$.A multiset of $$$k$$$ simple paths is called valid if the following two conditions are both true. Each path starts from $$$1$$$. Let $$$c_i$$$ be the number of paths covering vertex $$$i$$$. For each pair of vertices $$$(u,v)$$$ ($$$2\le u,v\le n$$$) that have the same parent, $$$|c_u-c_v|\le 1$$$ holds. The value of the path multiset is defined as $$$\sum\limits_{i=1}^n c_i s_i$$$.It can be shown that it is always possible to find at least one valid multiset. Find the maximum value among all valid multisets.
For each test case, print a single integer — the maximum value of a path multiset.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two space-separated integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the size of the tree and the required number of paths. The second line contains $$$n - 1$$$ space-separated integers $$$p_2,p_3,\ldots,p_n$$$ ($$$1\le p_i\le n$$$), where $$$p_i$$$ is the parent of the $$$i$$$-th vertex. It is guaranteed that this value describe a valid tree with root $$$1$$$. The third line contains $$$n$$$ space-separated integers $$$s_1,s_2,\ldots,s_n$$$ ($$$0 \le s_i \le 10^4$$$) — the scores of the vertices. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
standard output
standard input
PyPy 3-64
Python
1,900
train_103.jsonl
0aa4f7c04879e29daa20b32f27724b29
256 megabytes
["2\n\n5 4\n\n1 2 1 3\n\n6 2 1 5 7\n\n5 3\n\n1 2 1 3\n\n6 6 1 4 10"]
PASSED
from sys import stdin, stdout from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def readint(): return int(stdin.readline()) def readarray(typ): return list(map(typ, stdin.readline().split())) def print_list(l): print(' '.join(list(map(str, l)))) ans = 0 @bootstrap def dfs(u, adj, ss, ks, cum_scores): global ans k = ks[u] nn = len(adj[u]) ans += ss[u] * k if nn == 0: # leaf cum_scores[u] = ss[u] yield cum_scores[u] scores = [] ks_ = [k // nn for _ in range(nn)] for v, k_ in zip(adj[u], ks_): ks[v] = k_ score = yield dfs(v, adj, ss, ks, cum_scores) scores.append(score) vals = sorted(scores, reverse=True) for val in vals[:k % nn]: ans += val cum_scores[u] = ss[u] + vals[k % nn] yield cum_scores[u] t = readint() for _ in range(t): ans = 0 n, k = readarray(int) ps = readarray(int) ss = readarray(int) adj = [[] for _ in range(n)] for i, p in enumerate(ps): adj[p-1].append(i+1) ks = [k] + [0] * (n-1) cum_scores = [0] * n dfs(0, adj, ss, ks, cum_scores) print(ans)
1665844500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["27", "18"]
de5a9d39dcd9ad7c53ae0fa2d441d3f0
NoteIn the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys all the video cards and pick the one with the power 2 as the leading, the powers of all other video cards should be reduced by 1, thus the total power would be 2 + 2 + 14 + 8 = 26, that is less than 27. Please note, that it's not allowed to reduce the power of the leading video card, i.e. one can't get the total power 3 + 1 + 15 + 9 = 28.In the second sample, the optimal answer is to buy all video cards and pick the one with the power 2 as the leading. The video card with the power 7 needs it power to be reduced down to 6. The total power would be 8 + 2 + 2 + 6 = 18.
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.There are n video cards in the shop, the power of the i-th video card is equal to integer value ai. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.
The only line of the output should contain one integer value — the maximum possible total power of video cards working together.
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of video cards in the shop. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 200 000) — powers of video cards.
standard output
standard input
Python 3
Python
1,900
train_073.jsonl
5daf5dcd6ad1a9d9a9fad2f1a3a09612
256 megabytes
["4\n3 2 15 9", "4\n8 2 2 7"]
PASSED
def main(): n = int(input()) aa = list(map(int, input().split())) aa.sort() lim = aa[-1] + 1 cnt, a = [0] * lim, aa[0] - 1 for i, b in zip(range(n, -1, -1), aa): if a != b: cnt[a + 1:b + 1] = [i] * (b - a) a = b avail, res = [True] * lim, [] for i, a in enumerate(aa): if avail[a]: avail[a] = False res.append(a * sum(cnt[a::a])) print(max(res)) if __name__ == '__main__': main()
1476611100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["YES\n0\n10\n110", "NO"]
1670a3d7dba83e29e98f0ac6fe4acb18
null
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.
If there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next N lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.
The first line contains one integer N (1 ≤ N ≤ 1000) — the number of words in Old Berland language. The second line contains N space-separated integers — the lengths of these words. All the lengths are natural numbers not exceeding 1000.
standard output
standard input
Python 3
Python
1,900
train_029.jsonl
b49df763e44559e6bbc8ca97eb2d7bbc
256 megabytes
["3\n1 2 3", "3\n1 1 1"]
PASSED
import sys sys.setrecursionlimit(1050) class Node: def __init__(self, depth, parent): self.depth = depth self.parent = parent self.left = None self.right = None self.leaf = False def __str__(self): return 'depth = %d, left? %s, right? %s' % (self.depth, self.left != None, self.right != None) stacks = {} def traverse(node, symbols): if node.leaf: s = ''.join(symbols) stacks.setdefault(len(s), []).append(s) return if node.left != None: symbols.append('0') traverse(node.left, symbols) symbols.pop() if node.right != None: symbols.append('1') traverse(node.right, symbols) symbols.pop() n = int(input()) original_lengths = list(map(int, input().split())) lengths = sorted(original_lengths[:]) root = Node(0, None) curr = root for i in range(lengths[0]): curr.left = Node(curr.depth+1, curr) curr = curr.left curr.leaf = True for length in lengths[1:]: curr = curr.parent while curr.right != None: if curr == root: print('NO') sys.exit() curr = curr.parent curr.right = Node(curr.depth+1, curr) curr = curr.right while curr.depth != length: curr.left = Node(curr.depth+1, curr) curr = curr.left curr.leaf = True print('YES') traverse(root, []) for length in original_lengths: print(stacks[length].pop())
1288018800
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
3 seconds
["2", "3", "0", "0"]
b4332870aac6159d5aaa4ff21f8e9f7f
NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game.
The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty).
Print a single integer — the number of ways to choose two different groups such that it's possible to select two teams to play the game.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$) — the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once.
standard output
standard input
PyPy 2
Python
2,500
train_013.jsonl
99c4d33d7a26bfdd881cc121de5f36f7
512 megabytes
["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"]
PASSED
import os import sys from atexit import register from io import BytesIO sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = BytesIO(os.read(0, os.fstat(0).st_size)).readline def main(): class UnionFind(): def __init__(self, n): self.n = n self.root = [-1] * (n + 1) self.rnk = [0] * (n + 1) def find_root(self, x): while self.root[x] >= 0: x = self.root[x] return x def unite(self, x, y): x = self.find_root(x) y = self.find_root(y) if x == y: return elif self.rnk[x] > self.rnk[y]: self.root[x] += self.root[y] self.root[y] = x else: self.root[y] += self.root[x] self.root[x] = y if self.rnk[x] == self.rnk[y]: self.rnk[y] += 1 def unite_root(self, x, y): # assert self.root[x] < 0 and self.root[y] < 0 if self.rnk[x] > self.rnk[y]: self.root[x] += self.root[y] self.root[y] = x else: self.root[y] += self.root[x] self.root[x] = y if self.rnk[x] == self.rnk[y]: self.rnk[y] += 1 def isSameGroup(self, x, y): return self.find_root(x) == self.find_root(y) def size(self, x): return -self.root[self.find_root(x)] N, M, K = map(int, input().split()) C = [0] + list(map(int, input().split())) V_color = [[] for _ in range(K+1)] for v in range(1, N+1): V_color[C[v]].append(v) E = {} UF = UnionFind(2 * N) for _ in range(M): a, b = map(int, input().split()) ca, cb = C[a], C[b] if ca == cb: UF.unite(a, b + N) UF.unite(a + N, b) else: if ca > cb: ca, cb = cb, ca c_ab = ca * (K+1) + cb if c_ab in E: E[c_ab].append((a, b)) else: E[c_ab] = [(a, b)] ok_color_num = 0 ok_color = [0] * (K+1) root_c = [set() for _ in range(K+1)] for c in range(1, K+1): ok = 1 for v in V_color[c]: r1 = UF.find_root(v) r2 = UF.find_root(v+N) if r1 == r2: ok = 0 break else: root_c[c].add(min(r1, r2)) if ok: ok_color_num += 1 ok_color[c] = 1 else: for v in V_color[c]: UF.root[v] = -1 R = [-1] * (N*2+1) for v in range(1, 2*N+1): R[v] = UF.find_root(v) ans = (ok_color_num - 1) * ok_color_num // 2 root_ori = UF.root[:] for c_ab in E: ca, cb = divmod(c_ab, K+1) if ok_color[ca] * ok_color[cb] == 0: continue ok = 1 for a, b in E[c_ab]: ra = R[a] rb = R[b] if ra <= N: ra2 = ra + N else: ra2 = ra - N if rb <= N: rb2 = rb + N else: rb2 = rb - N r_ra = UF.find_root(ra) r_rb2 = UF.find_root(rb2) if r_ra != r_rb2: UF.unite_root(r_ra, r_rb2) r_ra2 = UF.find_root(ra2) r_rb = UF.find_root(rb) if r_ra2 == r_rb: ok = 0 break else: UF.unite_root(r_ra2, r_rb) """ if len(root_c[ca]) > len(root_c[cb]): ca, cb = cb, ca for v in root_c[ca]: if UF.isSameGroup(v, v+N): ok = 0 break """ if ok == 0: ans -= 1 for v in root_c[ca]: UF.root[v] = root_ori[v] UF.root[v+N] = root_ori[v] for v in root_c[cb]: UF.root[v] = root_ori[v] UF.root[v+N] = root_ori[v] print(ans) if __name__ == '__main__': main()
1604228700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["2", "4", "0"]
44d3494f40176d56c8fe57908ff09db5
NoteIn the first test case possible arrays are $$$[1, 2, 1]$$$ and $$$[2, 1, 2]$$$.In the second test case possible arrays are $$$[1, 2]$$$, $$$[1, 3]$$$, $$$[2, 1]$$$ and $$$[2, 3]$$$.
You are given an array of $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$. Your task is to calculate the number of arrays of $$$n$$$ positive integers $$$b_1, b_2, \ldots, b_n$$$ such that: $$$1 \le b_i \le a_i$$$ for every $$$i$$$ ($$$1 \le i \le n$$$), and $$$b_i \neq b_{i+1}$$$ for every $$$i$$$ ($$$1 \le i \le n - 1$$$). The number of such arrays can be very large, so print it modulo $$$998\,244\,353$$$.
Print the answer modulo $$$998\,244\,353$$$ in a single line.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).
standard output
standard input
PyPy 3
Python
2,400
train_088.jsonl
870ea5ed861d57ff48c9bd55ba572e9a
512 megabytes
["3\n2 2 2", "2\n2 3", "3\n1 1 1"]
PASSED
import sys input = sys.stdin.buffer.readline class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) p = 998244353 def process(A): n = len(A) B = [] for i in range(n): B.append([A[i], i]) B.sort() B2 = [] curr = 0 data = [-1 for i in range(n+2)] for i in range(n): if i > 0 and B[i][0] > B[i-1][0]: curr+=1 B2.append([curr, B[i][1]]) Seg = SegmentTree(data=data, default=-1, func=max) B2.sort(key=lambda a: a[1]) S = [None] g = [0] Sn = 0 for i in range(n): ai = A[i] scaled_ai = B2[i][0] j = Seg.query(1, scaled_ai+1) gn1 = g[-1] if j==-1: Sn = ai*(gn1+(-1)**(i)) elif j==i-1: Sn = (ai-1)*S[-1] else: gn1 = g[-1] gi = g[j] Sn = ai*(gn1+(-1)**(i-j+1)*gi)+(-1)**(i-j)*S[j+1] Sn = Sn % p Seg[scaled_ai+1] = i S.append(Sn) g.append(Sn-gn1) print(S[-1]) n = int(input()) A = [int(x) for x in input().split()] process(A)
1639322100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
0.5 seconds
["572", "3574", "-1"]
bc375e27bd52f413216aaecc674366f8
null
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
standard output
standard input
Python 2
Python
1,300
train_001.jsonl
fdfba12830bb7bd699582d5175d1fe3c
256 megabytes
["527", "4573", "1357997531"]
PASSED
#!/usr/bin/env python # -*- encoding: utf-8 -*- # pylint: disable=C0111 def main(): n = list(raw_input().strip()) maxswap = (0, -1) for x in xrange(len(n) - 2, -1, -1): if int(n[x]) % 2 == 0: if maxswap[0] == 0 or (int(n[-1]) - int(n[x]) > 0): maxswap = (int(n[-1]) - int(n[x]), x) if maxswap[1] != -1: x = maxswap[1] n[x], n[-1] = n[-1], n[x] print ''.join(n) else: print -1 main()
1422376200
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
2 seconds
["9\n12\n3595374"]
2cc35227174e6a4d48e0839cba211724
NoteFor $$$n = 3$$$ the sequence is $$$[1,3,4,9...]$$$
Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.
For each test case, print one integer — the $$$k$$$-th special number in increasing order modulo $$$10^9+7$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).
standard output
standard input
Python 3
Python
1,100
train_097.jsonl
1a3f3791cc31c216f3c7afb8215f6371
256 megabytes
["3\n3 4\n2 12\n105 564"]
PASSED
import math t = int(input()) def calcul(n, k): s = 0 while k>0: x = math.log2(k) p = int(x) c = pow(2, p) i = int(c*(x-p)) #update s += pow(n, p) k -= c p = i return s%(1000000007) for i in range(t): n, k = map(int, input().split()) print(calcul(n, k))
1633705500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nYES\nNO\nYES\nYES\nNO\nNO"]
7ac27da2546a50d453f7bb6cacef1068
null
In the pet store on sale there are: $$$a$$$ packs of dog food; $$$b$$$ packs of cat food; $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.
For each test case in a separate line, output: YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats; NO else. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \le a,b,c,x,y \le 10^8$$$).
standard output
standard input
PyPy 3-64
Python
800
train_092.jsonl
f98f3016f39da1ab0ed61bf80c55fa56
256 megabytes
["7\n\n1 1 4 2 3\n\n0 0 0 0 0\n\n5 5 0 4 6\n\n1 1 1 1 1\n\n50000000 50000000 100000000 100000000 100000000\n\n0 0 0 100000000 100000000\n\n1 3 2 2 5"]
PASSED
for _ in range(int(input())): a,b,c,x,y=map(int,input().split()) if a>=x and b>=y: print('YES') elif a>=x and b<y: if b+c<y: print('NO') else: print('YES') elif a<x and b>=y: if a+c<x: print('NO') else: print('YES') else: v = c - ((x - a) + (y - b)) if v>=0: print('YES') else: print('NO')
1651761300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2 1 1 \n9 0 \n0 4 9 6 9"]
fd47f1eb701077abc5ec67163ad4fcc5
NoteIn the first test case, we can prove that initial sequence was $$$[2,1,1]$$$. In that case, the following moves were performed: On the first wheel: $$$2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{D}]{} 9$$$. On the second wheel: $$$1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{U}]{} 3$$$. On the third wheel: $$$1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{U}]{} 1$$$. The final sequence was $$$[9,3,1]$$$, which matches the input.
Luca has a cypher made up of a sequence of $$$n$$$ wheels, each with a digit $$$a_i$$$ written on it. On the $$$i$$$-th wheel, he made $$$b_i$$$ moves. Each move is one of two types: up move (denoted by $$$\texttt{U}$$$): it increases the $$$i$$$-th digit by $$$1$$$. After applying the up move on $$$9$$$, it becomes $$$0$$$. down move (denoted by $$$\texttt{D}$$$): it decreases the $$$i$$$-th digit by $$$1$$$. After applying the down move on $$$0$$$, it becomes $$$9$$$. Example for $$$n=4$$$. The current sequence is 0 0 0 0. Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.
For each test case, output $$$n$$$ space-separated digits  — the initial sequence of the cypher.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of wheels. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 9$$$) — the digit shown on the $$$i$$$-th wheel after all moves have been performed. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains the integer $$$b_i$$$ ($$$1 \leq b_i \leq 10$$$) and $$$b_i$$$ characters that are either $$$\texttt{U}$$$ or $$$\texttt{D}$$$ — the number of moves performed on the $$$i$$$-th wheel, and the moves performed. $$$\texttt{U}$$$ and $$$\texttt{D}$$$ represent an up move and a down move respectively.
standard output
standard input
PyPy 3-64
Python
800
train_086.jsonl
57311e8ef789ed2bee89cb84f7f07670
256 megabytes
["3\n\n3\n\n9 3 1\n\n3 DDD\n\n4 UDUU\n\n2 DU\n\n2\n\n0 9\n\n9 DDDDDDDDD\n\n9 UUUUUUUUU\n\n5\n\n0 5 9 8 3\n\n10 UUUUUUUUUU\n\n3 UUD\n\n8 UUDUUDDD\n\n10 UUDUUDUDDU\n\n4 UUUU"]
PASSED
t = int(input()) while t: n = int(input()) s1 = list(input().split(" ")) swaps = [] while n: sw = input() total_swap = 0 for i in sw: if i == "U": total_swap += 1 elif i == "D": total_swap -= 1 swaps.append(total_swap) n -= 1 for j in range(len(s1)): s1[j] = int(s1[j]) - swaps[j] if s1[j] < 0: s1[j] %= -10 s1[j] = 10 + s1[j] if s1[j] >= 10: s1[j] %= 10 print(*s1) t -= 1
1657636500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["18\n5\n5000000000"]
882deb8385fb175b4547f43b1eb01fc6
NoteIn the first test, you can apply the operation $$$x=1$$$, $$$l=3$$$, $$$r=3$$$, and the operation $$$x=1$$$, $$$l=5$$$, $$$r=5$$$, then the array becomes $$$[0, 6, 2, 1, 4, 5]$$$.In the second test, you can apply the operation $$$x=2$$$, $$$l=2$$$, $$$r=3$$$, and the array becomes $$$[1, 1, -1, -1, 1, -1, 1]$$$, then apply the operation $$$x=2$$$, $$$l=3$$$, $$$r=4$$$, and the array becomes $$$[1, 1, 1, 1, 1, -1, 1]$$$. There is no way to achieve a sum bigger than $$$5$$$.
You are given an array $$$a$$$ of $$$n$$$ integers and a set $$$B$$$ of $$$m$$$ positive integers such that $$$1 \leq b_i \leq \lfloor \frac{n}{2} \rfloor$$$ for $$$1\le i\le m$$$, where $$$b_i$$$ is the $$$i$$$-th element of $$$B$$$. You can make the following operation on $$$a$$$: Select some $$$x$$$ such that $$$x$$$ appears in $$$B$$$. Select an interval from array $$$a$$$ of size $$$x$$$ and multiply by $$$-1$$$ every element in the interval. Formally, select $$$l$$$ and $$$r$$$ such that $$$1\leq l\leq r \leq n$$$ and $$$r-l+1=x$$$, then assign $$$a_i:=-a_i$$$ for every $$$i$$$ such that $$$l\leq i\leq r$$$. Consider the following example, let $$$a=[0,6,-2,1,-4,5]$$$ and $$$B=\{1,2\}$$$: $$$[0,6,-2,-1,4,5]$$$ is obtained after choosing size $$$2$$$ and $$$l=4$$$, $$$r=5$$$. $$$[0,6,2,-1,4,5]$$$ is obtained after choosing size $$$1$$$ and $$$l=3$$$, $$$r=3$$$. Find the maximum $$$\sum\limits_{i=1}^n {a_i}$$$ you can get after applying such operation any number of times (possibly zero).
For each test case print a single integer — the maximum possible sum of all $$$a_i$$$ after applying such operation any number of times.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2\leq n \leq 10^6$$$, $$$1 \leq m \leq \lfloor \frac{n}{2} \rfloor$$$) — the number of elements of $$$a$$$ and $$$B$$$ respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$-10^9\leq a_i \leq 10^9$$$). The third line of each test case contains $$$m$$$ distinct positive integers $$$b_1,b_2,\ldots,b_m$$$ ($$$1 \leq b_i \leq \lfloor \frac{n}{2} \rfloor$$$) — the elements in the set $$$B$$$. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 2
Python
2,400
train_088.jsonl
fc56835124bef36b019bb7ac0f94a91c
256 megabytes
["3\n6 2\n0 6 -2 1 -4 5\n1 2\n7 1\n1 -1 1 -1 1 -1 1\n2\n5 1\n-1000000000 -1000000000 -1000000000 -1000000000 -1000000000\n1"]
PASSED
from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip from bisect import bisect_left as lower_bound, bisect_right as upper_bound def so(): return int(input()) def st(): return input() def mj(): return map(int,input().strip().split(" ")) def msj(): return list(map(str,input().strip().split(" "))) def le(): return list(map(int,input().split())) def rc(): return map(float,input().split()) def lebe():return list(map(int, input())) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() def joro(L): return(''.join(map(str, L))) def decimalToBinary(n): return bin(n).replace("0b","") def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def npr(n, r): return factorial(n) // factorial(n - r) if n >= r else 0 def ncr(n, r): import math as my return my.factorial(n) // (my.factorial(r) * my.factorial(n - r)) if n >= r else 0 def lower_bound(li, num): answer = -1 start = 0 end = len(li) - 1 while (start <= end): middle = (end + start) // 2 if li[middle] >= num: answer = middle end = middle - 1 else: start = middle + 1 return answer # min index where x is not less than num def upper_bound(li, num): answer = -1 start = 0 end = len(li) - 1 while (start <= end): middle = (end + start) // 2 if li[middle] <= num: answer = middle start = middle + 1 else: end = middle - 1 return answer # max index where x is not greater than num def tir(a,b,c): if(0==c): return 1 if(len(a)<=b): return 0 if(c!=-1): return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c)) else: return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1)) hoi=int(2**20) def abs(x): return x if x >= 0 else -x def binary_search(li, val, lb, ub): # print(lb, ub, li) ans = -1 while (lb <= ub): mid = (lb + ub) // 2 # print('mid is',mid, li[mid]) if li[mid] > val: ub = mid - 1 elif val > li[mid]: lb = mid + 1 else: ans = mid # return index break return ans def kadane(x): # maximum sum contiguous subarray sum_so_far = 0 current_sum = 0 for i in x: current_sum += i if current_sum < 0: current_sum = 0 else: sum_so_far = max(sum_so_far, current_sum) return sum_so_far def pref(li): pref_sum = [0] for i in li: pref_sum.append(pref_sum[-1] + i) return pref_sum def gosa(a,b): if(b==0): return a else: return gosa(b,a%b) def SieveOfEratosthenes(n): prime = [True for i in range(n + 1)] p = 2 li = [] while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 for p in range(2, len(prime)): if prime[p]: li.append(p) return li def primefactors(n): factors = [] while (n % 2 == 0): factors.append(2) n //= 2 for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left while n % i == 0: factors.append(i) n //= i if n > 2: # incase of prime factors.append(n) return factors def read(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def tr(n): return n*(n+1)//2 boi=int(1e9-7) doi=int(1e9+7) hoi=int(100+1e6) y="Yes" n="No" x=[0]*hoi y=[0]*hoi def cal(jp,op,u): re=0 te=1 while(te<=op): z=0 p=int(2e9) ad=0 for i in range(te,jp+1,op): if(0>x[i]): z=z^1 ad=abs(x[i])+ad p=min(abs(x[i]),p) if(0!=z^u): ad=-2*p+ad re=ad+re te=1+te return re def iu(): import sys import math as my input=sys.stdin.readline from collections import deque, defaultdict jp,kp=mj() L=le() M=le() for i in range(1+jp): x[i]=L[i-1] op=0 for i in range(1+kp): y[i]=M[i-1] op=gosa(y[i],op) opp=max(cal(jp,op,0),cal(jp,op,1)) print(opp) def main(): for i in range(so()): iu() # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() main() #dmain() # Comment Read()
1643294100
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["3", "0", "755808950"]
f88140475930b3d654ad80d620d48c1a
NoteIn the first sample, there are three active startups labeled $$$1$$$, $$$2$$$ and $$$3$$$, and zero acquired startups. Here's an example of how one scenario can happen Startup $$$1$$$ acquires startup $$$2$$$ (This state can be represented by the array $$$[-1, 1, -1]$$$) Startup $$$3$$$ acquires startup $$$1$$$ (This state can be represented by the array $$$[3, -1, -1]$$$) Startup $$$2$$$ acquires startup $$$3$$$ (This state can be represented by the array $$$[-1, -1, 2]$$$). Startup $$$2$$$ acquires startup $$$1$$$ (This state can be represented by the array $$$[2, -1, 2]$$$). At this point, there is only one active startup, and this sequence of steps took $$$4$$$ days. It can be shown the expected number of days is $$$3$$$.For the second sample, there is only one active startup, so we need zero days.For the last sample, remember to take the answer modulo $$$10^9+7$$$.
There are $$$n$$$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup.The following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day. Two distinct active startups $$$A$$$, $$$B$$$, are chosen uniformly at random. A fair coin is flipped, and with equal probability, $$$A$$$ acquires $$$B$$$ or $$$B$$$ acquires $$$A$$$ (i.e. if $$$A$$$ acquires $$$B$$$, then that means $$$B$$$'s state changes from active to acquired, and its starts following $$$A$$$). When a startup changes from active to acquired, all of its previously acquired startups become active. For example, the following scenario can happen: Let's say $$$A$$$, $$$B$$$ are active startups. $$$C$$$, $$$D$$$, $$$E$$$ are acquired startups under $$$A$$$, and $$$F$$$, $$$G$$$ are acquired startups under $$$B$$$: Active startups are shown in red. If $$$A$$$ acquires $$$B$$$, then the state will be $$$A$$$, $$$F$$$, $$$G$$$ are active startups. $$$C$$$, $$$D$$$, $$$E$$$, $$$B$$$ are acquired startups under $$$A$$$. $$$F$$$ and $$$G$$$ have no acquired startups: If instead, $$$B$$$ acquires $$$A$$$, then the state will be $$$B$$$, $$$C$$$, $$$D$$$, $$$E$$$ are active startups. $$$F$$$, $$$G$$$, $$$A$$$ are acquired startups under $$$B$$$. $$$C$$$, $$$D$$$, $$$E$$$ have no acquired startups: You are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following.You're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end.It can be shown the expected number of days can be written as a rational number $$$P/Q$$$, where $$$P$$$ and $$$Q$$$ are co-prime integers, and $$$Q \not= 0 \pmod{10^9+7}$$$. Return the value of $$$P \cdot Q^{-1}$$$ modulo $$$10^9+7$$$.
Print a single integer, the expected number of days needed for the process to end with exactly one active startup, modulo $$$10^9+7$$$.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 500$$$), the number of startups. The next line will contain $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = -1$$$ or $$$1 \leq a_i \leq n$$$). If $$$a_i = -1$$$, then that means startup $$$i$$$ is active. Otherwise, if $$$1 \leq a_i \leq n$$$, then startup $$$i$$$ is acquired, and it is currently following startup $$$a_i$$$. It is guaranteed if $$$a_i \not= -1$$$, then $$$a_{a_i} =-1$$$ (that is, all startups that are being followed are active).
standard output
standard input
Python 3
Python
3,200
train_035.jsonl
ab7092ad2b2a2b98a8315b00e888c591
256 megabytes
["3\n-1 -1 -1", "2\n2 -1", "40\n3 3 -1 -1 4 4 -1 -1 -1 -1 -1 10 10 10 10 10 10 4 20 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 3 3 3 3 3 3 3 3"]
PASSED
n,a=int(input()),input().split() print((pow(2,n-1)-1-sum(pow(2,a.count(x))-1for x in{*a}-{'-1'}))%(10**9+7))
1534685700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2 4 6 1 3", "1 -3 4 11 6"]
fa256021dc519f526ef3878cce32ff31
NoteIn the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and  - 4 = 4 - 6 + 1 - 3.In the second sample test, the sequence 1,  - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6.
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: The crow sets ai initially 0. The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi + 2 - bi + 3.... Memory gives you the values a1, a2, ..., an, and he now wants you to find the initial numbers b1, b2, ..., bn written in the row? Can you do it?
Print n integers corresponding to the sequence b1, b2, ..., bn. It's guaranteed that the answer is unique and fits in 32-bit integer type.
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of integers written in the row. The next line contains n, the i'th of which is ai ( - 109 ≤ ai ≤ 109) — the value of the i'th number.
standard output
standard input
Python 3
Python
800
train_007.jsonl
e577e8b1dc6f986d3ca89b22e9a18e7c
256 megabytes
["5\n6 -4 8 -2 3", "5\n3 -2 -1 5 6"]
PASSED
a=int(input()) b=list(map(int,input().split())) for x in range(a-1): print(b[x]+b[x+1],end=' ') print(b[-1],end='')
1473525900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["B 4\n\nA 2\n\nA 8\n\nC 4"]
513480a6c7a715e237c3a63805208039
NoteNote that to make the sample more clear, we added extra empty lines. You shouldn't print any extra empty lines during the interaction process.In the first test $$$n=10$$$ and $$$x=4$$$.Initially the set is: $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.In the first operation, you ask how many numbers are multiples of $$$4$$$ and delete them. The answer is $$$2$$$ because there are two numbers divisible by $$$4$$$: $$$\{4,8\}$$$. $$$8$$$ will be deleted but $$$4$$$ won't, because the number $$$x$$$ will never be deleted. Now the set is $$$\{1,2,3,4,5,6,7,9,10\}$$$.In the second operation, you ask how many numbers are multiples of $$$2$$$. The answer is $$$4$$$ because there are four numbers divisible by $$$2$$$: $$$\{2,4,6,10\}$$$.In the third operation, you ask how many numbers are multiples of $$$8$$$. The answer is $$$0$$$ because there isn't any number divisible by $$$8$$$ in the current set.In the fourth operation, you know that $$$x=4$$$, which is the right answer.
This is an interactive problem.There is an unknown integer $$$x$$$ ($$$1\le x\le n$$$). You want to find $$$x$$$.At first, you have a set of integers $$$\{1, 2, \ldots, n\}$$$. You can perform the following operations no more than $$$10000$$$ times: A $$$a$$$: find how many numbers are multiples of $$$a$$$ in the current set. B $$$a$$$: find how many numbers are multiples of $$$a$$$ in this set, and then delete all multiples of $$$a$$$, but $$$x$$$ will never be deleted (even if it is a multiple of $$$a$$$). In this operation, $$$a$$$ must be greater than $$$1$$$. C $$$a$$$: it means that you know that $$$x=a$$$. This operation can be only performed once. Remember that in the operation of type B $$$a&gt;1$$$ must hold.Write a program, that will find the value of $$$x$$$.
null
The first line contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The remaining parts of the input will be given throughout the interaction process.
standard output
standard input
Python 3
Python
2,600
train_002.jsonl
7050d3c4034763a599f5c3db5bc453cd
512 megabytes
["10\n\n2\n\n4\n\n0"]
PASSED
n = int(input()) is_prime = [1] * (n + 1) primes = [2] i = 3 while i * i <= n: if is_prime[i] == 1: primes.append(i) for j in range(i * i, n + 1, i * 2): is_prime[j] = 0 i += 2 for j in range(i, n + 1, 2): if is_prime[j]: primes.append(j) s = set(range(1, n + 1)) ans = 1 l = 0 while l < len(primes): if ans * primes[l] > n: break r = min(l + min(400, max(50, (len(primes) - l) // 2)), len(primes)) for p in primes[l:r]: if ans * p > n: break print(f'B {p}') input() for q in range(p, n + 1, p): s.discard(q) print(f'A 1') res = int(input()) if res > len(s): for p in primes[l:r]: if ans * p > n: break print(f'A {p}') res = int(input()) q = p while res > 0: ans *= p q *= p if ans * p > n: break print(f'A {q}') res = int(input()) l = r break l = r for p in primes[l:]: if ans * p > n: break q = p while ans * q <= n: expected = 0 for i in range(q, n + 1, q): if i in s: expected += 1 print(f'A {q}') res = int(input()) if res == expected: break ans *= p q *= p print(f'C {ans}')
1599918300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["10 10 10 10 10 4 0 0 0 0", "13 13 13 13 0 0 0 0 0 0 0"]
0ad96b6a8032d70df400bf2ad72174bf
null
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture. For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Print n numbers. The i-th of them should be equal to ai.
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
standard output
standard input
Python 2
Python
1,300
train_003.jsonl
ec8ce31bbd816b4ae4e3786bde536b2a
256 megabytes
["10 10 54", "11 13 37"]
PASSED
arr = [int(x) for x in raw_input().split()] n, k, t = arr s = t * n * k / 100 for i in range(n): w = min(s, k) print(w) s -= w
1301410800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6\n15\n-2"]
93fb13c40ab03700ef9a827796bd3d9d
NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \cdot 1 + 5 = 3$$$ points, i. e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations.
You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.
For each testcase, print a single integer — the maximum number of points that you can score.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 100; -100 \le a, b \le 100$$$) — the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.
standard output
standard input
PyPy 3-64
Python
1,000
train_094.jsonl
5500e25cef752be2d521ce1d7a287ea3
256 megabytes
["3\n3 2 0\n000\n5 -2 5\n11001\n6 1 -4\n100111"]
PASSED
# ------------------- fast io -------------------- from itertools import count import os import sys from io import BytesIO, IOBase import math BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def is_prime(n): if (n <= 1): return False for i in range(2, int(math.sqrt(n))+1): if (n % i == 0): return False return True # ------------------- write code from here -------------------- t= int(input()) # l=0 for _ in range(t): # l+=1 # n = int(input()) n, a,b = map(int, input().split()) arr= list(map(int, input())) # print(*arr) # if l==56: # print(n,a,b) # print(*arr) # output_arr =[] if b>=0: print(n*a+n*b) else: count=0 tu=[] t=0 z= arr[0] for i in range(len(arr)): if z!=arr[i]: count+=1 if i==len(arr)-1: tu.append(count) elif z==arr[i] and count>0: tu.append(count) count=0 tu.append(len(arr)-sum(tu)) # print((a*count)+b) ans=0 # print(*tu) for i in tu: ans+= i*a+b print(ans)
1626273300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3", "10", "2"]
4278fece7812148863688c67218aca7b
NoteIn the first example it is enough to set mouse trap in rooms $$$1$$$ and $$$4$$$. If mouse starts in room $$$1$$$ then it gets caught immideately. If mouse starts in any other room then it eventually comes to room $$$4$$$.In the second example it is enough to set mouse trap in room $$$2$$$. If mouse starts in room $$$2$$$ then it gets caught immideately. If mouse starts in any other room then it runs to room $$$2$$$ in second $$$1$$$.Here are the paths of the mouse from different starts from the third example: $$$1 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$; $$$2 \rightarrow 2 \rightarrow \dots$$$; $$$3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$; $$$4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$; $$$5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$; $$$6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$; $$$7 \rightarrow 6 \rightarrow 7 \rightarrow \dots$$$; So it's enough to set traps in rooms $$$2$$$ and $$$6$$$.
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $$$80\%$$$ of applicants are girls and majority of them are going to live in the university dormitory for the next $$$4$$$ (hopefully) years.The dormitory consists of $$$n$$$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $$$i$$$ costs $$$c_i$$$ burles. Rooms are numbered from $$$1$$$ to $$$n$$$.Mouse doesn't sit in place all the time, it constantly runs. If it is in room $$$i$$$ in second $$$t$$$ then it will run to room $$$a_i$$$ in second $$$t + 1$$$ without visiting any other rooms inbetween ($$$i = a_i$$$ means that mouse won't leave room $$$i$$$). It's second $$$0$$$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $$$1$$$ to $$$n$$$ at second $$$0$$$.What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?
Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.
The first line contains as single integers $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of rooms in the dormitory. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^4$$$) — $$$c_i$$$ is the cost of setting the trap in room number $$$i$$$. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — $$$a_i$$$ is the room the mouse will run to the next second after being in room $$$i$$$.
standard output
standard input
Python 3
Python
1,700
train_016.jsonl
f35bf4ec04cdc62c5d494e3fc3d0902b
256 megabytes
["5\n1 2 3 2 10\n1 3 4 3 3", "4\n1 10 2 10\n2 4 2 2", "7\n1 1 1 1 1 1 1\n2 2 2 3 6 7 6"]
PASSED
n = int(input()) C = [int(s) for s in input().split(" ")] A = [int(s)-1 for s in input().split(" ")] al = [False for i in range(0, n)] ans = 0 for v in range(0, n): if al[v]: continue sequence = [] while not al[v]: sequence.append(v) al[v] = True v = A[v] if v in sequence: tek = C[v] for j in sequence[sequence.index(v)+1:]: tek = min(C[j], tek) ans += tek print(ans)
1534602900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1\n0"]
b12f2784bafb3db74598a22ac4603646
NoteIn the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him (, and 2 &lt; 3, but , and 5 ≥ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.Each warrior is represented by his personality — an integer number pi. Each commander has two characteristics — his personality pj and leadership lj (both are integer numbers). Warrior i respects commander j only if ( is the bitwise excluding OR of x and y).Initially Vova's army is empty. There are three different types of events that can happen with the army: 1 pi — one warrior with personality pi joins Vova's army; 2 pi — one warrior with personality pi leaves Vova's army; 3 pi li — Vova tries to hire a commander with personality pi and leadership li. For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.
For each event of the third type print one integer — the number of warriors who respect the commander Vova tries to hire in the event.
The first line contains one integer q (1 ≤ q ≤ 100000) — the number of events. Then q lines follow. Each line describes the event: 1 pi (1 ≤ pi ≤ 108) — one warrior with personality pi joins Vova's army; 2 pi (1 ≤ pi ≤ 108) — one warrior with personality pi leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment); 3 pi li (1 ≤ pi, li ≤ 108) — Vova tries to hire a commander with personality pi and leadership li. There is at least one event of this type.
standard output
standard input
Python 2
Python
2,000
train_000.jsonl
9dd47ff1a6c097b41b91861520e875fe
256 megabytes
["5\n1 3\n1 4\n3 6 3\n2 4\n3 6 3"]
PASSED
from sys import stdin, stdout from itertools import izip def main(it=int, bi=bin): n = int(stdin.readline()) to = [None] * 5800000 s = [0] * 5800000 c = 1 ans = [] pu = ans.append for line in stdin: line = line.split() if line[0] == '3': p, l = bi(it(line[1]))[2:].zfill(28), bi(it(line[2]))[2:].zfill(28) t = 0 f = 0 for pb, lb in izip(p, l): if to[t] is None: break if lb == '1': f += s[to[t][pb=='1']] t = to[t][pb=='0'] else: t = to[t][pb=='1'] pu(f) else: p = bi(it(line[1]))[2:].zfill(28) d = 1 if line[0] == '1' else -1 t = 0 for pb in p: if to[t] is None: to[t] = (c + 1, c + 2) c += 2 t = to[t][pb=='1'] s[t] += d stdout.write('\n'.join(map(str, ans))) main()
1497539100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["1", "0", "2"]
a1c3876d705ac8e8b81394ba2be12ed7
NoteIn the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).In the second sample test the two given words couldn't be obtained from the same word by removing one letter.In the third sample test the two given words could be obtained from either word "tory" or word "troy".
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.
Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo.
The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T. The second line contains word S. The third line contains word T. Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.
standard output
standard input
PyPy 3
Python
1,800
train_060.jsonl
e887d6774737bf369455f3ccd2798865
256 megabytes
["7\nreading\ntrading", "5\nsweet\nsheep", "3\ntoy\ntry"]
PASSED
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## import math import bisect mod = 998244353 # for _ in range(int(input())): from collections import Counter # sys.setrecursionlimit(10**6) # dp=[[-1 for i in range(n+5)]for j in range(cap+5)] # arr= list(map(int, input().split())) # n,l= map(int, input().split()) # arr= list(map(int, input().split())) # for _ in range(int(input())): # n=int(input()) # for _ in range(int(input())): import bisect from heapq import * from collections import defaultdict,deque def okay(x,y): if x<0 or x>=3 : return False if y<n and mat[x][y]!=".": return False if y+1<n and mat[x][y+1]!=".": return False if y+2<n and mat[x][y+2]!=".": return False return True '''for i in range(int(input())): n,m=map(int, input().split()) g=[[] for i in range(n+m)] for i in range(n): s=input() for j,x in enumerate(s): if x=="#": g[i].append(n+j) g[n+j].append(i) q=deque([0]) dis=[10**9]*(n+m) dis[0]=0 while q: node=q.popleft() for i in g[node]: if dis[i]>dis[node]+1: dis[i]=dis[node]+1 q.append(i) print(-1 if dis[n-1]==10**9 else dis[n-1])''' '''from collections import deque t = int(input()) for _ in range(t): q = deque([]) flag=False n,k = map(int, input().split()) mat = [input() for i in range(3)] vis=[[0 for i in range(105)]for j in range(3)] for i in range(3): if mat[i][0]=="s": q.append((i,0)) while q: x,y=q.popleft() if y+1>=n: flag=True break if vis[x][y]==1: continue vis[x][y]=1 if (y+1<n and mat[x][y+1]=='.' and okay(x-1,y+1)==True): q.append((x-1,y+3)) if (y+1<n and mat[x][y+1]=='.' and okay(x,y+1)==True): q.append((x,y+3)) if (y+1<n and mat[x][y+1]=='.' and okay(x+1,y+1)==True): q.append((x+1,y+3)) if flag: print("YES") else: print("NO") # ls=list(map(int, input().split())) # d=defaultdict(list)''' from collections import defaultdict #for _ in range(int(input())): n=int(input()) #n,k= map(int, input().split()) #arr=sorted([i,j for i,j in enumerate(input().split())]) s=input() t=input() n=len(s) f=0 l=0 i=0 while s[i]==t[i]: i+=1 j=n-1 while s[j]==t[j]: j-=1 print(int(s[i:j]==t[i+1:j+1])+int(s[i+1:j+1]==t[i:j]))
1429286400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["NO\nYES\nYES\nYES\nNO"]
7d6d1c5af6e3faefe67f585a5130d6bd
NoteOne possible path for the fourth test case is given in the picture in the statement.
You are given a grid with $$$n$$$ rows and $$$m$$$ columns. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$. All numbers are equal to $$$1$$$ or to $$$-1$$$. You start from the square $$$(1, 1)$$$ and can move one square down or one square to the right at a time. In the end, you want to end up at the square $$$(n, m)$$$.Is it possible to move in such a way so that the sum of the values written in all the visited cells (including $$$a_{11}$$$ and $$$a_{nm}$$$) is $$$0$$$?
For each test case, print "YES" if there exists a path from the top left to the bottom right that adds up to $$$0$$$, and "NO" otherwise. You can output each letter in any case.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)  — the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$a_{ij} = 1$$$ or $$$-1$$$)  — the element in the cell $$$(i, j)$$$. It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_089.jsonl
a65e4a4042961721c6407329f5477aa9
256 megabytes
["5\n\n1 1\n\n1\n\n1 2\n\n1 -1\n\n1 4\n\n1 -1 1 -1\n\n3 4\n\n1 -1 -1 -1\n\n-1 1 1 -1\n\n1 1 1 -1\n\n3 4\n\n1 -1 1 1\n\n-1 1 -1 1\n\n1 -1 1 1"]
PASSED
from sys import stdin input = stdin.readline #// - remember to add .strip() when input is a string t = int(input()) for _ in range(t): n, m = map(int,input().split()) grid = [] for i in range(n): row = list(map(int,input().split())) grid.append(row) new = [] for i in range(len(grid)): for j in range(len(grid[i])): new.append([i,j,grid[i][j]]) new.sort(key=lambda x: (min(x[0],x[1]))) #// max path DPmax = [] for i in range(n): temp = [] for j in range(m): temp.append(0) DPmax.append(temp) DPmax[0][0] = new[0][2] for i in range(1, len(new)): val1 = -float("inf") val2 = -float("inf") if new[i][0] - 1 >= 0: val1 = DPmax[new[i][0] - 1][new[i][1]] if new[i][1] - 1 >= 0: val2 = DPmax[new[i][0]][new[i][1] - 1] DPmax[new[i][0]][new[i][1]] = max(val1, val2) + grid[new[i][0]][new[i][1]] maxi = DPmax[-1][-1] #// min path DPmin = [] for i in range(n): temp = [] for j in range(m): temp.append(0) DPmin.append(temp) DPmin[0][0] = new[0][2] for i in range(1, len(new)): val1 = float("inf") val2 = float("inf") if new[i][0] - 1 >= 0: val1 = DPmin[new[i][0] - 1][new[i][1]] if new[i][1] - 1 >= 0: val2 = DPmin[new[i][0]][new[i][1] - 1] DPmin[new[i][0]][new[i][1]] = min(val1, val2) + grid[new[i][0]][new[i][1]] mini = DPmin[-1][-1] if mini <= 0 and maxi >= 0 and (mini%2==0 or maxi%2==0): # print("YES") else: print("NO")
1655562900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc"]
438d18b7381671df3a68fb421b6c8169
null
This problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $$$s$$$ of length $$$n$$$, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of $$$s[l..r]$$$. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than $$$3$$$ queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ ($$$\lceil x \rceil$$$ is $$$x$$$ rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.
null
First line contains number $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the picked string.
standard output
standard input
PyPy 3
Python
2,800
train_041.jsonl
96af280b0afb82f33da48fc634d9cc66
256 megabytes
["4\n\na\naa\na\n\ncb\nb\nc\n\nc"]
PASSED
from sys import stdout class String2: def __init__(self, s, b=None): if b is not None: self.b = b return self.b = [0] * 26 for i in s: self.b[ord(i) - ord('a')] += 1 def __add__(self, other): b = self.b.copy() for i in range(26): b[i] += other.b[i] return String2('', b) def __sub__(self, other): b = self.b.copy() for i in range(26): b[i] -= other.b[i] return b def __mul__(self, other): ans = String2('', self.b) for i in range(26): ans.b[i] *= other return ans def req(l, r, k=0): print('?', l, r) v = [''.join(sorted(input())) for i in range((r - l + 1) * (r - l + 2) // 2)] stdout.flush() return v def compute(v): bukvi = [[0] * (n + 2) for _ in range(26)] for el in v: cur = len(el) for e in el: bukvi[ord(e) - ord('a')][cur] += 1 return bukvi def compute2(bukvi): bukvis = [set() for i in range(n + 2)] for i in range(26): prev = bukvi[i][1] for j in range(1, n // 2 + n % 2 + 1): while bukvi[i][j] != prev: bukvis[j].add(chr(ord('a') + i)) prev += 1 return bukvis def solve(va, va2): for i in va2: va.remove(i) va.sort(key=len) s = va[0] for i in range(1, len(va)): for j in range(26): if va[i].count(chr(ord('a') + j)) != va[i - 1].count(chr(ord('a') + j)): s += chr(ord('a') + j) return s def check(v, s, s2, f): s3 = String2(v[0]) for i in range(1, len(v)): s3 = s3 + String2(v[i]) le = len(v[0]) cur = String2('', String2('', f - String2(s)) - String2(s2)) * le for i in range(le - 2): cur = cur + (String2(s[i]) * (i + 1)) + (String2(s2[-i-1]) * (i + 1)) cur = cur + (String2(s[le - 2]) * (le - 1)) + (String2(s[le - 1:]) * le) e = cur - s3 for i in range(26): if e[i]: return chr(ord('a') + i) def main(): if n == 1: va = req(1, 1) print('!', va[0]) return elif n == 2: va2 = req(1, 1) va3 = req(2, 2) print('!', va2[0] + va3[0]) return elif n == 3: va = req(1, 1) va2 = req(2, 2) va3 = req(3, 3) print('!', va[0] + va2[0] + va3[0]) return va = req(1, n) va2 = req(1, max(n // 2 + n % 2, 2)) va3 = req(2, max(n // 2 + n % 2, 2)) # bukvi2 = compute(va2) # bukvi3 = compute(va3) ma = [[] for i in range(n * 2)] for i in va: ma[len(i)].append(i) a = String2(''.join(ma[1])) s = solve(va2, va3) s2 = '' for i in range(2, n // 2 + 1): s2 = check(ma[i], s, s2, a) + s2 se = String2('', a - String2(s)) - String2(s2) for i in range(len(se)): if se[i]: s += chr(ord('a') + i) break print('!', s + s2) n = int(input()) main()
1578233100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6 5 4 0 0 0", "1 2 0", "0 6 5 4 3 2 1"]
97e68e5cf05c157b4f83eb07ff003790
null
Nikita likes tasks on order statistics, for example, he can easily find the $$$k$$$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $$$x$$$ is the $$$k$$$-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly $$$k$$$ numbers of this segment which are less than $$$x$$$.Nikita wants to get answer for this question for each $$$k$$$ from $$$0$$$ to $$$n$$$, where $$$n$$$ is the size of the array.
Print $$$n+1$$$ integers, where the $$$i$$$-th number is the answer for Nikita's question for $$$k=i-1$$$.
The first line contains two integers $$$n$$$ and $$$x$$$ $$$(1 \le n \le 2 \cdot 10^5, -10^9 \le x \le 10^9)$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(-10^9 \le a_i \le 10^9)$$$ — the given array.
standard output
standard input
PyPy 3
Python
2,300
train_040.jsonl
d59f52be8990f5ed8efbf2e0e7018c4a
256 megabytes
["5 3\n1 2 3 4 5", "2 6\n-5 9", "6 99\n-1 -1 -1 -1 -1 -1"]
PASSED
from math import pi from cmath import exp def fft(a, lgN, rot=1): # rot=-1 for ifft N = 1<<lgN assert len(a)==N rev = [0]*N for i in range(N): rev[i] = (rev[i>>1]>>1)+(i&1)*(N>>1) A = [a[rev[i]] for i in range(N)] h = 1 while h<N: w_m = exp((0+1j) * rot * (pi / h)) for k in range(0, N, h<<1): w = 1 for j in range(h): t = w * A[k+j+h] A[k+j+h] = A[k+j]-t A[k+j] = A[k+j]+t w *= w_m h = h<<1 return A if rot==1 else [x/N for x in A] import sys ints = (int(x) for x in sys.stdin.read().split()) n, x = (next(ints) for i in range(2)) r = [next(ints) for i in range(n)] ac = [0]*(n+1) for i in range(n): ac[i+1] = (r[i]<x) + ac[i] # Multiset addition min_A, min_B = 0, -ac[-1] max_A, max_B = ac[-1], 0 N, lgN, m = 1, 0, 2*max(max_A-min_A+1, max_B-min_B+1) while N<m: N,lgN = N<<1,lgN+1 a, b = [0]*N, [0]*N for x in ac: a[x-min_A] += 1 b[-x-min_B] += 1 c = zip(fft(a, lgN), fft(b, lgN)) c = fft([x*y for x,y in c], lgN, rot=-1) c = [round(x.real) for x in c][-min_A-min_B:][:n+1] c[0] = sum((x*(x-1))//2 for x in a) print(*c, *(0 for i in range(n+1-len(c))), flush=True)
1529166900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["edb\nccbbba\nbbbbbaaaaaaa\nz\naaaaa"]
9c86925036cd1f83273bc21e2ea3e5c8
NoteIn the first test case, the books can be divided into $$$3$$$ compartments as below: the first compartment contains the books with indices $$$1, 2, 3, 7$$$: $$$multiset_1 = \{$$$'c', 'a', 'b', 'd'$$$\}$$$ $$$\rightarrow$$$ $$$MEX(multiset_1) =$$$ 'e' the second compartment contains the books with indices $$$4, 5, 6, 9$$$ : $$$multiset_2 = \{$$$'c', 'c', 'a', 'b'$$$\}$$$ $$$\rightarrow$$$ $$$MEX(multiset_2) =$$$ 'd' the third compartment contains the remaining books $$$8, 10, 11, 12$$$ : $$$multiset_3 = \{$$$ 'a', 'a', 'a', 'c'$$$\}$$$ $$$\rightarrow$$$ $$$MEX(multiset_3) =$$$ 'b' Therefore, the answer is 'edb'. It can be proven that there is no way that Ela can arrange the books so that it results in a lexicographically greater string.
Ela loves reading a lot, just like her new co-workers in DTL! On her first day after becoming an engineer in DTL, she is challenged by a co-worker to sort a heap of books into different compartments on the shelf.$$$n$$$ books must be split into $$$k$$$ compartments on the bookshelf ($$$n$$$ is divisible by $$$k$$$). Each book is represented by a lowercase Latin letter from 'a' to 'y' inclusively, which is the beginning letter in the title of the book.Ela must stack exactly $$$\frac{n}{k}$$$ books in each compartment. After the books are stacked, for each compartment indexed from $$$1$$$ to $$$k$$$, she takes the minimum excluded (MEX) letter of the multiset of letters formed by letters representing all books in that compartment, then combines the resulting letters into a string. The first letter of the resulting string is the MEX letter of the multiset of letters formed by the first compartment, the second letter of the resulting string is the MEX letter of the multiset of letters formed by the second compartment, ... and so on. Please note, under the constraint of this problem, MEX letter can always be determined for any multiset found in this problem because 'z' is not used.What is the lexicographically greatest resulting string possible that Ela can create?A string $$$a$$$ is lexicographically greater than a string $$$b$$$ if and only if one of the following holds: $$$b$$$ is a prefix of $$$a$$$, but $$$b \ne a$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears later in the alphabet than the corresponding letter in $$$b$$$. The minimum excluded (MEX) letter of a multiset of letters is the letter that appears earliest in the alphabet and is not contained in the multiset. For example, if a multiset of letters contains $$$7$$$ letters 'b', 'a', 'b', 'c', 'e', 'c', 'f' respectively, then the MEX letter of this compartment is 'd', because 'd' is not included in the multiset, and all letters comes before 'd' in the alphabet, namely 'a', 'b' and 'c', are included in the multiset.
For each test case, output a string of $$$k$$$ letters which is the most optimal string that Ela can find.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 200$$$; $$$1 \le k \le n$$$). It is guaranteed that $$$n$$$ is divisible by $$$k$$$. The second line of each test case contains a string of $$$n$$$ lowercase Latin letters from 'a' to 'y' inclusively. Each letter represents the starting letter of the title of a book in the initial heap. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.
standard output
standard input
Python 3
Python
900
train_094.jsonl
e69487aa7886ac8ea861fbf4d2ff0991
256 megabytes
["5\n\n12 3\n\ncabccadabaac\n\n12 6\n\ncabccadabaac\n\n12 12\n\ncabccadabaac\n\n25 1\n\nabcdefghijklmnopqrstuvwxy\n\n10 5\n\nbcdxedbcfg"]
PASSED
import sys input = sys.stdin.buffer.readline def main(): t = int(input()) for _ in range(t): n, k = map(int, input().split()) burti = list(input()) #burti = burti[:-1] print(get_mex(n, k, burti)) def get_mex(n, k, b): burti = [0] * 30 for i in b: if (i >= 97): burti[i - 97] += 1 rtrn_string = "" sub = n // k for i in range(k): indx = min(burti.index(0), sub) last_nonzero_idx = [x for x, e in enumerate(burti) if e != 0] last_nonzero_idx = last_nonzero_idx[-1] burti = burti[:last_nonzero_idx + 2] rtrn_string += chr(indx + 97) crrnt = sub for j in range(indx): if (burti[j] > 0): burti[j] -= 1 crrnt -= 1 if crrnt == 0: break first_zero_indx = burti.index(0) while (crrnt != 0): if (len(burti)-1 == first_zero_indx): idx2 = len(burti) - burti[::-1].index(max(burti)) - 1 burti[idx2] -= 1 else: arr_after_zero = burti[first_zero_indx + 1:] idx2 = len(arr_after_zero) - \ arr_after_zero[::-1].index(max(arr_after_zero)) - 1 if (burti[first_zero_indx + idx2 + 1] > 0): burti[first_zero_indx + idx2 + 1] -= 1 else: idx2 = len(burti) - burti[::-1].index(max(burti)) - 1 burti[idx2] -= 1 crrnt -= 1 return rtrn_string if __name__ == "__main__": main()
1665153300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["100\n22\n14\n42"]
acec4108e865c3f894de14248156abfd
NoteIn the first test case you can remove snow from the cells $$$(2, 1)$$$ and $$$(2, 2)$$$ for $$$100$$$ coins. Then you can give instructions All friends in the first collum should move to the previous cell. After this, your friend will be in the cell $$$(2, 1)$$$. All friends in the second row should move to the next cell. After this, your friend will be in the cell $$$(2, 2)$$$. In the second test case you can remove all snow from the columns $$$3$$$ and $$$4$$$ for $$$22$$$ coins. Then you can give instructions All friends in the first row should move to the next cell. All friends in the first row should move to the next cell. All friends in the second row should move to the next cell. All friends in the second row should move to the next cell. All friends in the third column should move to the next cell. All friends in the third column should move to the next cell. All friends in the fourth column should move to the next cell. All friends in the fourth column should move to the next cell. It can be shown that none of the friends will become ill and that it is impossible to spend less coins.
Circular land is an $$$2n \times 2n$$$ grid. Rows of this grid are numbered by integers from $$$1$$$ to $$$2n$$$ from top to bottom and columns of this grid are numbered by integers from $$$1$$$ to $$$2n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and column $$$y$$$ for $$$1 \leq x \leq 2n$$$ and $$$1 \leq y \leq 2n$$$.There are $$$n^2$$$ of your friends in the top left corner of the grid. That is, in each cell $$$(x, y)$$$ with $$$1 \leq x, y \leq n$$$ there is exactly one friend. Some of the other cells are covered with snow.Your friends want to get to the bottom right corner of the grid. For this in each cell $$$(x, y)$$$ with $$$n+1 \leq x, y \leq 2n$$$ there should be exactly one friend. It doesn't matter in what cell each of friends will be.You have decided to help your friends to get to the bottom right corner of the grid.For this, you can give instructions of the following types: You select a row $$$x$$$. All friends in this row should move to the next cell in this row. That is, friend from the cell $$$(x, y)$$$ with $$$1 \leq y &lt; 2n$$$ will move to the cell $$$(x, y + 1)$$$ and friend from the cell $$$(x, 2n)$$$ will move to the cell $$$(x, 1)$$$. You select a row $$$x$$$. All friends in this row should move to the previous cell in this row. That is, friend from the cell $$$(x, y)$$$ with $$$1 &lt; y \leq 2n$$$ will move to the cell $$$(x, y - 1)$$$ and friend from the cell $$$(x, 1)$$$ will move to the cell $$$(x, 2n)$$$. You select a column $$$y$$$. All friends in this column should move to the next cell in this column. That is, friend from the cell $$$(x, y)$$$ with $$$1 \leq x &lt; 2n$$$ will move to the cell $$$(x + 1, y)$$$ and friend from the cell $$$(2n, y)$$$ will move to the cell $$$(1, y)$$$. You select a column $$$y$$$. All friends in this column should move to the previous cell in this column. That is, friend from the cell $$$(x, y)$$$ with $$$1 &lt; x \leq 2n$$$ will move to the cell $$$(x - 1, y)$$$ and friend from the cell $$$(1, y)$$$ will move to the cell $$$(2n, y)$$$. Note how friends on the grid border behave in these instructions. Example of applying the third operation to the second column. Here, colorful circles denote your friends and blue cells are covered with snow. You can give such instructions any number of times. You can give instructions of different types. If after any instruction one of your friends is in the cell covered with snow he becomes ill.In order to save your friends you can remove snow from some cells before giving the first instruction: You can select the cell $$$(x, y)$$$ that is covered with snow now and remove snow from this cell for $$$c_{x, y}$$$ coins. You can do this operation any number of times.You want to spend the minimal number of coins and give some instructions to your friends. After this, all your friends should be in the bottom right corner of the grid and none of them should be ill.Please, find how many coins you will spend.
For each test case output one integer — the minimal number of coins you should spend.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \leq n \leq 250$$$). Each of the next $$$2n$$$ lines contains $$$2n$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, 2n}$$$ ($$$0 \leq c_{i, j} \leq 10^9$$$) — costs of removing snow from cells. If $$$c_{i, j} = 0$$$ for some $$$i, j$$$ than there is no snow in cell $$$(i, j)$$$. Otherwise, cell $$$(i, j)$$$ is covered with snow. It is guaranteed that $$$c_{i, j} = 0$$$ for $$$1 \leq i, j \leq n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$250$$$.
standard output
standard input
PyPy 3-64
Python
2,100
train_092.jsonl
8f324c47c20358fd3d96489d3977c613
256 megabytes
["4\n\n1\n\n0 8\n\n1 99\n\n2\n\n0 0 0 0\n\n0 0 0 0\n\n9 9 2 2\n\n9 9 9 9\n\n2\n\n0 0 4 2\n\n0 0 2 4\n\n4 2 4 2\n\n2 4 2 4\n\n4\n\n0 0 0 0 0 0 0 2\n\n0 0 0 0 0 0 2 0\n\n0 0 0 0 0 2 0 0\n\n0 0 0 0 2 0 0 0\n\n0 0 0 2 2 0 2 2\n\n0 0 2 0 1 6 2 1\n\n0 2 0 0 2 4 7 4\n\n2 0 0 0 2 0 1 6"]
PASSED
from sys import stdin, gettrace if gettrace(): def inputi(): return input() else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n = int(input()) cc = [[int(c) for c in input().split()] for _ in range(2*n)] res = sum(sum(cc[i][n:]) for i in range(n, 2*n)) + min(cc[0][n], cc[0][2*n - 1], cc[n-1][n], cc[n-1][2*n -1], cc[n][0], cc[2*n-1][0], cc[n][n-1], cc[2*n-1][n-1]) print(res) def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main()
1641220500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["20", "114", "3"]
0b4362204bb9f0e95eaf7e2949315c8f
NoteIn the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). There are pairs of vertices (s, t) such that s &lt; t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5·2 + 10·1 = 20.In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s &lt; t), so the answer is 3·1 = 3.
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s &lt; t.
Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s &lt; t.
The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ 5) — the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) — the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree.
standard output
standard input
PyPy 2
Python
2,100
train_064.jsonl
57b3a9f455ce6f04fc39ab4ec77df006
256 megabytes
["6 2\n1 2\n1 3\n2 4\n2 5\n4 6", "13 3\n1 2\n3 2\n4 2\n5 2\n3 6\n10 6\n6 7\n6 13\n5 8\n5 9\n9 11\n11 12", "3 5\n2 1\n3 1"]
PASSED
def main(): inp = readnumbers() ii = 0 n = inp[ii] ii += 1 k = inp[ii] ii += 1 coupl = [[] for _ in range(n)] for _ in range(n-1): u = inp[ii]-1 ii += 1 v = inp[ii]-1 ii += 1 coupl[u].append(v) coupl[v].append(u) found = [False]*n @bootstrap def solve(node): A = [0]*k A[0] = 1 Acount = 0 Aans = 0 for nei in coupl[node]: if not found[nei]: found[nei] = True B,Bcount,Bans = yield solve(nei) Aans += Bans Aans += Bcount * sum(A) Aans += Acount * sum(B) Acount += Bcount for i in range(k): for j in range(k): Aans += ((i+j+k)//k)*A[i]*B[j] for i in range(k-1): A[i+1] += B[i] A[0] += B[k-1] Acount += B[k-1] yield A,Acount,Aans found[0] = True _,_,ans = solve(0) print ans ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is different which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A # My magical way of doing recursion in python. This # isn't the fastest, but at least it works. from types import GeneratorType def bootstrap(func, stack=[]): def wrapped_function(*args, **kwargs): if stack: return func(*args, **kwargs) else: call = func(*args, **kwargs) while True: if type(call) is GeneratorType: stack.append(call) call = next(call) else: stack.pop() if not stack: break call = stack[-1].send(call) return call return wrapped_function if __name__== "__main__": main()
1489851300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1.5 seconds
["17\n2 5 11\n-1"]
0639fbeb3a5be67a4c0beeffe8f5d43b
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,400
train_109.jsonl
947c08be65b538faad5719f99f375b76
256 megabytes
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
PASSED
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # 2.DFS from a vertex def DFS(self,vertex): path=[] stack=[vertex] visited=defaultdict(lambda:0) while len(stack): u=stack.pop(-1) if visited[u]==0: path.append(u) visited[u]=1 for neighbour in self.graph[u]: if visited[neighbour]==0: stack.append(neighbour) return path t=int(input()) for _ in range(t): n=int(input()) g=Graph() edges=[] for i in range(n-1): u,v=list(map(int,input().split())) g.addEdge(u,v) if u>v: edges.append((v,u)) else: edges.append((u,v)) data=g.graph for vertex in data: if len(data[vertex])>=3: print(-1) break else: path=g.DFS(1) path=g.DFS(path[-1]) res=defaultdict(lambda:0) for i in range(n-1): if i%2==0: if path[i]<path[i+1]: res[(path[i],path[i+1])]=2 else: res[(path[i+1],path[i])]=2 else: if path[i]<path[i+1]: res[(path[i],path[i+1])]=3 else: res[(path[i+1],path[i])]=3 for num in edges: print(res[num],end=" ") print()
1642257300
[ "number theory", "trees" ]
[ 0, 0, 0, 0, 1, 0, 0, 1 ]
3 seconds
["39\n32\n0"]
99e3ab8db0a27cdb6882486dcd46ef0b
Note In the first query, their movement from the $$$1$$$-st to the $$$2$$$-nd room is as follows. $$$1 \rightarrow 5$$$ — takes $$$\max(|10 + 4|, |10 - 4|) = 14$$$ energy. $$$5 \rightarrow 6$$$ — takes $$$\max(|4 + (-6)|, |4 - (-6)|) = 10$$$ energy. $$$6 \rightarrow 2$$$ — takes $$$\max(|-6 + (-9)|, |-6 - (-9)|) = 15$$$ energy. In total, it takes $$$39$$$ energy.In the second query, the illusion rate of the $$$1$$$-st room changes from $$$10$$$ to $$$-3$$$.In the third query, their movement from the $$$1$$$-st to the $$$2$$$-nd room is as follows. $$$1 \rightarrow 5$$$ — takes $$$\max(|-3 + 4|, |-3 - 4|) = 7$$$ energy. $$$5 \rightarrow 6$$$ — takes $$$\max(|4 + (-6)|, |4 - (-6)|) = 10$$$ energy. $$$6 \rightarrow 2$$$ — takes $$$\max(|-6 + (-9)|, |-6 - (-9)|) = 15$$$ energy. Now, it takes $$$32$$$ energy.
Chanek Jones is back, helping his long-lost relative Indiana Jones, to find a secret treasure in a maze buried below a desert full of illusions.The map of the labyrinth forms a tree with $$$n$$$ rooms numbered from $$$1$$$ to $$$n$$$ and $$$n - 1$$$ tunnels connecting them such that it is possible to travel between each pair of rooms through several tunnels.The $$$i$$$-th room ($$$1 \leq i \leq n$$$) has $$$a_i$$$ illusion rate. To go from the $$$x$$$-th room to the $$$y$$$-th room, there must exist a tunnel between $$$x$$$ and $$$y$$$, and it takes $$$\max(|a_x + a_y|, |a_x - a_y|)$$$ energy. $$$|z|$$$ denotes the absolute value of $$$z$$$.To prevent grave robbers, the maze can change the illusion rate of any room in it. Chanek and Indiana would ask $$$q$$$ queries.There are two types of queries to be done: $$$1\ u\ c$$$ — The illusion rate of the $$$x$$$-th room is changed to $$$c$$$ ($$$1 \leq u \leq n$$$, $$$0 \leq |c| \leq 10^9$$$). $$$2\ u\ v$$$ — Chanek and Indiana ask you the minimum sum of energy needed to take the secret treasure at room $$$v$$$ if they are initially at room $$$u$$$ ($$$1 \leq u, v \leq n$$$). Help them, so you can get a portion of the treasure!
For each type $$$2$$$ query, output a line containing an integer — the minimum sum of energy needed for Chanek and Indiana to take the secret treasure.
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq q \leq 10^5$$$) — the number of rooms in the maze and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq |a_i| \leq 10^9$$$) — inital illusion rate of each room. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$s_i$$$ and $$$t_i$$$ ($$$1 \leq s_i, t_i \leq n$$$), meaning there is a tunnel connecting $$$s_i$$$-th room and $$$t_i$$$-th room. The given edges form a tree. The next $$$q$$$ lines contain the query as described. The given queries are valid.
standard output
standard input
PyPy 3
Python
2,300
train_102.jsonl
84f05661557fd1a0cc492051130ef824
512 megabytes
["6 4\n10 -9 2 -1 4 -6\n1 5\n5 4\n5 6\n6 2\n6 3\n2 1 2\n1 1 -3\n2 1 2\n2 3 3"]
PASSED
def naiveSolve(): return def solve(): return from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc class SegmentTree(): def __init__(self,arr,combinerFunction,isCommutative=True): # isCommutative means f(a,b)==f(b,a) self.n=len(arr) def cmb(a,b): if a==None: return b if b==None: return a return combinerFunction(a,b) self.cmb=cmb self.sz=self.n if isCommutative else pow(2,((self.n-1).bit_length())) # non-commutative needs power of 2 size self.t=[None]*(2*self.sz) # use None as initial value for i in range(self.n): self.t[i+self.sz]=arr[i] for i in range(self.sz-1,0,-1): self.pull(i) def pull(self,p): self.t[p]=self.cmb(self.t[2*p],self.t[2*p+1]) def update(self,idx,val): # set val at idx idx+=self.sz self.t[idx]=val idx//=2 while idx>0: self.pull(idx) idx//=2 def query(self,l,r): # aggregated value in [l,r] inclusive l+=self.sz; r+=self.sz+1 a=b=None while l<r: if l%2==1: a=self.cmb(a,self.t[l]); l+=1 if r%2==1: r-=1; b=self.cmb(self.t[r],b) l//=2; r//=2 return self.cmb(a,b) def getMaxSegTree(arr): return SegmentTree(arr,lambda a,b:max(a,b),True) def getMinSegTree(arr): return SegmentTree(arr,lambda a,b:min(a,b),True) def getSumSegTree(arr): return SegmentTree(arr,lambda a,b:a+b,True) def main(): n,q=readIntArr() a=readIntArr() for i in range(n): a[i]=abs(a[i]) adj=[[] for _ in range(n)] for _ in range(n-1): u,v=readIntArr(); u-=1; v-=1 adj[u].append(v) adj[v].append(u) # Using the fact that max(abs(x+y),abs(x-y))=abs(x)+abs(y), # and using an Euler tour to "flatten" the tree to allow for querying. # Store an array of size 2*n. Save the entry and exit indexes in the # euler tour array. When entering, store abs(a) in euler tour array. # When exiting, store -abs(a). # To update, change the entry and exit indexes of euler tour array. # To get distance from root, query from 0 to the entry index. # Use LCA to find common ancestor, and subtract the dist from node to # common ancestor. root=0 ## To modify accordingly @bootstrap def eulerTour(node,p): # O(n) up[node][0]=p tin[node]=time[0] eulerTourArr[time[0]]=2*a[node] # add cost time[0]+=1 for v in adj[node]: # adj[u]=[v1,v2,v3,...] if v!=p: yield eulerTour(v,node) tout[node]=time[0] eulerTourArr[time[0]]=-2*a[node] # subtract cost for prefix sum to give cost from root to node time[0]+=1 yield None time=[0] tin=[-1]*(n) # this is also the node entry index in eulerTourArr tout=[-1]*(n) # this is also the node exit index in eulerTourArr maxPow=0 while pow(2,maxPow)<n: maxPow+=1 maxPow+=1 up=[[-1 for _ in range(maxPow)] for __ in range(n+1)] eulerTourArr=[0]*(2*n) # stores the energy sum for 2 * node eulerTour(root,-1) for i in range(1,maxPow): # Build up in O(nlogn) for u in range(1,n+1): if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root continue up[u][i]=up[up[u][i-1]][i-1] def isAncestor(u,v): # True if u is ancestor of v return tin[u]<=tin[v] and tout[u]>=tout[v] def findLCA(u,v): # Find LCA in O(logn) # traverse u to LCA if not isAncestor(u,v): u2=u for i in range(maxPow-1,-1,-1): if up[u2][i]!=-1 and not isAncestor(up[u2][i],v): u2=up[u2][i] # next level up is lca lca=up[u2][0] else: lca=u return lca st=getSumSegTree(eulerTourArr) allans=[] # print(tin) # print(tout) for _ in range(q): x,u,v=readIntArr(); u-=1 if x==1: # update u to c c=abs(v) st.update(tin[u],2*c) st.update(tout[u],-2*c) a[u]=c else: # query u to v v-=1 # print(eulerTourArr) rootToU=st.query(0,tin[u])-a[root]-a[u] rootToV=st.query(0,tin[v])-a[root]-a[v] lca=findLCA(u,v) rootToLCA=st.query(0,tin[lca])-a[root]-a[lca] ans=rootToU+rootToV-2*rootToLCA allans.append(ans) # print('u:{} v:{} rootToU:{} roottoV:{} lca:{}'.format( # u+1,v+1,rootToU,rootToV,lca+1)) multiLineArrayPrint(allans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(x): print('{}'.format(x)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil # from math import floor,ceil # for Python2 for _abc in range(1): main()
1633181700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["10.0000000000", "-1", "85.4800000000"]
d9bd63e03bf51ed87ba73cd15e8ce58d
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
standard output
standard input
Python 3
Python
1,500
train_000.jsonl
81dc74b11eab12928dcc4fe4ab4fde0f
256 megabytes
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
PASSED
"""for p in range(int(input())): n,k=map(int,input().split(" ")) number=input().split(" ") chances=[k for i in range(n)] prev=-1 prev_updated=-1 last_used=False toSub=0 start=0 prevSub=0 if(number[0]=='1'): prev=0 prev_updated=0 start=1 for i in range(start,n): if(number[i]=='1'): # print("\ni",i,"\ntoSub",toSub,"\nprevUpadted",prev_updated,"\nprev",prev,"\nlast_used",last_used) f1=False # toSub+=1 toSub=0 zeros=i - prev_updated - 1 if(last_used): zeros-=1 #chances[i]-=toSub #print(prevSub,(i - prev - 1 ) +1) if(i - prev - 1 <= prevSub): chances[i]-= prevSub - (i - prev - 1 ) +1 if(chances[i]<zeros): chances[i]=zeros toSub+= prevSub - (i - prev - 1 ) +1 f1=True if(zeros==0 or chances[i]==0): prev_updated=i prev=i last_used=False prevSub=toSub continue # print("\nchances: ",chances[i],"\t\tzeroes : ",zeros,"\t\tprevSub :",prevSub) if(chances[i]>zeros): # print("\t\t\t\t1") number[i-zeros]='1' number[i]='0' prev_updated=i-zeros last_used=False elif(chances[i]==zeros): # print("\t\t\t\t2") number[i]='0' number[i-chances[i]]='1' prev_updated=i-chances[i] last_used=True else: # print("\t\t\t\t3") number[i]='0' number[i-chances[i]]='1' prev_updated=i-chances[i] last_used=True prev=i prevSub=toSub if(prev_updated>2 and f1): if(number[prev_updated]=='1' and number[prev_updated-1]=='0' and number[prev_updated-2]=='1'): last_used=False #if() # print("\ni",i,"\ntoSub",toSub,"\nprevUpadted",prev_updated,"\nprev",prev,"\nlast_used",last_used) # print(number) else: toSub=0 print(*number) # print(chances)""" """class offer: def __init__(self, n, fre): self.num = n self.free = fre self.delta= n-fre n,m,k=map(int,input().split(" ")) shovel=list(map(int,input().split(" "))) #dicti={} offers=[] temp_arr=[False for i in range(n)] for i in range(m): p,q=map(int,input().split(" ")) if(p>k): continue offers.append(offer(p,q)) # dicti[p]=q #for i in dicti: # dicti[i].sort() shovel.sort() shovel=shovel[:k+1] offers.sort(key=lambda x: x.delta/x.num,reverse=True) bestoffer=[] for i in offers: if(not temp_arr[i.num]): temp_arr[i.num]=True bestoffer.append(i) cost=0 for i in bestoffer: for p in range(int(input())): arr=list(input()) n=len(arr) for i in range(n): arr[i]=ord(arr[i])-96 arr.sort() arr1=arr[:n//2] arr2=arr[n//2:] arr=[] #print(arr,arr1,arr2) i1=n//2-1 i2=n-i1-2 while (i1!=-1 and i2!=-1): arr.append(arr1[i1]) arr.append(arr2[i2]) i1-=1 i2-=1 if(i1!=-1): arr.append(arr1[i1]) elif(i2!=-1): arr.append(arr2[i2]) #print(arr) s="" for i in range(n-1): if(abs(arr[i]-arr[i+1])==1): s=-1 print("No answer") break else: s+=chr(arr[i]+96) if(s!=-1): s+=chr(arr[-1]+96) print(s)""" """ n,m=map(int,input().split(" ")) seti=[] ans=[1 for i in range(n)] for i in range(m): arr=list(map(int,input().split(" "))) if(arr[0]>1): seti.append(set(arr[1:])) else: m-=1 parent=[-1 for i in range(m)] #print(seti) for i in range(m-1): for j in range(i+1,m): if(parent[j]==-1): if(len(seti[i].intersection(seti[j]))>0): seti[i]=seti[i].union(seti[j]) parent[j]=i #print(parent) for i in range(m): if(parent[i]==-1): temp=list(seti[i]) store=len(temp) for j in temp: ans[j-1]=store print(*ans) for p in range(int(input())): arr=list(input()) n=len(arr) for i in range(n): arr[i]=ord(arr[i])-96 arr.sort() arr1=arr[:n//2] arr2=arr[n//2:] arr=[] #print(arr,arr1,arr2) i1=n//2-1 i2=n-i1-2 while (i1!=-1 and i2!=-1): arr.append(arr1[i1]) arr.append(arr2[i2]) i1-=1 i2-=1 if(i1!=-1): arr.append(arr1[i1]) elif(i2!=-1): arr.append(arr2[i2]) s="" for i in range(n-1): if(abs(arr[i]-arr[i+1])==1): s=-1 print("No answer") break else: s+=chr(arr[i]+96) if(s!=-1): s+=chr(arr[-1]+96) print(s) #n=0""" n=int(input()) p=int(input()) arr1=list(map(int,input().split(" "))) arr2=list(map(int,input().split(" "))) a=1 flag=False for i in range(n): a*=((arr1[i]-1)*(arr2[i]-1))/(arr1[i]*arr2[i]) if(a==0): flag=True break if(flag): print(-1) else: print(p*((1-a)/a))
1532617500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["Freda's\nOMG&gt;.&lt; I don't know!\nOMG&gt;.&lt; I don't know!\nRainbow's\nOMG&gt;.&lt; I don't know!"]
ee9ba877dee1a2843e885a18823cbff0
null
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.
For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG&gt;.&lt; I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.
The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.
standard output
standard input
Python 2
Python
1,100
train_005.jsonl
6b79c0b265b02b0d8b1c3879c2880d13
256 megabytes
["5\nI will go to play with you lala.\nwow, welcome.\nmiao.lala.\nmiao.\nmiao ."]
PASSED
I=lambda:map(int, raw_input().split()) n=input() for _ in xrange(n): s=raw_input() if s.startswith('miao.') and s.endswith('lala.'): print 'OMG>.< I don\'t know!' elif s.startswith('miao.'): print 'Rainbow\'s' elif s.endswith('lala.'): print 'Freda\'s' else: print 'OMG>.< I don\'t know!'
1369582200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["3", "10"]
782b819eb0bfc86d6f96f15ac09d5085
NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process. Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.
Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).
The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
standard input
Python 3
Python
1,300
train_023.jsonl
acd19a5f6a8b1c40c2c03f39b1e4fa52
256 megabytes
["1", "2"]
PASSED
n = int(input()) mod = 10**9 +7 def power_2_k(k): if k == 0: return 1 if k % 2 == 0: lower = power_2_k(k // 2) return (lower * lower) % mod else: k -= 1 lower = power_2_k(k // 2) return (((lower * lower) % mod) * 2) % mod p = power_2_k(n) print((p * (p + 1) // 2) % mod)
1336145400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0\nDDRR"]
13c58291ab9cf7ad1b8c466c3e36aacf
null
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
standard output
standard input
PyPy 3
Python
2,000
train_004.jsonl
fce8911b7e6e06e7b36a7a2c9f5b4251
64 megabytes
["3\n1 2 3\n4 5 6\n7 8 9"]
PASSED
n = int(input()) xr = range(n) a5 = [list(map(int, input().split())) for _ in xr] a2 = [[0 for _ in xr] for _ in xr] y = 0 x0 = -1 for y in xr: for x in xr: i = a5[y][x] m5 = 0 m2 = 0 if i == 0: x0 = x while i and i%2 == 0: i/=2 m2+=1 while i and i%5 == 0: i/=5 m5+=1 if y == 0 and x == 0: a5[y][x] = m5 a2[y][x] = m2 continue left5 = a5[y][x-1] left2 = a2[y][x-1] up5 = a5[y-1][x] up2 = a2[y-1][x] if y == 0: a5[y][x] = left5 + m5 a2[y][x] = left2 + m2 continue if x == 0: a5[y][x] = up5 + m5 a2[y][x] = up2 + m2 continue a5[y][x] = min(up5, left5) + m5 a2[y][x] = min(up2, left2) + m2 def getpath(k): p = '' y = x = n-1 while not (y == 0 and x == 0): if y and x: if k == 5: if a5[y-1][x] < a5[y][x-1]: p+='D' y-=1 else: p+='R' x-=1 else: if a2[y-1][x] < a2[y][x-1]: p+='D' y-=1 else: p+='R' x-=1 elif y == 0: p+='R' x-=1 elif x == 0: p+='D' y-=1 return p[::-1] ten = 0 path = '' if a5[n-1][n-1] < a2[n-1][n-1]: ten = a5[n-1][n-1] path = getpath(5) else: ten = a2[n-1][n-1] path = getpath(2) if ten > 1 and x0 > -1: ten = 1 path = 'R'*x0 + 'D'*(n-1) + 'R'*(n-1-x0) print(ten) print(path)
1267117200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n****\n*..*\n****\n****\n..**", "1\n***\n***\n***"]
e514d949e7837c603a9ee032f83b90d2
NoteIn the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.
The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.
In the first line print the minimum number of cells which should be transformed from water to land. In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them. It is guaranteed that the answer exists on the given data.
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.
standard output
standard input
Python 3
Python
1,600
train_027.jsonl
7ffd074e9d27acae64081da685cb6dac
256 megabytes
["5 4 1\n****\n*..*\n****\n**.*\n..**", "3 3 0\n***\n*.*\n***"]
PASSED
n,m,k = (int(x) for x in input().split()) Map = [] lakesizes = [0] lakemembers = [0] for i in range(n): Map.append([x for x in input()]) stack = [(x,y,None) for x in range(1,m-1) for y in range(1,n-1)] + [(0,y,None) for y in range(n)] + [(m-1,y,None) for y in range(n)] + [(x,0,None) for x in range(1,m-1)] + [(x,n-1,None) for x in range(1,m-1)] lakenumber = [ [None]*m for y in range(n) ] for y in range(n): for x in range(m): if Map[y][x] == '.': lakenumber[y][x] = -1 while(stack): x,y,current = stack.pop() if lakenumber[y][x] is not None and lakenumber[y][x] < 0: if current is None: if x in [0,m-1] or y in [0,n-1]: current = 0 else: current = len(lakesizes) lakesizes.append(0) lakemembers.append([]) lakenumber[y][x] = current lakesizes[current] += 1 if current > 0: lakemembers[current].append( (x,y) ) for xo,yo in [(x,y+1),(x,y-1),(x+1,y),(x-1,y)]: if 0 <= yo < n and 0 <= xo < m: stack.append( (xo,yo,current) ) ordlakes = [(lakesizes[i],i) for i in range(1,len(lakesizes))] ordlakes.sort() totalsize = 0 for i in range(len(ordlakes)-k): size,ind = ordlakes[i] totalsize += size for x,y in lakemembers[ind]: Map[y][x] = '*' print(totalsize) for i in range(n): print(''.join(Map[i]))
1475494500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4", "3"]
09f5623c3717c9d360334500b198d8e0
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
standard output
standard input
PyPy 2
Python
1,600
train_009.jsonl
598070e42b55dd31be98dadc7a48faed
256 megabytes
["3\n3 2 2", "4\n2 2 2 2"]
PASSED
""" // Author : snape_here - Susanta Mukherjee """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def fi(): return float(input()) def si(): return input() def mi(): return map(int,input().split()) def li(): return list(mi()) def read(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def isPrime(n): if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def gcd(x, y): while y: x, y = y, x % y return x mod=1000000007 from math import log,sqrt,factorial,cos,tan,sin,radians,ceil,floor import bisect from decimal import * getcontext().prec = 25 abc="abcdefghijklmnopqrstuvwxyz" pi=3.141592653589793238 def main(): n=ii() a=li() ans=int(ceil(sum(a)/(n-1))) ans=max(ans,max(a)) print(ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() main()
1380295800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1.5000000000", "10.2222222222"]
f404720fd6624174c33d93af6349e561
NoteIn the first sample, Niwel has three bears. Two bears can choose the path , while one bear can choose the path . Even though the bear that goes on the path can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. 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 .
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively. Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
standard output
standard input
Python 3
Python
2,200
train_051.jsonl
88233b56744fe41b4fe1fcc8149e2b33
256 megabytes
["4 4 3\n1 2 2\n2 4 1\n1 3 1\n3 4 2", "5 11 23\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 3 4\n2 4 5\n3 5 6\n1 4 2\n2 5 3\n1 5 2\n3 2 30"]
PASSED
from queue import Queue def addEdge(s, t, flow): E[s].append((len(E[t]), t, flow)) E[t].append((len(E[s])-1, s, 0)) def mkLevel(): global src, des, E, lvl for i in range(n): lvl[i] = -1 lvl[src] = 0 q = Queue() q.put(src) while (not q.empty()): cur = q.get() for j in range(len(E[cur])): to = E[cur][j][1] if (lvl[to] < 0 and E[cur][j][2] > 0): lvl[to] = lvl[cur] + 1 q.put(to) if (to == des): return True return False def extend(cur, lim): global des, E if (lim == 0 or cur == des): return lim flow = 0 for j in range(len(E[cur])): if (flow >= lim): break to = E[cur][j][1] lim0 = min(lim-flow, E[cur][j][2]) if (E[cur][j][2] > 0 and lvl[to] == lvl[cur] + 1): newf = extend(to, lim0) if (newf > 0): E[cur][j] = (E[cur][j][0], E[cur][j][1], E[cur][j][2] - newf) jj = E[cur][j][0] E[to][jj] = (E[to][jj][0], E[to][jj][1], E[to][jj][2] + newf) flow += newf if (flow == 0): lvl[cur] = -1 return flow def Dinic(): # for i in range(len(E)): # print('i = {} : {}'.format(i, E[i]), flush = True) flow = 0 newf = 0 while (mkLevel()): newf = extend(src, INF) while (newf > 0): flow += newf newf = extend(src, INF) return flow def check(mid): global E E = [[] for i in range(n)] for i in range(m): if (w[i] - bears * mid > 0): addEdge(u[i], v[i], bears) else: addEdge(u[i], v[i], int(w[i] / mid)) return (Dinic() >= bears) n,m,bears = map(int, input().split()) #print(n, m, bears, flush = True) INF = 0x3f3f3f3f src = 0 des = n-1 lo = 0.0 hi = 0.0 u = [0 for i in range(m)] v = [0 for i in range(m)] w = [0 for i in range(m)] for i in range(m): u[i],v[i],w[i] = map(int, input().split()) #print(u[i], v[i], w[i], flush = True) u[i] -= 1 v[i] -= 1 hi = max(hi, w[i]) E = [[] for i in range(n)] lvl = [0 for i in range(n)] for i in range(100): mid = (lo + hi) / 2 #print('mid = {:.3f}'.format(mid), flush = True) if (check(mid)): lo = mid else: hi = mid print('{:.10f}'.format(mid * bears))
1458376500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["8\n0\n500\n2128012501878\n899999999999999999"]
50738d19041f2e97e2e448eff3feed84
null
You are given a positive integer $$$n$$$. In one move, you can increase $$$n$$$ by one (i.e. make $$$n := n + 1$$$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^{18}$$$; $$$1 \le s \le 162$$$).
standard output
standard input
Python 3
Python
1,500
train_005.jsonl
db1243f680b2a769c0b2379280066c8f
256 megabytes
["5\n2 1\n1 1\n500 4\n217871987498122 10\n100000000000000001 1"]
PASSED
for _ in range(int(input())): d,s=input().split() n=[int(i) for i in d] s=int(s) if sum(n)<=s: print(0) else: c=0 t=len(n) for i in range(len(n)): if c+n[i]<s: c+=n[i] else: break f=d[i:] t=t-i g=10**t-int(f) print(g)
1599230100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["5 2 \n8 2 1 3 \n9 3 8 \n100 50 25 75 64 \n42 \n128 96 80 88 52 7 \n17 2 4 8 16"]
bdd1974e46f99eff3d03ed4174158dd9
NoteIn the first test case of the example, there are only two possible permutations $$$b$$$  — $$$[2, 5]$$$ and $$$[5, 2]$$$: for the first one $$$c=[2, 1]$$$, for the second one $$$c=[5, 1]$$$.In the third test case of the example, number $$$9$$$ should be the first in $$$b$$$, and $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, so the second number of $$$b$$$ should be $$$3$$$.In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation $$$b$$$.
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. Using each of them exactly at once, you're to make such sequence $$$b_1, b_2, \dots, b_n$$$ that sequence $$$c_1, c_2, \dots, c_n$$$ is lexicographically maximal, where $$$c_i=GCD(b_1,\dots,b_i)$$$ - the greatest common divisor of the first $$$i$$$ elements of $$$b$$$. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.
For each test case output the answer in a single line  — the desired sequence $$$b$$$. If there are multiple answers, print any.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$)  — the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\dots,a_n$$$ ($$$1 \le a_i \le 10^3$$$)  — the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.
standard output
standard input
PyPy 3
Python
1,300
train_015.jsonl
ec7dd9492b6309e80129e40cc2248f55
256 megabytes
["7\n2\n2 5\n4\n1 8 2 3\n3\n3 8 9\n5\n64 25 75 100 50\n1\n42\n6\n96 128 88 80 52 7\n5\n2 4 8 16 17"]
PASSED
import math def get_int(): return int(input()) def get_int_list(): return list(map(int, input().split())) def get_char_list(): return list(input()) def gcd(x, y): if x < y: return gcd(y, x) z = x % y if z == 0: return y else: return gcd(y, z) cases = get_int() for _ in range(cases): n = get_int() ints = get_int_list() v = max(ints) result = [v] visited = set() visited.add(ints.index(v)) while len(visited) < n: md = 0 t = None for i, d in enumerate(ints): if i in visited: continue cd = gcd(v, d) if cd > md: md = cd t = i v = md result.append(ints[t]) visited.add(t) print(*result)
1599575700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["YES\nYES\nNO\nYES"]
a213bc75245657907c0ae28b067985f2
NoteThe queries in the example are following: substrings "a" and "a" are isomorphic: f(a) = a; substrings "ab" and "ca" are isomorphic: f(a) = c, f(b) = a; substrings "bac" and "aba" are not isomorphic since f(b) and f(c) must be equal to a at same time; substrings "bac" and "cab" are isomorphic: f(b) = c, f(a) = a, f(c) = b.
You are given a string s of length n consisting of lowercase English letters.For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S and T for which f(si) = ti. Formally: f(si) = ti for any index i, for any character there is exactly one character that f(x) = y, for any character there is exactly one character that f(x) = y. For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best".You have to handle m queries characterized by three integers x, y, len (1 ≤ x, y ≤ n - len + 1). For each query check if two substrings s[x... x + len - 1] and s[y... y + len - 1] are isomorphic.
For each query in a separate line print "YES" if substrings s[xi... xi + leni - 1] and s[yi... yi + leni - 1] are isomorphic and "NO" otherwise.
The first line contains two space-separated integers n and m (1 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105) — the length of the string s and the number of queries. The second line contains string s consisting of n lowercase English letters. The following m lines contain a single query on each line: xi, yi and leni (1 ≤ xi, yi ≤ n, 1 ≤ leni ≤ n - max(xi, yi) + 1) — the description of the pair of the substrings to check.
standard output
standard input
Python 3
Python
2,300
train_075.jsonl
8505e2d022784e6519f8fd2c4442ad77
256 megabytes
["7 4\nabacaba\n1 1 1\n1 4 2\n2 1 3\n2 4 3"]
PASSED
def getIntList(): return list(map(int, input().split())); def getTransIntList(n): first=getIntList(); m=len(first); result=[[0]*n for _ in range(m)]; for i in range(m): result[i][0]=first[i]; for j in range(1, n): curr=getIntList(); for i in range(m): result[i][j]=curr[i]; return result; n, m = getIntList() s=input(); orda=ord('a'); a=[ord(s[i])-orda for i in range(n)]; countSame=[1]*n; upLim=0; for lowLim in range(n): if lowLim<upLim: continue; for upLim in range(lowLim+1, n): if a[upLim]!=a[lowLim]: break; else: upLim+=1; for i in range(lowLim, upLim): countSame[i]=upLim-i; def test(x, y, l): map1=[0]*27; map2=[0]*27; count=0; lowLim=min(countSame[x], countSame[y])-1; for i in range(lowLim, l): x1=map1[a[x+i]]; x2=map2[a[y+i]]; if x1!=x2: return 'NO'; if x1==0: count+=1; map1[a[x+i]]=count; map2[a[y+i]]=count; return 'YES'; results=[]; for _ in range(m): x, y, l=getIntList(); results.append(test(x-1, y-1, l)); print('\n'.join(results));
1526913900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["10100\n011\n10100101"]
9683d5960247359b6b9066e96897d6f9
NoteIn the first test case, we have the following: $$$s_1 = s_2 + s_2$$$, since $$$\texttt{abab} = \texttt{ab} + \texttt{ab}$$$. Remember that $$$j$$$ can be equal to $$$k$$$. $$$s_2$$$ is not the concatenation of any two strings in the list. $$$s_3 = s_2 + s_5$$$, since $$$\texttt{abc} = \texttt{ab} + \texttt{c}$$$. $$$s_4$$$ is not the concatenation of any two strings in the list. $$$s_5$$$ is not the concatenation of any two strings in the list. Since only $$$s_1$$$ and $$$s_3$$$ satisfy the conditions, only the first and third bits in the answer should be $$$\texttt{1}$$$, so the answer is $$$\texttt{10100}$$$.
You are given $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$ of length at most $$$\mathbf{8}$$$. For each string $$$s_i$$$, determine if there exist two strings $$$s_j$$$ and $$$s_k$$$ such that $$$s_i = s_j + s_k$$$. That is, $$$s_i$$$ is the concatenation of $$$s_j$$$ and $$$s_k$$$. Note that $$$j$$$ can be equal to $$$k$$$.Recall that the concatenation of strings $$$s$$$ and $$$t$$$ is $$$s + t = s_1 s_2 \dots s_p t_1 t_2 \dots t_q$$$, where $$$p$$$ and $$$q$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. For example, concatenation of "code" and "forces" is "codeforces".
For each test case, output a binary string of length $$$n$$$. The $$$i$$$-th bit should be $$$\texttt{1}$$$ if there exist two strings $$$s_j$$$ and $$$s_k$$$ where $$$s_i = s_j + s_k$$$, and $$$\texttt{0}$$$ otherwise. Note that $$$j$$$ can be equal to $$$k$$$.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of strings. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains non-empty string $$$s_i$$$ of length at most $$$\mathbf{8}$$$, consisting of lowercase English letters. Among the given $$$n$$$ strings, there may be equal (duplicates). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,100
train_086.jsonl
31e0c17a56cfd42027cfd11450e4b881
256 megabytes
["3\n\n5\n\nabab\n\nab\n\nabc\n\nabacb\n\nc\n\n3\n\nx\n\nxx\n\nxxx\n\n8\n\ncodeforc\n\nes\n\ncodes\n\ncod\n\nforc\n\nforces\n\ne\n\ncode"]
PASSED
#import io, os #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t=int(input()) for _ in range(t): n=int(input()) words=[] prefs={} suffs={} for i in range(n): word=input() words.append(word) if not word in prefs: prefs.update({word:1}) else: prefs.update({word:prefs[word]+1}) if not word in suffs: suffs.update({word:1}) else: suffs.update({word:suffs[word]+1}) bina="" for i in words:# flag=False for j in range(len(i)-1): a=i[:(j+1)] b=i[j+1:] if a in prefs and b in suffs: flag=True if flag: bina+="1" else: bina+="0" print(bina)
1657636500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["10", "180 10"]
87c3a8a0d49288d0f6242fe2ac69a641
null
You wrote down all integers from $$$0$$$ to $$$10^n - 1$$$, padding them with leading zeroes so their lengths are exactly $$$n$$$. For example, if $$$n = 3$$$ then you wrote out 000, 001, ..., 998, 999.A block in an integer $$$x$$$ is a consecutive segment of equal digits that cannot be extended to the left or to the right.For example, in the integer $$$00027734000$$$ there are three blocks of length $$$1$$$, one block of length $$$2$$$ and two blocks of length $$$3$$$.For all integers $$$i$$$ from $$$1$$$ to $$$n$$$ count the number of blocks of length $$$i$$$ among the written down integers.Since these integers may be too large, print them modulo $$$998244353$$$.
In the only line print $$$n$$$ integers. The $$$i$$$-th integer is equal to the number of blocks of length $$$i$$$. Since these integers may be too large, print them modulo $$$998244353$$$.
The only line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$).
standard output
standard input
PyPy 3
Python
1,800
train_007.jsonl
62d191e3d38ce5676f43b46a4709c270
256 megabytes
["1", "2"]
PASSED
# | # _` | __ \ _` | __| _ \ __ \ _` | _` | # ( | | | ( | ( ( | | | ( | ( | # \__,_| _| _| \__,_| \___| \___/ _| _| \__,_| \__,_| import sys def read_line(): return sys.stdin.readline()[:-1] def read_int(): return int(sys.stdin.readline()) def read_int_line(): return [int(v) for v in sys.stdin.readline().split()] def power(x, y, p) : res = 1 # Initialize result # Update x if it is more # than or equal to p x = x % p while (y > 0) : # If y is odd, multiply # x with result if ((y & 1) == 1) : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res n = read_int() d = [0]*n p = 998244353 d[n-1] = 10 if n>1: d[n-2] = 180 for i in range(n-3,-1,-1): a1 = ((10*(n-i)*9*9)%p*power(10,n-i-3,p))%p a2 = (2*10*9*power(10,n-i-3,p))%p d[i] = (a1+a2)%p print(*d)
1584974100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n5000 9\n1\n7 \n4\n800 70 6 9000 \n1\n10000 \n1\n10"]
cd2519f4a7888b2c292f05c64a9db13a
null
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \le n \le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.
Print $$$t$$$ answers to the test cases. Each answer must begin with an integer $$$k$$$ — the minimum number of summands. Next, $$$k$$$ terms must follow, each of which is a round number, and their sum is $$$n$$$. The terms can be printed in any order. If there are several answers, print any of them.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing an integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
standard output
standard input
PyPy 3
Python
800
train_000.jsonl
52a2313fac7f87cb6696ab7b8e4dc447
256 megabytes
["5\n5009\n7\n9876\n10000\n10"]
PASSED
t = int(input()) for i in range(t): canPrintLength = True summends = [] num = int(input()) if num in range(1,11): print(1) print(num) else: a = 10 g = str(num) length = len(g) while num!=0: rem = num%a if rem !=0: summends.append(rem) a*=10 num-=rem else: a*=10 pass if canPrintLength==True: print(str(len(summends))) print(*summends)
1590154500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5\n1 2\n5 3\n4 5\n1 5\n1 3", "0"]
3b885c926076382f778a27a3c1f49d91
NoteThe following animation showcases the first sample test case. The black numbers represent the indices of the points, while the boxed orange numbers represent their labels. In the second test case, all labels are already in their correct positions, so no operations are necessary.
Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem!You are given $$$n$$$ points on the plane, no three of which are collinear. The $$$i$$$-th point initially has a label $$$a_i$$$, in such a way that the labels $$$a_1, a_2, \dots, a_n$$$ form a permutation of $$$1, 2, \dots, n$$$.You are allowed to modify the labels through the following operation: Choose two distinct integers $$$i$$$ and $$$j$$$ between $$$1$$$ and $$$n$$$. Swap the labels of points $$$i$$$ and $$$j$$$, and finally Draw the segment between points $$$i$$$ and $$$j$$$. A sequence of operations is valid if after applying all of the operations in the sequence in order, the $$$k$$$-th point ends up having the label $$$k$$$ for all $$$k$$$ between $$$1$$$ and $$$n$$$ inclusive, and the drawn segments don't intersect each other internally. Formally, if two of the segments intersect, then they must do so at a common endpoint of both segments.In particular, all drawn segments must be distinct.Find any valid sequence of operations, or say that none exist.
If it is impossible to perform a valid sequence of operations, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le \frac{n(n - 1)}{2}$$$)  — the number of operations to perform, followed by $$$k$$$ lines, each containing two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$, $$$i\neq j$$$)  — the indices of the points chosen for the operation. Note that you are not required to minimize or maximize the value of $$$k$$$. If there are multiple possible answers, you may print any of them.
The first line contains an integer $$$n$$$ ($$$3 \le n \le 2000$$$)  — the number of points. The $$$i$$$-th of the following $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ ($$$-10^6 \le x_i, y_i \le 10^6$$$, $$$1 \le a_i \le n$$$), representing that the $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$ and initially has label $$$a_i$$$. It is guaranteed that all points are distinct, no three points are collinear, and the labels $$$a_1, a_2, \dots, a_n$$$ form a permutation of $$$1, 2, \dots, n$$$.
standard output
standard input
Python 3
Python
3,000
train_087.jsonl
769343769fd52101ba06f019dab19e35
256 megabytes
["5\n-1 -2 2\n3 0 5\n1 3 4\n4 -3 3\n5 2 1", "3\n5 4 1\n0 0 2\n-3 -2 3"]
PASSED
import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() from math import atan2;from collections import deque def path(R): H=deque();H.append(R) while P[R]>=0: R=P[R];H.append(R) if len(H)>2:P[H.popleft()]=H[-1] return R def remove_middle(a,b,c): cross=(a[0]-b[0])*(c[1]-b[1])-(a[1]-b[1])*(c[0]-b[0]) dot=(a[0]-b[0])*(c[0]-b[0])+(a[1]-b[1])*(c[1]-b[1]) return cross<0 or cross==0 and dot<=0 def convex_hull(points): spoints=sorted(points);hull=[] for p in spoints+spoints[::-1]: while len(hull)>=2 and remove_middle(hull[-2],hull[-1],p):hull.pop() hull.append(p) hull.pop();return hull n=int(Z());p=[];p2=[];w=[-1]*n;labels=set() for i in range(n): x,y,a=map(int,Z().split());a-=1 if a!=i:p.append((x,y,i));p2.append((x,y));w[i]=a;labels.add(a) if not p:print(0);quit() q=[];bx,by,bi=p[-1];L=len(p)-1 for i in range(L):x,y,l=p[i];q.append((atan2(y-by,x-bx),(x,y),l)) q.sort();cycles=[-1]*n;c=0 while labels: v=labels.pop();cycles[v]=c;cur=w[v] while cur!=v:labels.remove(cur);cycles[cur]=c;cur=w[cur] c+=1 K=[-1]*c;P=[-1]*c;S=[1]*c;R=0;moves=[];ch=convex_hull(p2);adj1=adj2=None for i in range(len(ch)): x,y=ch[i] if x==bx and y==by:adj1=ch[(i+1)%len(ch)];adj2=ch[i-1];break for i in range(L): if (q[i][1]==adj1 and q[i-1][1]==adj2)or(q[i][1]==adj2 and q[i-1][1]==adj1):continue l1,l2=q[i][2],q[i-1][2];a,b=cycles[l1],cycles[l2] if a!=b: if K[a]>=0: if K[b]>=0: va,vb=path(K[a]),path(K[b]) if va!=vb: moves.append((l1,l2));sa,sb=S[va],S[vb] if sa>sb:P[vb]=va else: P[va]=vb if sa==sb:S[vb]+=1 else:pass else:K[b]=path(K[a]);moves.append((l1,l2)) else: moves.append((l1,l2)) if K[b]>=0:K[a]=path(K[b]) else:K[a]=R;K[b]=R;R+=1 for a,b in moves:w[a],w[b]=w[b],w[a] while w[bi]!=bi:a=w[bi];b=w[a];moves.append((a,bi));w[bi],w[a]=b,a print(len(moves));print('\n'.join(f'{a+1} {b+1}'for a,b in moves))
1618583700
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["-1\n1 2", "1 2\n1 3\n2 4\n2 5\n3 6\n4 7\n4 8\n1 2\n1 3\n2 4\n2 5\n2 6\n3 7\n6 8"]
b1959af75dfdf8281e70ae66375caa14
NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed  - 1 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this: In the second tree, the algorithm will find an answer with 3 nodes which is correct:
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm: Root the tree at node 1. Count the number of nodes at an even depth. Let it be evenCnt. Count the number of nodes at an odd depth. Let it be oddCnt. The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.
The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them.
The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.
standard output
standard input
Python 3
Python
1,500
train_005.jsonl
618613b04fb35fe6c9c94258bfc4974c
256 megabytes
["2", "8"]
PASSED
def wrong(x): if n < 6: print(-1) else: print("1 2") print("2 3") print("2 4") print("4 5") print("4 6") for i in range(7, x + 1): print("4", i) def true(x): for i in range(x-1): print(i+1,i+2) n = int(input()) wrong(n) true(n)
1522771500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]