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
1 second
["Yes\n1 1", "No", "Yes\n1 2 3 1 5"]
9abcb5481648a6485a818946f8f94d1d
NoteBelow one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals $$$3 + 1 + 1 = 5$$$, and the branching coefficient equals $$$2$$$. Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals $$$6 + 3 + 2 + 1 + 2 + 1 = 15$$$, and the branching coefficient equals $$$2$$$.
Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree!Misha would like to construct a rooted tree with $$$n$$$ vertices, indexed from 1 to $$$n$$$, where the root has index 1. Every other vertex has a parent $$$p_i$$$, and $$$i$$$ is called a child of vertex $$$p_i$$$. Vertex $$$u$$$ belongs to the subtree of vertex $$$v$$$ iff $$$v$$$ is reachable from $$$u$$$ while iterating over the parents ($$$u$$$, $$$p_{u}$$$, $$$p_{p_{u}}$$$, ...). Clearly, $$$v$$$ belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex $$$1$$$.Below there is a tree with $$$6$$$ vertices. The subtree of vertex $$$2$$$ contains vertices $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$. Hence the size of its subtree is $$$4$$$. The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals $$$2$$$. Your task is to construct a tree with $$$n$$$ vertices such that the sum of the subtree sizes for all vertices equals $$$s$$$, and the branching coefficient is minimum possible.
If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers $$$p_2$$$, $$$p_3$$$, ..., $$$p_n$$$, where $$$p_i$$$ denotes the parent of vertex $$$i$$$.
The only input line contains two integers $$$n$$$ and $$$s$$$ — the number of vertices in the tree and the desired sum of the subtree sizes ($$$2 \le n \le 10^5$$$; $$$1 \le s \le 10^{10}$$$).
standard output
standard input
Python 3
Python
2,400
train_054.jsonl
f635dcc097455b2ce5d5d22d62b32b3e
256 megabytes
["3 5", "4 42", "6 15"]
PASSED
import math def f(n,k): if k==1: return (n*(n+1))//2 a=math.floor(math.log(n,k)) b=sum(k**i for i in range(a+1)) c=sum((i+1)*k**i for i in range(a+1)) if n<b: return c-(b-n)*(a+1) else: return c+(n-b)*(a+2) n,s=map(int,input().split()) if s==(n*(n+1))//2: print("Yes") a=[str(i+1) for i in range(n-1)] print(" ".join(a)) elif s>(n*(n+1))//2: print("No") elif s<2*n-1: print("No") else: mini=1 maxi=n-1 curr=1 while True: a,b=f(n,curr),f(n,curr+1) if b>s: mini=curr+1 curr=math.ceil((curr+maxi)/2) elif a<=s: maxi=curr-1 curr=(curr+mini)//2 else: opt=curr+1 break depths=[0,1]+[0]*(n-1) ins=1 ind=2 while True: a=min(opt**(ind-1),n-ins) depths[ind]=a ind+=1 ins+=a if ins==n: break left=s-b far=ind-1 bulk=ind-1 if depths[bulk]==1: bulk-=1 while left>0: if far+1-bulk<=left: far+=1 left-=far-bulk depths[far]+=1 depths[bulk]-=1 if depths[bulk]==1: bulk-=1 else: depths[bulk]-=1 depths[bulk+left]+=1 left=0 verts=[None]*far sumi=0 for i in range(far): verts[i]=list(range(sumi+1,sumi+1+depths[i+1])) sumi+=depths[i+1] out="" for i in range(1,far): for j in range(len(verts[i])): out+=str(verts[i-1][j//opt])+" " print("Yes") print(out)
1546706100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3 seconds
["6", "2"]
6da720d47a627df3afb876253b1cbe58
null
"Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills.And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.The prototype is ready, you now need to urgently carry out its experiments in practice. You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of n vertices, the i-th vertex contains ki beavers. "Beavermuncher-0xFF" works by the following principle: being at some vertex u, it can go to the vertex v, if they are connected by an edge, and eat exactly one beaver located at the vertex v. It is impossible to move to the vertex v if there are no beavers left in v. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops.Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled.The root of the tree is located at the vertex s. This means that the "Beavermuncher-0xFF" begins its mission at the vertex s and it must return there at the end of experiment, because no one is going to take it down from a high place. Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex.
Print the maximum number of beavers munched by the "Beavermuncher-0xFF". Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
The first line contains integer n — the number of vertices in the tree (1 ≤ n ≤ 105). The second line contains n integers ki (1 ≤ ki ≤ 105) — amounts of beavers on corresponding vertices. Following n - 1 lines describe the tree. Each line contains two integers separated by space. These integers represent two vertices connected by an edge. Vertices are numbered from 1 to n. The last line contains integer s — the number of the starting vertex (1 ≤ s ≤ n).
standard output
standard input
Python 2
Python
2,100
train_066.jsonl
a7266edb99e50f2ef6a576ff13b8c7a5
256 megabytes
["5\n1 3 1 3 2\n2 5\n3 4\n4 5\n1 5\n4", "3\n2 1 1\n3 2\n1 2\n3"]
PASSED
n = input()+1 k = [0]+map(int,raw_input().split()) d = [[] for _ in xrange(n)] for _ in xrange(n-2): a,b = [int(x) for x in raw_input().split()] d[a].append(b) d[b].append(a) s = input() q = [0] d[0] = [s] v = [True]+[False]*n for x in q: for u in d[x]: if not v[u]: v[u]=True q.append(u) r = [[] for _ in xrange(n)] v = [True]*n f = [0]*n for i in xrange(n): if i!=s: k[i]-=1 for x in reversed(q): v[x]=False for u in d[x]: if v[u]: continue rx = sorted(r[u],reverse=True)[:k[u]] res = sum(rx)+2*len(rx) k[u]-=len(rx) b = min(k[u],f[u]) k[u]-=b res+=b*2 f[x]+=k[u] r[x].append(res) print r[0][0]
1303226100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["26\n24\n134"]
7100fa11adfa0c1f5d33f9e3a1c3f352
NoteIn the first test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+5+1+1+1+1+3+1+5+1+2+3=26$$$. It can be shown that we cannot get a smaller perimeter.Consider the following invalid arrangement.Even though the perimeter of the shape above is $$$24$$$, it does not satisfy all conditions of the problem. The bottom edge of the $$$1 \times 1$$$ slice of cheese is not a segment of the x-axis.In the second test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+2+2+3+2+3+2+2+2+4=24$$$. It can be shown that we cannot get a smaller perimeter.
Pak Chanek has $$$n$$$ two-dimensional slices of cheese. The $$$i$$$-th slice of cheese can be represented as a rectangle of dimensions $$$a_i \times b_i$$$. We want to arrange them on the two-dimensional plane such that: Each edge of each cheese is parallel to either the x-axis or the y-axis. The bottom edge of each cheese is a segment of the x-axis. No two slices of cheese overlap, but their sides can touch. They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape.
For each test case, output a line containing an integer representing the minimum possible perimeter of the constructed shape.
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — 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 2 \cdot 10^5$$$) — the number of slices of cheese Pak Chanek has. The $$$i$$$-th of the next $$$n$$$ lines of each test case contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i,b_i \leq 10^9$$$) — the dimensions of the $$$i$$$-th slice of cheese. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
800
train_096.jsonl
eb88a3bab2f463ab873d441b1ba730fa
256 megabytes
["3\n\n4\n\n4 1\n\n4 5\n\n1 1\n\n2 3\n\n3\n\n2 4\n\n2 6\n\n2 3\n\n1\n\n2 65"]
PASSED
t = int(input()) while t > 0: t-=1 n = int(input()) # number of slices x = n slicesH = [] slicesW = [] totala = 0 totalb = 0 currw = 0 currh = 0 existingh = [] slicesH2 = [] slicesW2 = [] existingh2 = [] while x>0: x-=1 a,b = map(int, input().split()) h = 0 w = 0 h = max(a,b) w = min(a,b) slicesH.append(h) slicesW.append(w) d = {i:ix for ix, i in enumerate(slicesH)} slicesH = sorted(slicesH) slicesW = sorted(slicesW, key=lambda x: d.get(x, float('inf'))) slicesH.reverse() slicesW.reverse() #print(slicesH) #print(slicesW) prevh = 0 top = 0 bottom = 0 sides = 0 for x in range(len(slicesH)): top += slicesW[x]*2 hdiff = abs(slicesH[x]-prevh) sides+=hdiff prevh = slicesH[x] sides+= prevh print(top+bottom+sides)
1667034600
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["167", "582491518"]
f4a9abc1cdfcdc2c96982477f17a197b
NoteDescription of the first example: $$$f(1, 1) = 5 \cdot 1 = 5$$$; $$$f(1, 2) = 2 \cdot 1 + 5 \cdot 2 = 12$$$; $$$f(1, 3) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 = 25$$$; $$$f(1, 4) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 + 7 \cdot 4 = 53$$$; $$$f(2, 2) = 2 \cdot 1 = 2$$$; $$$f(2, 3) = 2 \cdot 1 + 4 \cdot 2 = 10$$$; $$$f(2, 4) = 2 \cdot 1 + 4 \cdot 2 + 7 \cdot 3 = 31$$$; $$$f(3, 3) = 4 \cdot 1 = 4$$$; $$$f(3, 4) = 4 \cdot 1 + 7 \cdot 2 = 18$$$; $$$f(4, 4) = 7 \cdot 1 = 7$$$;
You are given an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are pairwise distinct.Let's define function $$$f(l, r)$$$ as follows: let's define array $$$b_1, b_2, \dots, b_{r - l + 1}$$$, where $$$b_i = a_{l - 1 + i}$$$; sort array $$$b$$$ in increasing order; result of the function $$$f(l, r)$$$ is $$$\sum\limits_{i = 1}^{r - l + 1}{b_i \cdot i}$$$. Calculate $$$\left(\sum\limits_{1 \le l \le r \le n}{f(l, r)}\right) \mod (10^9+7)$$$, i.e. total sum of $$$f$$$ for all subsegments of $$$a$$$ modulo $$$10^9+7$$$.
Print one integer — the total sum of $$$f$$$ for all subsegments of $$$a$$$ modulo $$$10^9+7$$$
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$) — array $$$a$$$.
standard output
standard input
PyPy 3
Python
2,300
train_032.jsonl
e41eb7e15c0c70495a44339e6c917ed3
256 megabytes
["4\n5 2 4 7", "3\n123456789 214365879 987654321"]
PASSED
import sys MOD = (int)(1e9+7) def add(a, b): a += b if a >= MOD: a -= MOD return a def mul(a, b): return (a * b) % MOD class fenwickTree: def __init__(self, max_val): self.max_val = max_val + 5 self.tree = [0] * self.max_val def update(self, idx, value): idx += 1 while idx < self.max_val: self.tree[idx] = add(self.tree[idx], value) idx += (idx & (-idx)) def read(self, idx): idx += 1 res = 0 while idx > 0: res = add(res, self.tree[idx]) idx -= (idx & (-idx)) return res inp = [int(x) for x in sys.stdin.read().split()] n = inp[0] a = [] for i in range(1, n + 1): a.append(inp[i]) sorted_array = sorted(a) dict = {} for i in range(n): dict[sorted_array[i]] = i factor = [0] * n for i in range(0, n): factor[i] = mul(i + 1, n - i) left_tree = fenwickTree(n) for i in range(0, n): element_idx = dict[a[i]] factor[i] = add(factor[i], mul(n - i, left_tree.read(element_idx))) left_tree.update(element_idx, i + 1) right_tree = fenwickTree(n) for i in range(n - 1, -1, -1): element_idx = dict[a[i]] factor[i] = add(factor[i], mul(i + 1, right_tree.read(element_idx))) right_tree.update(element_idx, n - i) ans = 0 for i in range(n): ans = add(ans, mul(a[i], factor[i])) print(ans)
1557930900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 1 1", "77 77 79"]
91d5147fb602298e08cbdd9f86d833f8
null
Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.
Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.
A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.
standard output
standard input
PyPy 3
Python
800
train_006.jsonl
49c570e87d093a34dd80dc8f29de7209
256 megabytes
["3", "233"]
PASSED
n = int(input()) if n % 2 != 0: n = n - 1 a = n // 2 b = n - a while a % 3 == 0 or b % 3 == 0: a = a + 1 b = b - 1 print(1 , a , b) else: n = n - 2 a = n // 2 b = n - a while a % 3 == 0 or b % 3 == 0: a = a + 1 b = b - 1 print(2 , a , b)
1537540500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2.5 seconds
["2 1 0 1\n1 2 1 0\n0 1 2 1\n1 0 1 2", "1 0 0 0 0 0 0 0\n0 2 0 0 0 0 2 0\n0 0 1 0 1 1 0 0\n0 0 0 2 0 0 0 2\n0 0 1 0 1 1 0 0\n0 0 1 0 1 1 0 0\n0 2 0 0 0 0 2 0\n0 0 0 2 0 0 0 2"]
23467790e295f49feaaf1fc64beafa86
NoteThe following picture describes the first example.The tree with red edges is a BFS tree rooted at both $$$1$$$ and $$$2$$$.Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way.
We define a spanning tree of a graph to be a BFS tree rooted at vertex $$$s$$$ if and only if for every node $$$t$$$ the shortest distance between $$$s$$$ and $$$t$$$ in the graph is equal to the shortest distance between $$$s$$$ and $$$t$$$ in the spanning tree. Given a graph, we define $$$f(x,y)$$$ to be the number of spanning trees of that graph that are BFS trees rooted at vertices $$$x$$$ and $$$y$$$ at the same time.You are given an undirected connected graph with $$$n$$$ vertices and $$$m$$$ edges. Calculate $$$f(i,j)$$$ for all $$$i$$$, $$$j$$$ by modulo $$$998\,244\,353$$$.
Print $$$n$$$ lines, each consisting of $$$n$$$ integers. The integer printed in the row $$$i$$$ and the column $$$j$$$ should be $$$f(i,j) \bmod 998\,244\,353$$$.
The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 400$$$, $$$0 \le m \le 600$$$) — the number of vertices and the number of edges in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i &lt; b_i$$$), representing an edge connecting $$$a_i$$$ and $$$b_i$$$. It is guaranteed that all edges are distinct and the graph is connected.
standard output
standard input
PyPy 3
Python
2,600
train_085.jsonl
89a5265b7f65c09bcc7a586db0959607
512 megabytes
["4 4\n1 2\n2 3\n3 4\n1 4", "8 9\n1 2\n1 3\n1 4\n2 7\n3 5\n3 6\n4 8\n2 3\n3 4"]
PASSED
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) MOD = 998244353 adjList = [] dist = [] ans = [] for _ in range(n): adjList.append([]) for _ in range(m): a,b = map(int,input().split()) adjList[a - 1].append(b - 1) adjList[b - 1].append(a - 1) for i in range(n): curDist = [-1] * n curDist[i] = 0 bfsQueue = [i] bfsIndex = 0 while len(bfsQueue) > bfsIndex: c = bfsQueue[bfsIndex] bfsIndex += 1 for elem in adjList[c]: if curDist[elem] == -1: curDist[elem] = curDist[c] + 1 bfsQueue.append(elem) dist.append(curDist) for _ in range(n): ans.append([0] * n) for i in range(n): for j in range(i, n): # Find shortest path between i and j isCovered = [False] * n isCovered[i] = True isCovered[j] = True jCpy = j flag = True while jCpy != i: cnt = 0 cntIndex = -1 for elem in adjList[jCpy]: if dist[i][elem] == dist[i][jCpy] - 1: cnt += 1 cntIndex = elem if cnt >= 2: flag = False break else: isCovered[cntIndex] = True jCpy = cntIndex if not flag: ans[i][j] = 0 ans[j][i] = 0 else: curAns = 1 for k in range(n): if isCovered[k]: continue cnt = 0 for elem in adjList[k]: if dist[i][elem] == dist[i][k] - 1 and dist[j][elem] == dist[j][k] - 1: cnt += 1 curAns *= cnt curAns %= MOD ans[i][j] = curAns ans[j][i] = curAns for elem in ans: print(" ".join(map(str,elem))) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
1615377900
[ "math", "trees", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 1 ]
2 seconds
["none\nany\nat least one\nat least one\nany", "any\nany\nnone", "at least one\nat least one\nat least one"]
be83ef61283f104dcb00612ae11f2e93
NoteIn the second sample the MST is unique for the given graph: it contains two first edges.In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST.
You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST.
Print m lines — the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input.
The first line contains two integers n and m (2 ≤ n ≤ 105, ) — the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers — the description of the graph's edges as "ai bi wi" (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106, ai ≠ bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges.
standard output
standard input
Python 3
Python
2,300
train_073.jsonl
0ba0bade310d53c2e2bcf3caf30ccaee
256 megabytes
["4 5\n1 2 101\n1 3 100\n2 3 2\n2 4 2\n3 4 1", "3 3\n1 2 1\n2 3 1\n1 3 2", "3 3\n1 2 1\n2 3 1\n1 3 1"]
PASSED
import sys, threading from heapq import heappop, heappush #from mygraph import MyGraph from collections import defaultdict n_nodes, n_edges = map(int, input().split()) edges = list() results = defaultdict(lambda: 'any') highest = defaultdict(lambda: -1) to_check = defaultdict(list) graph = defaultdict(list) class UDFS: def __init__(self, n): self.n = n # index is the node self.parents = [i for i in range(n)] self.ranks = [0 for i in range(n)] def __str__(self): ''' Group -> Node ''' return '\n'.join(f'{e} -> {i}' for i, e in enumerate(self.parents)) def get_group(self, a): if a == self.parents[a]: return a # Side effect for balancing the tree self.parents[a] = self.get_group(self.parents[a]) return self.parents[a] def is_parent(self, n): return n == self.get_group(n) def is_same_group(self, a, b): return self.get_group(a) == self.get_group(b) def join(self, a, b): parent_a = self.get_group(a) parent_b = self.get_group(b) if self.ranks[parent_a] > self.ranks[parent_b]: self.parents[parent_b] = parent_a else: self.parents[parent_a] = parent_b self.ranks[parent_b] += int( self.ranks[parent_a] == self.ranks[parent_b] ) def count(self): ''' Returns number of groups ''' count = 0 for n in range(self.n): count += self.is_parent(n) return count #def get_graph(nodes, label): # graph = MyGraph(graph_type='graph', size='20,11.25!', ratio='fill',label=label, fontsize=40) # # for v in range(1,nodes+1): # graph.add_nodes(v) # # return graph # #def make_original_graph(nodes, edges): # original_graph = get_graph(nodes, "Grafo Original") # # for r in range(edges): # a, b, w = map(int, input('\tInsira dois nós e o peso da aresta que existe entre eles: ').split()) # original_graph.link(a, b, str(w)) # # img_name = "original_graph" # # original_graph.save_img(img_name) # # print(f"O grafo original foi salvo em {img_name}.png!") # #def make_edges_in_mst_graph(nodes, edges): # edges_graph = get_graph(nodes, "Arestas em MSTs") # # for r in range(edges): # edges_graph.link(a, b, str(w)) # # img_name = "edges_in_mst" # # edges_graph.save_img(img_name) # # print(f"O grafo com a ocorrências das arestas em MSTs foi salvo em {img_name}.png!") def dfs(a, depth, p): global edges global results global highest global graph if highest[a] != -1: return highest[a]; minimum = depth highest[a] = depth for (w, a, b, i) in graph[a]: ##print('@', w, a, b, i, depth) if i == p: continue nextt = dfs(b, depth + 1, i) if nextt <= depth: results[i] = 'at least one' else: results[i] = 'any' minimum = min(minimum, nextt) highest[a] = minimum return highest[a] def main(): global edges global results global highest global graph for i in range(n_edges): a, b, w = map(int, input().split()) edges.append((w, a-1, b-1, i)) edges = sorted(edges, key=lambda x: x[0]) dsu = UDFS(n_nodes) i = 0 while i < n_edges: counter = 0 j = i while j < n_edges and edges[j][0] == edges[i][0]: if dsu.get_group(edges[j][1]) == dsu.get_group(edges[j][2]): results[edges[j][3]] = 'none' else: to_check[counter] = edges[j] counter += 1 j += 1 for k in range(counter): w, a, b, i = to_check[k] ra = dsu.get_group(a) rb = dsu.get_group(b) graph[ra].append((w, ra, rb, i)) graph[rb].append((w, rb, ra, i)) for k in range(counter): #print('To check:', to_check[k][:-1], k) dfs(to_check[k][1], 0, -1) for k in range(counter): w, a, b, i = to_check[k] ra = dsu.get_group(a) rb = dsu.get_group(b) dsu.join(ra, rb) graph[ra] = list() graph[rb] = list() highest[ra] = -1 highest[rb] = -1 counter = 0 i = j for i in range(n_edges): print(results[i]) if __name__ == "__main__": sys.setrecursionlimit(2**32//2-1) threading.stack_size(1 << 27) thread = threading.Thread(target=main) thread.start() thread.join()
1331046000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1\n3", "2\n3 4", "0"]
f046fc902b22fdbc3b1ec9cb4f411179
NoteIn the first test, $$$p=2$$$. If $$$x \le 2$$$, there are no valid permutations for Yuzu. So $$$f(x)=0$$$ for all $$$x \le 2$$$. The number $$$0$$$ is divisible by $$$2$$$, so all integers $$$x \leq 2$$$ are not good. If $$$x = 3$$$, $$$\{1,2,3\}$$$ is the only valid permutation for Yuzu. So $$$f(3)=1$$$, so the number $$$3$$$ is good. If $$$x = 4$$$, $$$\{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\}$$$ are all valid permutations for Yuzu. So $$$f(4)=4$$$, so the number $$$4$$$ is not good. If $$$x \ge 5$$$, all $$$6$$$ permutations are valid for Yuzu. So $$$f(x)=6$$$ for all $$$x \ge 5$$$, so all integers $$$x \ge 5$$$ are not good. So, the only good number is $$$3$$$.In the third test, for all positive integers $$$x$$$ the value $$$f(x)$$$ is divisible by $$$p = 3$$$.
This is the easy version of the problem. The difference between versions is the constraints on $$$n$$$ and $$$a_i$$$. You can make hacks only if all versions of the problem are solved.First, Aoi came up with the following idea for the competitive programming problem:Yuzu is a girl who collecting candies. Originally, she has $$$x$$$ candies. There are also $$$n$$$ enemies numbered with integers from $$$1$$$ to $$$n$$$. Enemy $$$i$$$ has $$$a_i$$$ candies.Yuzu is going to determine a permutation $$$P$$$. A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$\{2,3,1,5,4\}$$$ is a permutation, but $$$\{1,2,2\}$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$\{1,3,4\}$$$ is also not a permutation (because $$$n=3$$$ but there is the number $$$4$$$ in the array).After that, she will do $$$n$$$ duels with the enemies with the following rules: If Yuzu has equal or more number of candies than enemy $$$P_i$$$, she wins the duel and gets $$$1$$$ candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations $$$P$$$ exist?This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:Let's define $$$f(x)$$$ as the number of valid permutations for the integer $$$x$$$.You are given $$$n$$$, $$$a$$$ and a prime number $$$p \le n$$$. Let's call a positive integer $$$x$$$ good, if the value $$$f(x)$$$ is not divisible by $$$p$$$. Find all good integers $$$x$$$.Your task is to solve this problem made by Akari.
In the first line, print the number of good integers $$$x$$$. In the second line, output all good integers $$$x$$$ in the ascending order. It is guaranteed that the number of good integers $$$x$$$ does not exceed $$$10^5$$$.
The first line contains two integers $$$n$$$, $$$p$$$ $$$(2 \le p \le n \le 2000)$$$. It is guaranteed, that the number $$$p$$$ is prime (it has exactly two divisors $$$1$$$ and $$$p$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 2000)$$$.
standard output
standard input
PyPy 3
Python
1,900
train_001.jsonl
d5c42d3f633256749816436a710ad52a
256 megabytes
["3 2\n3 4 5", "4 3\n2 3 5 6", "4 3\n9 1 1 1"]
PASSED
def func(length, prime): nums = sorted(map(int, input().split())) mini = max(nums[0], nums[-1]-length+1) xs = list(range(mini, min(mini+length, nums[-1]+1))) L = len(xs) # candidates, 0~L-length idxs = [0] * length for i in range(L-1, -1, -1): if xs[i] == nums[-1]: idxs[-1] = length-i break for i in range(length-2, -1, -1): diff = nums[i+1]-nums[i] idxs[i] = min(length, idxs[i+1]+diff) for i in range(length): idxs[i] -= (length-1-i) from collections import defaultdict num2i = defaultdict(set) bad = [False] * (length+1) for i in range(prime, length+1, prime): bad[i] = True flag = False for i, n in enumerate(idxs): if n == i+1: if bad[n]: flag = True break else: num2i[n].add(i) res = [] incri = 0 for x in xs: if flag: break if not any((k+incri)%prime==0 for k in num2i): res.append(x) incri += 1 for k in list(num2i.keys()): v = num2i[k] if k+incri-1 in v: v.remove(k+incri-1) if (k+incri)%prime ==0: flag = True break if not v: num2i.pop(k) print(len(res)) print(" ".join(map(str, res)) if res else "") # cases = int(input()) for i in range(1): n, k = map(int, input().split()) func(n, k)
1593610500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["3\n4", "20", "-1"]
7589b30ec643278d8a83d74d43d9aebe
null
Daniel is organizing a football tournament. He has come up with the following tournament format: In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.
Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.
The first line contains a single integer n (1 ≤ n ≤ 1018), the number of games that should be played. 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.
standard output
standard input
Python 3
Python
1,800
train_009.jsonl
7462c70ad5102f5ef7cf9ccf5e2ab786
256 megabytes
["3", "25", "2"]
PASSED
def cc(res): l = 1 r = res while l<=r: mid = l+r >>1 if mid*mid==res: return mid elif mid*mid>res: r = mid-1 else: l = mid+1 return -1 def solve(a,b,c): if b*b-4*a*c<0: return -1 r = cc(b*b-4*a*c) if r*r!=b*b-4*a*c: return -1 r = -b+r if r%(2*a)!=0: return -1 return int(r/2/a) n = int(input()) tmp = [] for i in range(0,100): now = 1<<(i+1) ans = solve(1,now-3,-2*n) if ans!=-1 and ans%2==1: tmp.append( int(ans*now/2) ) tmp.sort() pre = -1 for i in tmp: if i!=pre: print(i) pre = i if pre ==-1: print(-1)
1373734800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0.0000000\n0\n2.0000\n0.00\n1"]
9f019c3898f27d687c5b3498586644e8
NoteIn the picture, the downtowns of the first three test cases are illustrated. Triangles are enumerated according to the indices of test cases they belong to. In the first two test cases, all points on the borders of the downtowns are safe, thus the answers are $$$0$$$.In the following picture unsafe points for the third test case are marked with black color: In the fourth test case, all points on the border of the downtown are safe.
Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle: its vertices have integer coordinates, the coordinates of vertices are non-negative, and its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line $$$y = 0$$$ walking along some straight line, without crossing the interior of the triangle. In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.
For each test case print a single number — the answer to the problem. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally let your answer be $$$a$$$, jury answer be $$$b$$$. Your answer will be considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$$$.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. Each test case contains three lines, each of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^9$$$) — coordinates of the vertices of the downtown's border.
standard output
standard input
Python 3
Python
800
train_092.jsonl
37265648ec77aa531ad8d59a5c98a7fc
256 megabytes
["5\n8 10\n10 4\n6 2\n4 6\n0 1\n4 2\n14 1\n11 2\n13 2\n0 0\n4 0\n2 4\n0 1\n1 1\n0 0"]
PASSED
n=int(input("")) k=0 ne=[] for i in range(n): d=0 a=input("") b=input("") c=input("") a=a.split() b=b.split() c=c.split() l=[a,b,c] if int(a[1])==int(b[1]) and int(c[1])<int(a[1]): d=d+int(a[0])-int(b[0]) if int(b[1])==int(c[1]) and int(a[1])<int(c[1]): d=d+int(b[0])-int(c[0]) if int(a[1])==int(c[1]) and int(b[1])<int(a[1]): d=d+int(a[0])-int(c[0]) ne.append((d**2)**(1/2)) for j in ne: print(j)
1645611000
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["4", "16", "0", "18716"]
47a8fd4c1f4e7b1d4fd15fbaf5f6fda8
null
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station. The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane. The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane. Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
standard output
standard input
Python 2
Python
2,000
train_059.jsonl
465864721312b41ec9b5ec83aeb0c216
256 megabytes
["3 6\n1 2 3", "5 5\n-7 -6 -3 -1 1", "1 369\n0", "11 2\n-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822"]
PASSED
n, m = map(int,raw_input().split()) C = map(int,raw_input().split()) res,l = 0, 0 while l < n: res = res + C[n - 1] - C[l] l,n = l + m, n - m print res*2
1399044600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3\n1\n0\n595458194\n200000000"]
116dd636a4f2547aef01a68f98c46ca2
NoteIn the first test case, the possible arrays $$$b$$$ are: $$$[4,2,1]$$$; $$$[4,2,3]$$$; $$$[4,2,5]$$$. In the second test case, the only array satisfying the demands is $$$[1,1]$$$.In the third test case, it can be proven no such array exists.
You are given two integers $$$n$$$ and $$$m$$$ and an array $$$a$$$ of $$$n$$$ integers. For each $$$1 \le i \le n$$$ it holds that $$$1 \le a_i \le m$$$.Your task is to count the number of different arrays $$$b$$$ of length $$$n$$$ such that: $$$1 \le b_i \le m$$$ for each $$$1 \le i \le n$$$, and $$$\gcd(b_1,b_2,b_3,...,b_i) = a_i$$$ for each $$$1 \le i \le n$$$. Here $$$\gcd(a_1,a_2,\dots,a_i)$$$ denotes the greatest common divisor (GCD) of integers $$$a_1,a_2,\ldots,a_i$$$.Since this number can be too large, print it modulo $$$998\,244\,353$$$.
For each test case, print a single integer — the number of different arrays satisfying the conditions above. Since this number can be large, print it modulo $$$998\,244\,353$$$.
Each test consist of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the length of the array $$$a$$$ and the maximum possible value of the element. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_101.jsonl
12adcb65337194fec096bfd9137e45bd
256 megabytes
["5\n\n3 5\n\n4 2 1\n\n2 1\n\n1 1\n\n5 50\n\n2 3 5 2 3\n\n4 1000000000\n\n60 30 1 1\n\n2 1000000000\n\n1000000000 2"]
PASSED
#from pyrival import * import math import sys import heapq input = lambda: sys.stdin.readline().rstrip("\r\n") mod = 998244353 # Count the number of numbers # up to m which are divisible # by given prime numbers def count(a, n, m): #print(a) #print(n, m) total = 0 # Run from i = 000..0 to i = 111..1 # or check all possible # subsets of the array for i in range(0, 1 << n): mult = 1 for j in range(n): if (i & (1 << j)): mult *= a[j] # Take the multiplication # of all the set bits # If the number of set bits # is odd, then add to the # number of multiples total += (-1)**(bin(i).count('1') & 1) * (m // mult) #print(f'subtracting out {m // mult}') return total def countRelPrime(n, m): #print(f'counting rel {n} {m}') facts = [] for div in range(2, math.ceil(n**0.5) + 2): if n % div == 0: facts += [div] while n % div == 0: n //= div if n != 1: facts += [n] return count(facts, len(facts), m) t = int(input()) for _ in range(t): cache = {} N, M = map(int, input().split()) A = list(map(int, input().split())) ways = 1 for pos in range(1, N): big, small = A[pos - 1 : pos + 1] if (big, small) not in cache: if math.gcd(big, small) < small: ways = 0 break cache[(big, small)] = countRelPrime(big//small, M//small) new_ways = cache[(big, small)] #print(f'found {new_ways}') ways = (ways * new_ways) % mod print(f'{ways}')
1667745300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["Yes\n4\n4 3\n4 2\n1 3\n1 2", "Yes\n6\n6 5\n6 4\n6 3\n5 4\n5 3\n2 1", "No"]
f1c1d50865d46624294b5a31d8834097
null
There are n players sitting at a round table. All of them have s cards of n colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules: as the players swap, a player can give a card of his color only; a player can't accept a card of a color he already has (particularly, he can't take cards of his color, no matter whether he has given out all of them or not); during one swap a pair of people swaps cards (each person gives one card and takes one card). The aim of all n people is as follows: each of them should give out all the cards he had initially (that is, all cards of his color). Your task is to denote whether such sequence of swaps is possible. If the answer is positive, you should list all the swaps.
On the first line print "No" if such sequence of swaps is impossible. Otherwise, print "Yes". If the answer is positive, next print number k — the number of the swaps. Then on k lines describe the swaps by pairs of indices of the swapping players. Print the swaps and the numbers of the swaps in any order.
The first line contains integers n (1 ≤ n ≤ 200000) and s (1 ≤ s ≤ 200000). The second line contains n numbers, the i-th number stands for how many cards the i-th player has by the moment the game starts. It is possible that a player has no cards initially.
standard output
standard input
Python 2
Python
2,200
train_037.jsonl
8c83488018611ed3649fcb9d1aeb1d9a
256 megabytes
["4 8\n2 2 2 2", "6 12\n1 1 2 2 3 3", "5 5\n0 0 0 0 5"]
PASSED
from heapq import * n, s = map(int, raw_input().split()) a = map(int, raw_input().split()) q = [(-x, i) for (i, x) in enumerate(a) if x > 0] heapify(q) res = [] while q: (x, i) = heappop(q) if -x > len(q): print 'No' break for (y, j) in [heappop(q) for _ in xrange(-x)]: res.append((i + 1, j + 1)) if y + 1: heappush(q, (y + 1, j)) else: print 'Yes' print len(res) for (i, j) in res: print i, j
1322838000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES"]
0a720a0b06314fde783866b47f35af81
NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero: choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$; choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$.
You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.
For each test case print the answer to it — YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \le a, b \le 10^9$$$).
standard output
standard input
PyPy 3
Python
1,300
train_002.jsonl
28de3f0c5c80437e99979cb0e751672d
256 megabytes
["3\n6 9\n1 1\n1 2"]
PASSED
t = int(input()) while t: t -= 1 a, b = tuple(map(int, input().split())) if (a > b): a, b = b, a if ((2 * a - b) % 3 == 0 and b <= 2 * a): print("Yes") else: print("No")
1574862600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["7\n1\n1\n2\n1\n3\n3\n3"]
7c0ffbba9e61a25e51c91b1f89c35532
null
You are given a matrix $$$a$$$, consisting of $$$3$$$ rows and $$$n$$$ columns. Each cell of the matrix is either free or taken.A free cell $$$y$$$ is reachable from a free cell $$$x$$$ if at least one of these conditions hold: $$$x$$$ and $$$y$$$ share a side; there exists a free cell $$$z$$$ such that $$$z$$$ is reachable from $$$x$$$ and $$$y$$$ is reachable from $$$z$$$. A connected component is a set of free cells of the matrix such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule.You are asked $$$q$$$ queries about the matrix. Each query is the following: $$$l$$$ $$$r$$$ — count the number of connected components of the matrix, consisting of columns from $$$l$$$ to $$$r$$$ of the matrix $$$a$$$, inclusive. Print the answers to all queries.
Print $$$q$$$ integers — the $$$j$$$-th value should be equal to the number of the connected components of the matrix, consisting of columns from $$$l_j$$$ to $$$r_j$$$ of the matrix $$$a$$$, inclusive.
The first line contains an integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of columns of matrix $$$a$$$. The $$$i$$$-th of the next three lines contains a description of the $$$i$$$-th row of the matrix $$$a$$$ — a string, consisting of $$$n$$$ characters. Each character is either $$$1$$$ (denoting a free cell) or $$$0$$$ (denoting a taken cell). The next line contains an integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. The $$$j$$$-th of the next $$$q$$$ lines contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$) — the description of the $$$j$$$-th query.
standard output
standard input
PyPy 3-64
Python
2,500
train_092.jsonl
c2ec762d45fcc57722b5c5f06d808acc
256 megabytes
["12\n100101011101\n110110010110\n010001011101\n8\n1 12\n1 1\n1 2\n9 9\n8 11\n9 12\n11 12\n4 6"]
PASSED
import sys def Column2Num( m, idx ): return int(m[0][idx] != 0) | (int(m[1][idx]) << 1) | (int(m[2][idx]) << 2) def QColumn( m, bits, idx ): if bits[idx] == 5: if m[0][idx] == m[2][idx]: return True return False def GetIntegratedCount( m ): ret, curr = [ 0 ], set() for c in range( len( m[0] ) ): if m[0][c] != 0: curr.add( m[0][c] ) if m[1][c] != 0: curr.add( m[1][c] ) if m[2][c] != 0: curr.add( m[2][c] ) ret.append( len( curr ) ) ret.append( len( curr ) ) return ret def Print( tm ): print( '\n', tm[0], '\n', tm[1], '\n', tm[2] ) def PrintIndexed( tm ): for i in range( len( tm[0] ) ): print( i+1, ':', tm[0][i], tm[1][i], tm[2][i] ) def next( b, next ): b &= next if b == 0: return b if b & 1 or b & 4: if next & 2: b |= 2 if b & 2: if next & 1: b |= 1 if next & 4: b |= 4 return b def setCompNumber( b, m, i, compNumber ): if b & 1: m[0][i] = compNumber if b & 2: m[1][i] = compNumber if b & 4: m[2][i] = compNumber def goLeft( start, compNumber, size, m, bits, fullColumn ): b = bits[start] fc = start for i in range( start - 1, -1, -1 ): b = next( b, bits[i] ) if b == 7: fc = i break if b == 0: break setCompNumber( b, m, i, compNumber ) if b == 5: fullColumn[ i ] = fc def goRight( start, compNumber, size, m, bits, fullColumn ): b = bits[start] for i in range( start, size ): b = next( b, bits[i] ) if b == 7: fc = i if b == 0: break setCompNumber( b, m, i, compNumber ) if b == 5: fullColumn[ i ] = fc def goRight12( b, start, compNumber, size, m, bits ): for i in range( start, size ): b = next( b, bits[i] ) if b == 0: break setCompNumber( b, m, i, compNumber ) def get3Components( compNumber, size, m, bits, leftFullColumn, rightFullColumn ): for i in range( size ): if bits[i] == 7: if m[ 0 ][ i ] == 1: compNumber += 1 goRight( i, compNumber, size, m, bits, leftFullColumn ) goLeft ( i, compNumber, size, m, bits, rightFullColumn ) return compNumber def get12Components( compNumber, size, m, bits ): for i in range( size ): if m[ 0 ][ i ] == 1: compNumber += 1 goRight12( 1, i, compNumber, size, m, bits ) if m[ 1 ][ i ] == 1: compNumber += 1 goRight12( 2, i, compNumber, size, m, bits ) if m[ 2 ][ i ] == 1: compNumber += 1 goRight12( 4, i, compNumber, size, m, bits ) def SolveBB( m, bits, integratedCount, s, e, leftFullColumn, rightFullColumn ): #debug = 0 #print( 'start,end =',s, e ) #if debug: Print( [ m[0][s-1:e], m[1][s-1:e], m[2][s-1:e] ] ) sol1 = 0 if s-1 == 0: sol1 = integratedCount[e] else: startCnt = 1 if bits[s-1] == 0: startCnt = 0 elif bits[s-1] == 5: if m[0][s-1] != m[2][s-1]: startCnt = 2 sol1 = startCnt + integratedCount[e] - integratedCount[s] sQ = QColumn( m, bits, s - 1) eQ = QColumn( m, bits, e - 1) if sQ and eQ: if m[0][s-1] == m[2][s-1]: if rightFullColumn[s-1] == rightFullColumn[e-1]: sol1 += 1 return sol1 elif leftFullColumn[s-1] == leftFullColumn[e-1]: sol1 += 1 return sol1 if sQ: if rightFullColumn[s-1] != -1: if rightFullColumn[s-1] > e-1: sol1 += 1 else: sol1 += 1 if eQ: if leftFullColumn[e-1] != -1: if leftFullColumn[e-1] < s-1: sol1 += 1 else: sol1 += 1 return sol1 def mainBB(): debug = 0 input = sys.stdin if len( sys.argv ) >= 2: input = open( sys.argv[1], 'r' ) size = int( input.readline() ) m = [] for i in range( 3 ): m.append( [ int( t ) for t in list( input.readline().strip() ) ] ) bits = [ Column2Num( m, i ) for i in range( size ) ] leftFullColumn = [ -1 for i in range( size ) ] rightFullColumn = list( leftFullColumn ) compNumber = get3Components( 1, size, m, bits, leftFullColumn, rightFullColumn ) get12Components( compNumber, size, m, bits ) integratedCount = GetIntegratedCount( m ) if debug: PrintIndexed( m ) if debug: Print( m ) if debug: print( integratedCount ) if debug: print( leftFullColumn ) if debug: print( rightFullColumn ) n = int( input.readline() ) for i in range( n ): ln = input.readline().strip().split() s = int( ln[0] ) e = int( ln[1] ) if debug: print( s, e, m ) print( SolveBB( m, bits, integratedCount, s, e, leftFullColumn, rightFullColumn ) ) if __name__ == "__main__": mainBB()
1649514900
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
2 seconds
["5\n4\n2\n0"]
21f7c9e71ce1532514a6eaf0ff1c92da
NoteThe towers in the example are: before the queries: $$$[[5, 1], [2], [7, 4, 3], [6]]$$$; after the first query: $$$[[2], [7, 5, 4, 3, 1], [6]]$$$; after the second query: $$$[[7, 5, 4, 3, 2, 1], [6]]$$$; after the third query, there is only one tower: $$$[7, 6, 5, 4, 3, 2, 1]$$$.
You have a set of $$$n$$$ discs, the $$$i$$$-th disc has radius $$$i$$$. Initially, these discs are split among $$$m$$$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers $$$i$$$ and $$$j$$$ (each containing at least one disc), take several (possibly all) top discs from the tower $$$i$$$ and put them on top of the tower $$$j$$$ in the same order, as long as the top disc of tower $$$j$$$ is bigger than each of the discs you move. You may perform this operation any number of times.For example, if you have two towers containing discs $$$[6, 4, 2, 1]$$$ and $$$[8, 7, 5, 3]$$$ (in order from bottom to top), there are only two possible operations: move disc $$$1$$$ from the first tower to the second tower, so the towers are $$$[6, 4, 2]$$$ and $$$[8, 7, 5, 3, 1]$$$; move discs $$$[2, 1]$$$ from the first tower to the second tower, so the towers are $$$[6, 4]$$$ and $$$[8, 7, 5, 3, 2, 1]$$$. Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers $$$[[3, 1], [2]]$$$ is $$$2$$$: you may move the disc $$$1$$$ to the second tower, and then move both discs from the second tower to the first tower.You are given $$$m - 1$$$ queries. Each query is denoted by two numbers $$$a_i$$$ and $$$b_i$$$, and means "merge the towers $$$a_i$$$ and $$$b_i$$$" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index $$$a_i$$$.For each $$$k \in [0, m - 1]$$$, calculate the difficulty of the set of towers after the first $$$k$$$ queries are performed.
Print $$$m$$$ integers. The $$$k$$$-th integer ($$$0$$$-indexed) should be equal to the difficulty of the set of towers after the first $$$k$$$ queries are performed.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le m \le n \le 2 \cdot 10^5$$$) — the number of discs and the number of towers, respectively. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$1 \le t_i \le m$$$), where $$$t_i$$$ is the index of the tower disc $$$i$$$ belongs to. Each value from $$$1$$$ to $$$m$$$ appears in this sequence at least once. Then $$$m - 1$$$ lines follow, denoting the queries. Each query is represented by two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le m$$$, $$$a_i \ne b_i$$$), meaning that, during the $$$i$$$-th query, the towers with indices $$$a_i$$$ and $$$b_i$$$ are merged ($$$a_i$$$ and $$$b_i$$$ are chosen in such a way that these towers exist before the $$$i$$$-th query).
standard output
standard input
Python 3
Python
2,300
train_050.jsonl
a7ff58d757af1055594167694f353909
512 megabytes
["7 4\n1 2 3 3 1 4 3\n3 1\n2 3\n2 4"]
PASSED
def get_ints(): return map(int, input().split()) def main(): _, m = get_ints() s = [set() for _ in range(m)] prev, score = -1, -1 for index, dest in enumerate(get_ints()): s[dest - 1].add(index) if prev != dest: score += 1 prev = dest ans = [score] for _ in range(m - 1): x, y = get_ints() x, y = x - 1, y - 1 target = x if len(s[x]) < len(s[y]): x, y = y, x for e in s[y]: if e - 1 in s[x]: score -= 1 if e + 1 in s[x]: score -= 1 for e in s[y]: s[x].add(e) s[target] = s[x] ans.append(score) print(*ans, sep='\n') main()
1594565100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["abc", "abdc"]
e758ae072b8aed53038e4593a720276d
null
Petya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: Extract the first character of s and append t with this character. Extract the last character of t and append u with this character. Petya wants to get strings s and t empty and string u lexicographically minimal.You should write a program that will help Petya win the game.
Print resulting string u.
First line contains non-empty string s (1 ≤ |s| ≤ 105), consisting of lowercase English letters.
standard output
standard input
Python 3
Python
1,700
train_015.jsonl
8bde194f031c0f296fa6a89cf3f64bbf
256 megabytes
["cab", "acdb"]
PASSED
#! /bin/python s = input() resultBase = "" resultRest = "" best = len(s) - 1 mini = [0] * len(s) for i in range(len(s) - 1, -1, -1): mini[i] = best if s[best] >= s[i]: best = i for i in range(len(s)): resultRest += s[i] while len(resultRest) > 0 and resultRest[-1] <= s[mini[i]]: resultBase += resultRest[-1] resultRest = resultRest[:-1] # print(resultRest[-1] if len(resultRest) > 0 else '-', s[mini[i]]) # print(resultRest) # print(resultBase) # print() print(resultBase + resultRest[::-1])
1492266900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["4", "2", "0", "3", "1"]
87d3c1d8d3d1f34664ff32081222117d
NoteIn the first example the question marks can be replaced in the following way: "aaaababbbb". $$$f_1 = 4$$$, $$$f_2 = 4$$$, thus the answer is $$$4$$$. Replacing it like this is also possible: "aaaabbbbbb". That way $$$f_1 = 4$$$, $$$f_2 = 6$$$, however, the minimum of them is still $$$4$$$.In the second example one of the possible strings is "aabbccdda".In the third example at least one letter won't appear in the string, thus, the minimum of values $$$f_i$$$ is always $$$0$$$.
You are given a string $$$s$$$ of length $$$n$$$. Each character is either one of the first $$$k$$$ lowercase Latin letters or a question mark.You are asked to replace every question mark with one of the first $$$k$$$ lowercase Latin letters in such a way that the following value is maximized.Let $$$f_i$$$ be the maximum length substring of string $$$s$$$, which consists entirely of the $$$i$$$-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the $$$i$$$-th letter doesn't appear in a string, then $$$f_i$$$ is equal to $$$0$$$.The value of a string $$$s$$$ is the minimum value among $$$f_i$$$ for all $$$i$$$ from $$$1$$$ to $$$k$$$.What is the maximum value the string can have?
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first $$$k$$$ lowercase Latin letters.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 17$$$) — the length of the string and the number of first Latin letters used. The second line contains a string $$$s$$$, consisting of $$$n$$$ characters. Each character is either one of the first $$$k$$$ lowercase Latin letters or a question mark.
standard output
standard input
PyPy 3
Python
2,500
train_094.jsonl
969d66385f4f66d2d8faf899a2e66eb0
256 megabytes
["10 2\na??ab????b", "9 4\n?????????", "2 3\n??", "15 3\n??b?babbc??b?aa", "4 4\ncabd"]
PASSED
import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline from collections import deque n, k = map(int,input().split()) s = input() def judge(needed): inf = 2147483647 minstate = [inf]*(1<<k) minstate[0] = 0 effect = [[inf]*(n+1) for j in range(k)] for j in range(k): accu = 0 index = inf for i in range(n)[::-1]: if s[i]==ord('?') or s[i]==97+j: accu += 1 else: accu = 0 if accu>=needed: index = i + needed effect[j][i] = index # effect[j][i] = min(effect[j][i],inf*inf+inf*inf) # print(effect) for state in range(1,1<<k): minimum = minstate[state] for j in range(k): if (1<<j) & state==0: continue index = minstate[state^(1<<j)] if index<n: minimum = min(minimum, effect[j][index]) minstate[state] = minimum # print(minstate) if minstate[-1]<=n: return True return False front = 0 rear = n//k+1 while front < rear: mid = (front+rear)//2 flag = judge(mid) # print(mid,flag) if flag: front = mid + 1 else: rear = mid print(front-1)
1626273300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["T\nHL"]
5bfce6c17af24959b4af3c9408536d05
NoteIn the first game, T removes a single stone from the only pile in his first turn. After that, although the pile still contains $$$1$$$ stone, HL cannot choose from this pile because it has been chosen by T in the previous turn. Therefore, T is the winner.
T is playing a game with his friend, HL.There are $$$n$$$ piles of stones, the $$$i$$$-th pile initially has $$$a_i$$$ stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.Assuming both players play optimally, given the starting configuration of $$$t$$$ games, determine the winner of each game.
For each game, print on a single line the name of the winner, "T" or "HL" (without quotes)
The first line of the input contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of games. The description of the games follows. Each description contains two lines: The first line contains a single integer $$$n$$$ $$$(1 \le n \le 100)$$$ — the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 100)$$$.
standard output
standard input
PyPy 3
Python
1,800
train_002.jsonl
8defb17bc2d2c6dc10de686b573670ee
256 megabytes
["2\n1\n2\n2\n1 1"]
PASSED
for t in range(int(input())): n=int(input()) l=list(map(int,input().split())) l.sort() s=sum(l) if l[-1]>s-l[-1]: print("T") elif s%2==0: print("HL") else: print("T")
1598798100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["10\n15\n1999999999\n113\n1000000001\n1"]
7d6f76e24fe9a352beea820ab56f03b6
null
You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. The $$$7$$$-th number among them is $$$10$$$.
For each test case print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$2 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$).
standard output
standard input
Python 3
Python
1,200
train_000.jsonl
83641157346168524dfcefc5d55e6430
256 megabytes
["6\n3 7\n4 12\n2 1000000000\n7 97\n1000000000 1000000000\n2 1"]
PASSED
import math t=int(input()) for _ in range(0,t): n,k=map(int,input().split(" ")) need=math.floor((k-1)//(n-1)) print(k+need)
1589034900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4\n-1\n5"]
474f29da694929a64eaed6eb8e4349c3
NoteIn the first test case the optimal sequence is: $$$4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$$$.
Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.
Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\le n, d \le 10^9$$$, $$$1 \le x, y \le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.
standard output
standard input
Python 2
Python
1,200
train_002.jsonl
7309be6e7e7fdb09adedff421628d79d
256 megabytes
["3\n10 4 5 2\n5 1 3 4\n20 4 19 3"]
PASSED
import math a = input() for _ in xrange(0, a): bookSize, startPage, endPage, jumpsAllowed = map(int, raw_input().split()) jumps = abs(((endPage - startPage) / float(jumpsAllowed))) if jumps.is_integer(): print int(jumps) continue jumpsLeft = abs(math.ceil(((startPage - 1) / float(jumpsAllowed)))) + abs((endPage - 1) / float(jumpsAllowed)) jumpsRight = abs(math.ceil(((bookSize - startPage) / float(jumpsAllowed)))) + abs((bookSize - endPage) / float(jumpsAllowed)) if jumpsLeft.is_integer() and jumpsRight.is_integer(): print min(int(jumpsLeft), int(jumpsRight)) elif jumpsLeft.is_integer(): print int(jumpsLeft) elif jumpsRight.is_integer(): print int(jumpsRight) else: print -1
1543415700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["1", "12", "0"]
1c2a2ad98e7162e89d36940b2848b921
null
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 109 + 7.
Print the number of ways to connect points modulo 109 + 7.
The first line contains one number n (3 ≤ n ≤ 500) — the number of marked points. Then n lines follow, each containing n elements. ai, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise ai, j = 0). It is guaranteed that for any pair of points ai, j = aj, i, and for any point ai, i = 0.
standard output
standard input
PyPy 2
Python
2,500
train_017.jsonl
60ad08b3377da64e3da0c570835fbe26
256 megabytes
["3\n0 0 1\n0 0 1\n1 1 0", "4\n0 1 1 1\n1 0 1 1\n1 1 0 1\n1 1 1 0", "3\n0 0 0\n0 0 1\n0 1 0"]
PASSED
import sys range = xrange input = raw_input MOD = 10**9 + 7 INVMOD = 1.0/MOD import __pypy__ mulmod = __pypy__.intop.int_mulmod sub = __pypy__.intop.int_sub mul = __pypy__.intop.int_mul def mo(a,b): return sub(mul(a,b), mul(MOD, int(INVMOD * a * b))) n = int(input()) A = [] for _ in range(n): A.append([int(x) for x in input().split()]) # don't connect ends DP0 = [[-1] * n for _ in range(n)] # connect ends DP1 = [[-1] * n for _ in range(n)] for i in range(n): DP0[i][0] = 1 DP1[i][0] = 1 for l in range(1, n): for i in range(n): Ai = A[i] DP0i = DP0[i] DP1i = DP1[i] x = 0.0 + DP1[i + 1 - n][l - 1] for k in range(1, l): if Ai[i + k - n]: x += mo(DP0i[k], DP0[i + k - n][l - k]) DP0i[l] = int(int(x) % MOD) x = 0.0 for k in range(1, l + 1): if Ai[i + k - n]: x += mo(DP0i[k], DP1[i + k - n][l - k]) DP1i[l] = int(int(x) % MOD) print DP1[0][n - 1]
1510239900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["3 3 5 5", "1000000000 1000000000 1000000000 1000000000 1000000000"]
41645bbe84910de81ac4ed2a56a046d3
NoteFor the first example, When k = 0, one possible optimal game is as follows: Oleg eats the carrot with juiciness 1. Igor eats the carrot with juiciness 5. Oleg eats the carrot with juiciness 2. The remaining carrot has juiciness 3.When k = 1, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2. Igor eats the carrot with juiciness 5. The remaining carrot has juiciness 3.When k = 2, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2 beforehand. Oleg eats the carrot with juiciness 3. The remaining carrot has juiciness 5.When k = 3, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2 beforehand. Oleg eats the carrot with juiciness 3 beforehand. The remaining carrot has juiciness 5.Thus, the answer is 3, 3, 5, 5.For the second sample, Oleg can always eat the carrot with juiciness 1 since he always moves first. So, the remaining carrot will always have juiciness 1000000000.
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present.There are n carrots arranged in a line. The i-th carrot from the left has juiciness ai. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose.To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS.Oleg is a sneaky bank client. When Igor goes to a restroom, he performs k moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first. Oleg wonders: for each k such that 0 ≤ k ≤ n - 1, what is the juiciness of the carrot they will give to ZS if he makes k extra moves beforehand and both players play optimally?
Output n space-separated integers x0, x1, ..., xn - 1. Here, xi denotes the juiciness of the carrot the friends will present to ZS if k = i.
The first line of input contains a single integer n (1 ≤ n ≤ 3·105) — the total number of carrots. The next line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). Here ai denotes the juiciness of the i-th carrot from the left of the line.
standard output
standard input
PyPy 3
Python
2,800
train_029.jsonl
6be7cc557c658d4c3f2837d49f561f47
256 megabytes
["4\n1 2 3 5", "5\n1000000000 1000000000 1000000000 1000000000 1"]
PASSED
def evens(A): n = len(A) l = n//2-1; r = n//2 if len(A)%2 == 1: l+= 1 ans = [max(A[l], A[r])] while r < n-1: l-= 1; r+= 1 ans.append(max(ans[-1], A[l], A[r])) return ans def interleave(A, B): q = [] for i in range(len(B)): q+= [A[i], B[i]] if len(A) != len(B): q.append(A[-1]) return q n = int(input()) A = list(map(int,input().split())) M = [min(A[i],A[i+1]) for i in range(n-1)] ansA = evens(A) ansM = evens(M) if n>1 else [] if n%2 == 0: print(*interleave(ansA, ansM[1:]), max(A)) else: print(*interleave(ansM, ansA[1:]), max(A))
1494668100
[ "math", "games" ]
[ 1, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES", "NO"]
21c0e12347d8be7dd19cb9f43a31be85
NoteIn the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct: a1 is equivalent to b1, and a2 is equivalent to b2 a1 is equivalent to b2, and a2 is equivalent to b1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
standard output
standard input
Python 3
Python
1,700
train_010.jsonl
eb0b65066323e88c4f008711ac4c69d7
256 megabytes
["aaba\nabaa", "aabb\nabab"]
PASSED
def checaEquavalencia(a, b, tam): if a == b: #print('YES') return True elif len(a) % 2 == 1: return False elif len(b) % 2 == 1: return False elif tam > 1: tam = tam // 2 a1 = a[ : tam] a2 = a[tam : ] b1 = b[ : tam] b2 = b[tam : ] #caso1 = checaEquavalencia(a1, b1, tam) and checaEquavalencia(a2, b2, tam) #caso2 = checaEquavalencia(a1, b2, tam) and checaEquavalencia(a2, b1, tam) if checaEquavalencia(a1, b2, tam) and checaEquavalencia(a2, b1, tam): return True elif checaEquavalencia(a1, b1, tam) and checaEquavalencia(a2, b2, tam): return True return False a = input() b = input() resposta = 'NO' ta = len(a) tb = len(b) if(ta != tb): resposta = 'NO' elif(a == b): resposta = 'YES' elif(ta % 2 == 0): resp = checaEquavalencia(a , b, ta) if resp == True: resposta = 'YES' print(resposta)
1437573600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["poisson\nuniform"]
e1dad71bee6d60b4d6dc33ea8cf09ba1
NoteThe full example input is visually represented below, along with the probability distribution function it was drawn from (the y-axis is labeled by its values multiplied by 250).
Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of V (1 ≤ V ≤ 100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures.Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants P (10 ≤ P ≤ 1000) of the village, they respond with a random non-negative integer k, drawn from one of two types of probability distributions: Poisson (d'avril) distribution: the probability of getting an answer k is for k = 0, 1, 2, 3, ..., Uniform distribution: the probability of getting an answer k is for k = 0, 1, 2, ..., 2P. Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution.Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answer came from a uniform distribution.
The first line of input will contain the number of villages V (1 ≤ V ≤ 100). The following V lines each describe one village. The description of each village consists of 250 space-separated integers k, drawn from one of the above distributions.
standard output
standard input
Python 3
Python
2,100
train_045.jsonl
2eeedebdca4c38ae7b7ceff577c02f97
256 megabytes
["2\n92 100 99 109 93 105 103 106 101 99 ... (input is truncated)\n28 180 147 53 84 80 180 85 8 16 ... (input is truncated)"]
PASSED
v = int(input()) eps = 3 def ans(a): a.sort() if len(a) % 2 == 0: med = a[len(a)//2] else: med = (a[len(a)//2] + a[len(a)//2 - 1]) // 2 l = med - med // 2 r = med + med // 2 c1 = c2 = 0 for i in a: if i >= l and i <= r: c1 += 1 else: c2 += 1 if c2 == 0: c2 = 0.0001 if c1 / c2 <= eps: return "uniform" else: return "poisson" for i in range(v): cur = [int(i) for i in input().split()] print(ans(cur))
1495958700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3.729935587093555327", "11.547005383792516398"]
b44c6836ee3d597a78d4b6b16ef1d4b3
null
A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.
Print a single real value — the minimum time the rescuers need to get to point (x2, y2). You 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 four integers x1, y1, x2, y2 (|x1|,  |y1|,  |x2|,  |y2| ≤ 10 000) — the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively. The second line contains two integers and t (0 &lt; v, t ≤ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively. Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that and .
standard output
standard input
Python 2
Python
2,100
train_006.jsonl
8427e856a1960db1ba05e67361e0751f
256 megabytes
["0 0 5 5\n3 2\n-1 -1\n-1 0", "0 0 0 1000\n100 1000\n-50 0\n50 0"]
PASSED
x,y,xx,yy=map(float,raw_input().split()) v,t=map(float,raw_input().split()) vx,vy=map(float,raw_input().split()) ux,uy=map(float,raw_input().split()) X=x+vx*t Y=y+vy*t ans=0 if (X-xx)*(X-xx)+(Y-yy)*(Y-yy)>v*t*v*t: ans=t x=X y=Y else: t=0 ux=vx uy=vy l=0.0 r=float(pow(10,20)) while r-l>pow(0.1,7): m=(l+r)*0.5 X=x+ux*m Y=y+uy*m if (X-xx)*(X-xx)+(Y-yy)*(Y-yy)>v*v*(m+t)*(m+t): l=m else: r=m print round(ans+l,7)
1445763600
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["25\n1438\n1101\n686531475"]
592e219abe72054c3de1b6823a1d049d
NoteLet's illustrate what happens with the first test case. Initially, we have $$$s = $$$ 231. Initially, $$$\ell = 0$$$ and $$$c = \varepsilon$$$ (the empty string). The following things happen if we follow the procedure above: Step 1, Move once: we get $$$\ell = 1$$$. Step 2, Cut once: we get $$$s = $$$ 2 and $$$c = $$$ 31. Step 3, Paste $$$s_\ell = $$$ 2 times: we get $$$s = $$$ 23131. Step 4: $$$\ell = 1 \not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\ell = 2$$$. Step 2, Cut once: we get $$$s = $$$ 23 and $$$c = $$$ 131. Step 3, Paste $$$s_\ell = $$$ 3 times: we get $$$s = $$$ 23131131131. Step 4: $$$\ell = 2 \not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\ell = 3$$$. Step 2, Cut once: we get $$$s = $$$ 231 and $$$c = $$$ 31131131. Step 3, Paste $$$s_\ell = $$$ 1 time: we get $$$s = $$$ 23131131131. Step 4: $$$\ell = 3 \not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\ell = 4$$$. Step 2, Cut once: we get $$$s = $$$ 2313 and $$$c = $$$ 1131131. Step 3, Paste $$$s_\ell = $$$ 3 times: we get $$$s = $$$ 2313113113111311311131131. Step 4: $$$\ell = 4 \not= x = 5$$$, so we return to step 1. Step 1, Move once: we get $$$\ell = 5$$$. Step 2, Cut once: we get $$$s = $$$ 23131 and $$$c = $$$ 13113111311311131131. Step 3, Paste $$$s_\ell = $$$ 1 times: we get $$$s = $$$ 2313113113111311311131131. Step 4: $$$\ell = 5 = x$$$, so we stop. At the end of the procedure, $$$s$$$ has length $$$25$$$.
We start with a string $$$s$$$ consisting only of the digits $$$1$$$, $$$2$$$, or $$$3$$$. The length of $$$s$$$ is denoted by $$$|s|$$$. For each $$$i$$$ from $$$1$$$ to $$$|s|$$$, the $$$i$$$-th character of $$$s$$$ is denoted by $$$s_i$$$. There is one cursor. The cursor's location $$$\ell$$$ is denoted by an integer in $$$\{0, \ldots, |s|\}$$$, with the following meaning: If $$$\ell = 0$$$, then the cursor is located before the first character of $$$s$$$. If $$$\ell = |s|$$$, then the cursor is located right after the last character of $$$s$$$. If $$$0 &lt; \ell &lt; |s|$$$, then the cursor is located between $$$s_\ell$$$ and $$$s_{\ell+1}$$$. We denote by $$$s_\text{left}$$$ the string to the left of the cursor and $$$s_\text{right}$$$ the string to the right of the cursor. We also have a string $$$c$$$, which we call our clipboard, which starts out as empty. There are three types of actions: The Move action. Move the cursor one step to the right. This increments $$$\ell$$$ once. The Cut action. Set $$$c \leftarrow s_\text{right}$$$, then set $$$s \leftarrow s_\text{left}$$$. The Paste action. Append the value of $$$c$$$ to the end of the string $$$s$$$. Note that this doesn't modify $$$c$$$. The cursor initially starts at $$$\ell = 0$$$. Then, we perform the following procedure: Perform the Move action once. Perform the Cut action once. Perform the Paste action $$$s_\ell$$$ times. If $$$\ell = x$$$, stop. Otherwise, return to step 1. You're given the initial string $$$s$$$ and the integer $$$x$$$. What is the length of $$$s$$$ when the procedure stops? Since this value may be very large, only find it modulo $$$10^9 + 7$$$. It is guaranteed that $$$\ell \le |s|$$$ at any time.
For each test case, output a single line containing a single integer denoting the answer for that test case modulo $$$10^9 + 7$$$.
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer $$$x$$$ ($$$1 \le x \le 10^6$$$). The second line of each test case consists of the initial string $$$s$$$ ($$$1 \le |s| \le 500$$$). It is guaranteed, that $$$s$$$ consists of the characters "1", "2", "3". It is guaranteed that the sum of $$$x$$$ in a single file is at most $$$10^6$$$. It is guaranteed that in each test case before the procedure will stop it will be true that $$$\ell \le |s|$$$ at any time.
standard output
standard input
PyPy 3
Python
1,700
train_005.jsonl
6c363be6160858827861bfddf5206e10
256 megabytes
["4\n5\n231\n7\n2323\n6\n333\n24\n133321333"]
PASSED
for _ in range(int(input())): x = int(input()) sen = list(map(int, input())) l = 1 len_sen = len(sen) while(l <= x): itr = sen[l-1] len_sen = (l + (len_sen - l) * sen[l-1])%(1000000007) idx = len(sen) for _ in range(itr-1): if len(sen) < x: sen += sen[l:idx] else: break l+=1 print(len_sen)
1576386300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0", "4", "5"]
cd921b5fc4140f1cd19e73c42b3bc2fe
NoteIn the first test case string a is the same as string b and equals 100 letters a. As both strings are equal, the Hamming distance between them is zero.In the second test case strings a and b differ in their 3-rd, 5-th, 6-th and 7-th characters. Thus, the Hamming distance equals 4.In the third test case string a is rzrrzr and string b is azazaz. The strings differ in all characters apart for the second one, the Hamming distance between them equals 5.
Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance.The Hamming distance between two strings s = s1s2... sn and t = t1t2... tn of equal length n is value . Record [si ≠ ti] is the Iverson notation and represents the following: if si ≠ ti, it is one, otherwise — zero.Now Xenia wants to calculate the Hamming distance between two long strings a and b. The first string a is the concatenation of n copies of string x, that is, . The second string b is the concatenation of m copies of string y. Help Xenia, calculate the required Hamming distance, given n, x, m, y.
Print a single integer — the required Hamming distance. 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 two integers n and m (1 ≤ n, m ≤ 1012). The second line contains a non-empty string x. The third line contains a non-empty string y. Both strings consist of at most 106 lowercase English letters. It is guaranteed that strings a and b that you obtain from the input have the same length.
standard output
standard input
Python 2
Python
1,900
train_013.jsonl
e8072e571611b1d5a86bb6c7f6b8fdce
256 megabytes
["100 10\na\naaaaaaaaaa", "1 1\nabacaba\nabzczzz", "2 3\nrzr\naz"]
PASSED
def gcd(a, b): c = a % b return gcd(b, c) if c else b h = {j: i for i, j in enumerate('abcdefghijklmnopqrstuvwxyz')} n, m = map(int, raw_input().split()) x, y = raw_input(), raw_input() a, b = len(x), len(y) s, c = 0, gcd(a, b) u, v = range(0, a, c), range(0, b, c) if a == c: if b == c: for i in range(c): s += int(y[i] == x[i]) else: for i in range(c): for j in v: s += int(y[j + i] == x[i]) elif b == c: for i in range(c): for j in u: s += int(x[j + i] == y[i]) else: t, d = [0] * (26 * c), 0 for i in range(c): for j in u: t[d + h[x[j + i]]] += 1 for j in v: s += t[d + h[y[j + i]]] d += 26 print(n * a - (m * c * s) // a)
1381838400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n0 1\n0\n1", "2\n-1 0 1\n1\n0 1"]
c2362d3254aefe30da99c4aeb4e1a894
NoteIn the second example you can print polynomials x2 - 1 and x. The sequence of transitions is(x2 - 1, x) → (x,  - 1) → ( - 1, 0).There are two steps in it.
Suppose you have two polynomials and . Then polynomial can be uniquely represented in the following way:This can be done using long division. Here, denotes the degree of polynomial P(x). is called the remainder of division of polynomial by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair to pair .
Print two polynomials in the following format. In the first line print a single integer m (0 ≤ m ≤ n) — the degree of the polynomial. In the second line print m + 1 integers between  - 1 and 1 — the coefficients of the polynomial, from constant to leading. The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials. If there is no answer for the given n, print -1. If there are multiple answer, print any of them.
You are given a single integer n (1 ≤ n ≤ 150) — the number of steps of the algorithm you need to reach.
standard output
standard input
Python 3
Python
2,200
train_057.jsonl
e09a3026235d45b3ddf68edc82d0b6cb
256 megabytes
["1", "2"]
PASSED
n = int(input()) def print_poly(a): print(len(a) - 1) print(' '.join(map(str, a))) def shift_add(a, mul, b): c = [0] * (len(a) + 1) for i in range(len(a)): c[i + 1] = a[i] * mul for i in range(len(b)): c[i] += b[i] return c a = [0, 1] b = [1] for i in range(n - 1): c = shift_add(a, 1, b) if max(c) <= 1 and min(c) >= -1: a, b = c, a else: c = shift_add(a, -1, b) if max(c) <= 1 and min(c) >= -1: a, b = c, a else: print('> <') if a[-1] == -1: a = list(map(lambda x: -x, a)) if b[-1] == -1: b = list(map(lambda x: -x, b)) print_poly(a) print_poly(b)
1513697700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["4 6 5\n2 2 3"]
39d8677b310bee8747c5112af95f0e33
NoteIn the first example $$$n = 3$$$ is possible, then $$$n \cdot 4 + 6 - 5 = 13 = m$$$. Other possible solutions include: $$$a = 4$$$, $$$b = 5$$$, $$$c = 4$$$ (when $$$n = 3$$$); $$$a = 5$$$, $$$b = 4$$$, $$$c = 6$$$ (when $$$n = 3$$$); $$$a = 6$$$, $$$b = 6$$$, $$$c = 5$$$ (when $$$n = 2$$$); $$$a = 6$$$, $$$b = 5$$$, $$$c = 4$$$ (when $$$n = 2$$$).In the second example the only possible case is $$$n = 1$$$: in this case $$$n \cdot 2 + 2 - 3 = 1 = m$$$. Note that, $$$n = 0$$$ is not possible, since in that case $$$n$$$ is not a strictly positive integer.
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $$$n$$$, he encrypts it in the following way: he picks three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$l \leq a,b,c \leq r$$$, and then he computes the encrypted value $$$m = n \cdot a + b - c$$$.Unfortunately, an adversary intercepted the values $$$l$$$, $$$r$$$ and $$$m$$$. Is it possible to recover the original values of $$$a$$$, $$$b$$$ and $$$c$$$ from this information? More formally, you are asked to find any values of $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$a$$$, $$$b$$$ and $$$c$$$ are integers, $$$l \leq a, b, c \leq r$$$, there exists a strictly positive integer $$$n$$$, such that $$$n \cdot a + b - c = m$$$.
For each test case output three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that, $$$l \leq a, b, c \leq r$$$ and there exists a strictly positive integer $$$n$$$ such that $$$n \cdot a + b - c = m$$$. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions.
The first line contains the only integer $$$t$$$ ($$$1 \leq t \leq 20$$$) — the number of test cases. The following $$$t$$$ lines describe one test case each. Each test case consists of three integers $$$l$$$, $$$r$$$ and $$$m$$$ ($$$1 \leq l \leq r \leq 500\,000$$$, $$$1 \leq m \leq 10^{10}$$$). The numbers are such that the answer to the problem exists.
standard output
standard input
Python 3
Python
1,500
train_001.jsonl
851a794c71a9a03c398e6560fb6c1aab
512 megabytes
["2\n4 6 13\n2 3 1"]
PASSED
# -*- coding: utf-8 -*- """ Created on Tue Jul 21 01:33:02 2020 @author: Manan Tyagi """ import math t=int(input()) p=0 a=0 while t: t-=1 l,r,m=map(int,input().split()) mxd=r-l if m<l: pr=m-l c=r b=c+pr a=l elif m==l: a=l b=l c=l else: for i in range(r,l-1,-1): #checking on every iteration n=math.floor(m/i) n1=math.ceil(m/i) f1=abs((n*i)-m) f2=abs((n1*i)-m) re=min(f1,f2) if re<=mxd: if re==f1: p=n else: p=n1 a=i break #print(p) pr=m-(a*p) #print(pr) if pr>0: c=l b=c+pr else: c=r b=c+pr print(a,b,c)
1595149200
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["4", "2"]
5be268e0607f2d654d7f5ae4f11e2f08
NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order: Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 &gt; w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$. Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$. Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$. Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 &gt; w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$. Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$. Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.
Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i &gt; 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i &lt; i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty): Choose a card $$$x$$$ such that no other cards are hanging onto it. Append the number written on card $$$x$$$ to the end of $$$s$$$. If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$. Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
Print a single integer — the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) describing which card that each card hangs onto.
standard output
standard input
Python 3
Python
1,800
train_096.jsonl
91168a86225097c6f1b2250ba9478ff5
256 megabytes
["6\n1 2 1 4 2", "2\n1"]
PASSED
import sys, threading from collections import defaultdict def main(): def dfs(node): d = 1 childs_sum = 0 for adj in tree[node]: child_depth,childs_val = dfs(adj) d = max(d, 1 + child_depth) childs_sum += childs_val return (d,max(childs_sum,d)) n = int(input()) pars = list(map(int, input().split())) tree = defaultdict(list) for i in range(n - 1): v = pars[i] tree[v].append(i + 2) res = dfs(1) print(max(*res)) sys.setrecursionlimit(1 << 30) threading.stack_size(1 << 27) main_thread = threading.Thread(target = main) main_thread.start() main_thread.join()
1667034600
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["0\n1\n2\n3"]
8c4a0a01c37fa1b7c507043ee6d93544
NoteIn the first sample, the array $$$a$$$ is already good.In the second sample, it's enough to delete $$$1$$$, obtaining array $$$[4, 4, 5, 6]$$$, which is good.
Let's call an array of $$$k$$$ integers $$$c_1, c_2, \ldots, c_k$$$ terrible, if the following condition holds:Let $$$AVG$$$ be the $$$\frac{c_1 + c_2 + \ldots + c_k}{k}$$$(the average of all the elements of the array, it doesn't have to be integer). Then the number of elements of the array which are bigger than $$$AVG$$$ should be strictly larger than the number of elements of the array which are smaller than $$$AVG$$$. Note that elements equal to $$$AVG$$$ don't count.For example $$$c = \{1, 4, 4, 5, 6\}$$$ is terrible because $$$AVG = 4.0$$$ and $$$5$$$-th and $$$4$$$-th elements are greater than $$$AVG$$$ and $$$1$$$-st element is smaller than $$$AVG$$$.Let's call an array of $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ bad, if at least one of its non-empty subsequences is terrible, and good otherwise.You are given an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Find the minimum number of elements that you have to delete from it to obtain a good array.An array is a subsequence of another array if it can be obtained from it by deletion of several (possibly, zero or all) elements.
For each testcase, print the minimum number of elements that you have to delete from it to obtain a good array.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the size of $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of array $$$a$$$. In each testcase for any $$$1 \le i \lt n$$$ it is guaranteed that $$$a_i \le a_{i+1}$$$. It is guaranteed that the sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,300
train_084.jsonl
1685b7530b86ed69b16a9bee6b9baf83
256 megabytes
["4\n3\n1 2 3\n5\n1 4 4 5 6\n6\n7 8 197860736 212611869 360417095 837913434\n8\n6 10 56026534 405137099 550504063 784959015 802926648 967281024"]
PASSED
import sys input = sys.stdin.buffer.readline def finder(A, x, l, r): if A[r] < x: return r+1 if A[l] >= x: return l s = l e = r #A[s] < x <= A[e] while s+1 < e: m = (s+e)//2 if A[m] < x: s, e = m, e else: s, e = s, m return e def process(A): n = len(A) if n <= 2 or A[-1]==A[0]: sys.stdout.write(f'0\n') return answer = n-2 for s in range(n): if s==0 or A[s] > A[s-1]: entry = s if s >= answer: break s1 = s+1 while s1+1 < n: x = 2*A[s1]-A[s] s2 = finder(A, x, s1+1, n-1) entry+=(s2-s1-1) if entry >= answer: break s1 = s2 answer = min(answer, entry) print(answer) return t = int(input()) for i in range(t): n = int(input()) A = [int(x) for x in input().split()] process(A)
1637678100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nNO\nNO\nYES\nYES\nNO"]
6d5aefc5a08194e35826764d60c8db3c
NoteIn the first test case, an awesome subsequence of $$$s$$$ is $$$[ab, cc, ba]$$$
Mihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.You are given a list $$$s$$$ of $$$n$$$ non-empty strings of length at most $$$3$$$, representing the scenes of Mihai's movie.A subsequence of $$$s$$$ is called awesome if it is non-empty and the concatenation of the strings in the subsequence, in order, is a palindrome.Can you help Mihai check if there is at least one awesome subsequence of $$$s$$$?A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.A sequence $$$a$$$ is a non-empty subsequence of a non-empty sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero, but not all) elements.
For each test case, print "YES" if there is an awesome subsequence of $$$s$$$, or "NO" otherwise (case insensitive).
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of scenes in the movie. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single non-empty string $$$s_i$$$ of length at most $$$3$$$, consisting of lowercase Latin letters. 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,700
train_093.jsonl
025f21716a3c704f5d6b0869b0a6f57c
512 megabytes
["6\n\n5\n\nzx\n\nab\n\ncc\n\nzx\n\nba\n\n2\n\nab\n\nbad\n\n4\n\nco\n\ndef\n\norc\n\nes\n\n3\n\na\n\nb\n\nc\n\n3\n\nab\n\ncd\n\ncba\n\n2\n\nab\n\nab"]
PASSED
import re for _ in range(int(input())): n = int(input()) arr = [] for i in range(n): arr.append(input()) tst = [[arr[0], set(), set(), set()]] if arr[0] == arr[0][::-1]: print("YES") continue flag = False for i in range(1, n): tst.append([arr[i], tst[i-1][1], tst[i-1][2],tst[i-1][3]]) if len(arr[i-1]) == 2: tst[-1][1].add(arr[i-1]) elif len(arr[i-1]) == 3: tst[-1][2].add(arr[i - 1]) tst[-1][3].add(arr[i - 1][:-1]) else: flag = True break item = arr[i] if len(arr[i]) == 2: item = arr[i] twos = tst[i][1] threes = tst[i][2] tthree = tst[i][3] temp = item[::-1] if temp == item: flag = True break if temp in twos: flag = True break if temp in tthree: flag = True break else: item = arr[i] twos = tst[i][1] threes = tst[i][2] tthree = tst[i][3] temp = item[::-1] if temp == item: flag = True break if temp in threes: flag = True break # tst 2 ba , cab , bac tst2 = temp[:-1] if tst2 in twos: flag = True break if flag: print("YES") continue print("NO") # for item, twos, threes,tthree in tst: # if len(item) == 2: # temp = item[::-1] # if temp == item: # flag = True # break # if temp in twos: # flag = True # break # if temp in tthree: # flag = True # break # else: # temp = item[::-1] # if temp == item: # flag = True # break # if temp in threes: # flag = True # break # # tst 2 ba , cab , bac # tst2 = temp[:-1] # if tst2 in twos: # flag = True # break # if flag: # print("YES") # continue # else: # print("NO") #
1642862100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\n3\n1\n3\n0\n0\n2\n1\n3\n4\n9\n2"]
728e0e5e5d8350a2b79e6a4b5bef407b
NoteThe answer for the first test case was considered above.The answer for the second test case was considered above.In the third test case, it's enough to add to the right the digit $$$4$$$ — the number $$$6$$$ will turn into $$$64$$$.In the fourth test case, let's add to the right the digit $$$8$$$ and then erase $$$7$$$ and $$$5$$$ — the taken number will turn into $$$8$$$.The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move.In the seventh test case, you can delete first of all the digit $$$3$$$ (the result is $$$01$$$) and then the digit $$$0$$$ (the result is $$$1$$$).
You are given an integer $$$n$$$. In $$$1$$$ move, you can do one of the following actions: erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); add one digit to the right. The actions may be performed in any order any number of times.Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number $$$301$$$ the digit $$$3$$$, the result is the number $$$01$$$ (not $$$1$$$).You need to perform the minimum number of actions to make the number any power of $$$2$$$ (i.e. there's an integer $$$k$$$ ($$$k \ge 0$$$) such that the resulting number is equal to $$$2^k$$$). The resulting number must not have leading zeroes.E.g. consider $$$n=1052$$$. The answer is equal to $$$2$$$. First, let's add to the right one digit $$$4$$$ (the result will be $$$10524$$$). Then let's erase the digit $$$5$$$, so the result will be $$$1024$$$ which is a power of $$$2$$$.E.g. consider $$$n=8888$$$. The answer is equal to $$$3$$$. Let's erase any of the digits $$$8$$$ three times. The result will be $$$8$$$ which is a power of $$$2$$$.
For each test case, output in a separate line one integer $$$m$$$ — the minimum number of moves to transform the number into any power of $$$2$$$.
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 one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).
standard output
standard input
PyPy 3-64
Python
1,300
train_103.jsonl
d895ba5787b15bdccc74fbbb6874a733
256 megabytes
["12\n1052\n8888\n6\n75\n128\n1\n301\n12048\n1504\n6656\n1000000000\n687194767"]
PASSED
from heapq import heapify, heappush, heappop from collections import Counter, defaultdict, deque from queue import PriorityQueue from itertools import combinations, product, permutations from bisect import bisect_left, bisect_right from functools import lru_cache from sys import stdin, stdout # for input /output import copy import math import array as arr from heapq import heappop, heappush import time # import sys # sys.setrecursionlimit(100000) #################### # stdin = open("testcase.txt") # def input(): # return stdin.readline().strip() ##################################################################### class FastIO: @classmethod def input(cls): from sys import stdin x = stdin.buffer.readline().decode().strip() return x @classmethod def integer_list(cls): return list(map(int, cls.input().split())) @classmethod def print(cls, s = "", end = "\n"): from sys import stdout stdout.write(str(s) + end) @classmethod def flush(cls): from sys import stdout stdout.flush() #################################################################### class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" """ initial default value for each node """ """ func which you want to apply to range """ 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[2*i], self.data[2*i + 1]) def __delitem__(self, idx): """ delete item set item value to its default """ self[idx] = self._default def __getitem__(self, idx): """ geting item by inx """ return self.data[idx + self._size] def __setitem__(self, idx, value): """ changing seting value to given index""" """ apply function to range """ 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) ##################################################################### class BinaryIndexTree(object): """ use one indexing """ def __init__(self, nums): n = len(nums) self._len = len(nums) self.nums = [0 for _ in range(n+1)] self.N = [0 for _ in range(n+1)] for i, v in enumerate(nums): self.__setitem__(i+1, v) def _lowbit(self, a): return a & -a def __setitem__(self, i, val): diff = val - self.nums[i] self.nums[i] = val while i < len(self.N): self.N[i] += diff i += self._lowbit(i) def __getitem__(self, i): # return sum up 0 to i ret = 0 while i > 0: ret += self.N[i] i -= self._lowbit(i) return ret ###################################################################### class DisJointSetsRank(): def __init__(self,N): # Initially, all elements are single element subsets self._parents = [node for node in range(N)] self._ranks = [1 for _ in range(N)] def find(self, u): while u != self._parents[u]: # path compression technique self._parents[u] = self._parents[self._parents[u]] u = self._parents[u] return u def connected(self, u, v): return self.find(u) == self.find(v) def union(self, u, v): # Union by rank optimization root_u, root_v = self.find(u), self.find(v) if root_u == root_v: return True if self._ranks[root_u] > self._ranks[root_v]: self._parents[root_v] = root_u elif self._ranks[root_v] > self._ranks[root_u]: self._parents[root_u] = root_v else: self._parents[root_u] = root_v self._ranks[root_v] += 1 return False ####################################################################### def integer_list(): return list(map(int, input().split())) def pprint(matrix): for i in range(len(matrix)): print(*matrix[i]) ##################################################### #test case section """ 1 - 5 9 10 1 2 7 0 1 1 """ ############################################################# # for manipulating 0 for runing to your system 1 for online MOD = 10**9+7 ONLINE_JUDGE = 1 def match_seq(power_2, s): i = j = 0 while i < len(power_2) and j < len(s): if power_2[i] == s[j]: i += 1 j += 1 else: j += 1 deleted_char = len(s) - i to_add = len(power_2) - i return deleted_char + to_add def main(): t = int(input()) # t = 1 powers = [] for i in range(61): num = str(2**i) powers.append(num) # print(powers) for _ in range(t): n = input() lst = [] k = len(n) ans = float('inf') for ele in powers: ans = min( ans , match_seq(ele, n)) print(ans) ############################################### if ONLINE_JUDGE: input = lambda : stdin.buffer.readline().decode().strip() else: stdin = open("testcase.txt") input = lambda : stdin.readline().strip() main()
1629297300
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
1 second
["2", "0", "Impossible"]
4147fef7a151c52e92c010915b12c06b
null
You are given string s consists of opening and closing brackets of four kinds &lt;&gt;, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace &lt; by the bracket {, but you can't replace it by ) or &gt;.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings &lt;s1&gt;s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]&lt;&gt;]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.
If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.
The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.
standard output
standard input
Python 3
Python
1,400
train_015.jsonl
f2bee33273d4cf388ebf1960543f6567
256 megabytes
["[&lt;}){}", "{()}[]", "]]"]
PASSED
k, s = 0, [] for q in input(): i = '[{<(]}>)'.find(q) if i > 3: if not s: s = 1 break if s.pop() != i - 4: k += 1 else: s += [i] print('Impossible' if s else k) # Made By Mostafa_Khaled
1451055600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 1 0 -1 \n1 1 2 2 1 0 2 6 \n3 0 1 4 3 \n1 0 -1 -1 -1 -1 -1 -1 \n2 1 0 2 -1 -1"]
18d19440e6df7316af0682ce99911738
NoteIn the first set of example inputs, $$$n=3$$$: to get $$$\mathrm{MEX}=0$$$, it is enough to perform one increment: $$$a_1$$$++; to get $$$\mathrm{MEX}=1$$$, it is enough to perform one increment: $$$a_2$$$++; $$$\mathrm{MEX}=2$$$ for a given array, so there is no need to perform increments; it is impossible to get $$$\mathrm{MEX}=3$$$ by performing increments.
Dmitry has an array of $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$.In one operation, Dmitry can choose any index $$$j$$$ ($$$1 \le j \le n$$$) and increase the value of the element $$$a_j$$$ by $$$1$$$. He can choose the same index $$$j$$$ multiple times.For each $$$i$$$ from $$$0$$$ to $$$n$$$, determine whether Dmitry can make the $$$\mathrm{MEX}$$$ of the array equal to exactly $$$i$$$. If it is possible, then determine the minimum number of operations to do it.The $$$\mathrm{MEX}$$$ of the array is equal to the minimum non-negative integer that is not in the array. For example, the $$$\mathrm{MEX}$$$ of the array $$$[3, 1, 0]$$$ is equal to $$$2$$$, and the array $$$[3, 3, 1, 4]$$$ is equal to $$$0$$$.
For each test case, output $$$n + 1$$$ integer — $$$i$$$-th number is equal to the minimum number of operations for which you can make the array $$$\mathrm{MEX}$$$ equal to $$$i$$$ ($$$0 \le i \le n$$$), or -1 if this cannot be done.
The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The descriptions of the test cases follow. The first line of the description of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_093.jsonl
4f81f4db3e705bbbe22ad9af00a44a3a
256 megabytes
["5\n3\n0 1 3\n7\n0 1 2 3 4 3 2\n4\n3 0 0 0\n7\n4 6 2 3 5 0 5\n5\n4 0 1 0 4"]
PASSED
INF = float('inf') def solve(): n = int(input()) mmin = n + 1 a = [] cnt = [0] * (n + 1) for i in input().split(): i = int(i) mmin = min(mmin, i) a.append(i) cnt[i] += 1 a.sort() if mmin > 0: print(0, end = ' ') i = 1 while i <= n: print(-1, end = ' ') i += 1 print() return '' i = 0 cntM = 0 prevM = [] pos = -1 while i <= n: if cntM < 0: while i <= n: print(-1, end = ' ') i += 1 print() return '' print(cntM + cnt[i], end = ' ') if cnt[i] == 0: if pos == -1: i += 1 while i <= n: print(-1, end = ' ') i += 1 print() return '' prevM[pos][1] -= 1 cntM += i - prevM[pos][0] while pos >= 0 and prevM[pos][1] == 0: pos -= 1 else: if cnt[i] > 1: prevM.append([i, cnt[i] - 1]) pos = len(prevM) - 1 i += 1 print() t = int(input()) while t: t -= 1 solve()
1640010900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["aaa\n\naaab\n\nabba\n\nbba\n\nabaaa\n\naabba"]
d341e5848836563953b3ec204cd59acc
null
This is an interactive problem.After completing the last level of the enchanted temple, you received a powerful artifact of the 255th level. Do not rush to celebrate, because this artifact has a powerful rune that can be destroyed with a single spell $$$s$$$, which you are going to find. We define the spell as some non-empty string consisting only of the letters a and b.At any time, you can cast an arbitrary non-empty spell $$$t$$$, and the rune on the artifact will begin to resist. Resistance of the rune is the edit distance between the strings that specify the casted spell $$$t$$$ and the rune-destroying spell $$$s$$$.Edit distance of two strings $$$s$$$ and $$$t$$$ is a value equal to the minimum number of one-character operations of replacing, inserting and deleting characters in $$$s$$$ to get $$$t$$$. For example, the distance between ababa and aaa is $$$2$$$, the distance between aaa and aba is $$$1$$$, the distance between bbaba and abb is $$$3$$$. The edit distance is $$$0$$$ if and only if the strings are equal.It is also worth considering that the artifact has a resistance limit  — if you cast more than $$$n + 2$$$ spells, where $$$n$$$ is the length of spell $$$s$$$, the rune will be blocked.Thus, it takes $$$n + 2$$$ or fewer spells to destroy the rune that is on your artifact. Keep in mind that the required destructive spell $$$s$$$ must also be counted among these $$$n + 2$$$ spells.Note that the length $$$n$$$ of the rune-destroying spell $$$s$$$ is not known to you in advance. It is only known that its length $$$n$$$ does not exceed $$$300$$$.
null
null
standard output
standard input
Python 3
Python
2,300
train_018.jsonl
0e06aa3a94bb6c99f3aebb47cbede5c0
256 megabytes
["2\n\n2\n\n1\n\n2\n\n3\n\n0"]
PASSED
from sys import stdout def f(x): if x == 0: exit(0) stdout.flush() print('a') x1 = int(input()) f(x1) if x1 == 300: print('b' * 300) exit(0) lenz = x1 + 1 print('a' * lenz) x = int(input()) f(x) ca = lenz - x patt = '' c1 = 1 c2 = ca if ca == 0: print('b' * (lenz - 1)) x = int(input()) f(x) else: while c2: print(patt + 'b' * c1 + 'a' * c2) x = int(input()) f(x) if x == lenz - c2 - len(patt) - c1: c1 += 1 else: c1 -= 1 patt += 'b' * c1 patt += 'a' c1 = 1 c2 -= 1 print(patt + 'b' * (lenz - len(patt))) x = int(input()) f(x)
1577198100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["7\n2000000000\n0"]
c8da5d7debf5d7a6fc04bb3a68cda2f0
NoteIn the first test case, we can achieve total intersection $$$5$$$, for example, using next strategy: make $$$[al_1, ar_1]$$$ from $$$[1, 2]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps; make $$$[al_2, ar_2]$$$ from $$$[1, 2]$$$ to $$$[1, 3]$$$ in $$$1$$$ step; make $$$[bl_1, br_1]$$$ from $$$[3, 4]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps; make $$$[bl_2, br_2]$$$ from $$$[3, 4]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps. In result, $$$I = \text{intersection_length}([al_1, ar_1], [bl_1, br_1]) + \text{intersection_length}([al_2, ar_2], [bl_2, br_2]) + \\ + \text{intersection_length}([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5$$$In the second test case, we can make $$$[al_1, ar_1] = [0, 1000000000]$$$ in $$$1000000000$$$ steps and $$$[bl_1, br_1] = [0, 1000000000]$$$ in $$$1000000000$$$ steps.In the third test case, the total intersection $$$I$$$ is already equal to $$$10 &gt; 3$$$, so we don't need to do any steps.
You are given two lists of segments $$$[al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n]$$$ and $$$[bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n]$$$.Initially, all segments $$$[al_i, ar_i]$$$ are equal to $$$[l_1, r_1]$$$ and all segments $$$[bl_i, br_i]$$$ are equal to $$$[l_2, r_2]$$$.In one step, you can choose one segment (either from the first or from the second list) and extend it by $$$1$$$. In other words, suppose you've chosen segment $$$[x, y]$$$ then you can transform it either into $$$[x - 1, y]$$$ or into $$$[x, y + 1]$$$.Let's define a total intersection $$$I$$$ as the sum of lengths of intersections of the corresponding pairs of segments, i.e. $$$\sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}$$$. Empty intersection has length $$$0$$$ and length of a segment $$$[x, y]$$$ is equal to $$$y - x$$$.What is the minimum number of steps you need to make $$$I$$$ greater or equal to $$$k$$$?
Print $$$t$$$ integers — one per test case. For each test case, print the minimum number of step you need to make $$$I$$$ greater or equal to $$$k$$$.
The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the length of lists and the minimum required total intersection. The second line of each test case contains two integers $$$l_1$$$ and $$$r_1$$$ ($$$1 \le l_1 \le r_1 \le 10^9$$$) — the segment all $$$[al_i, ar_i]$$$ are equal to initially. The third line of each test case contains two integers $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_2 \le r_2 \le 10^9$$$) — the segment all $$$[bl_i, br_i]$$$ are equal to initially. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,100
train_029.jsonl
8a691ca2ec3cfb2dbef97c283dec64ac
256 megabytes
["3\n3 5\n1 2\n3 4\n2 1000000000\n1 1\n999999999 999999999\n10 3\n5 10\n7 8"]
PASSED
for _ in range(int(input())): n,k=map(int,input().split()) l1,r1=map(int,input().split()) l2,r2=map(int,input().split()) over=min(r1,r2)-max(l1,l2) moves=0 #Case1: Already overlapped if (l1,r1)==(l2,r2): if (r1-l1)*n>=k: print(0) else: k-=(r1-l1)*n print(2*k) elif over>0: over*=n if over>=k: print(0) else: o=max(r1,r2)-min(l1,l2)-over//n if over+o*n>=k: print(k-over) else: moves+=o*n over+=o*n print(moves+(k-over)*2) #Case 2: No overlap(Here the fun begins) else: d=-1*over o=max(r1,r2)-min(l1,l2) x=k//o k=k%o if n>x: moves+=(x)*(d+o) if d<k or x==0: moves+=d+k else: moves+=2*k else: moves+=n*(d+o)+((x-n)*o+k)*2 print(moves)
1596033300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2\n3 2", "-1", "0"]
a0bceeb856fd95ece1990a0f98658d1a
null
Joseph really likes the culture of Japan. Last year he learned Japanese traditional clothes and visual arts and now he is trying to find out the secret of the Japanese game called Nonogram.In the one-dimensional version of the game, there is a row of $$$n$$$ empty cells, some of which are to be filled with a pen. There is a description of a solution called a profile — a sequence of positive integers denoting the lengths of consecutive sets of filled cells. For example, the profile of $$$[4, 3, 1]$$$ means that there are sets of four, three, and one filled cell, in that order, with at least one empty cell between successive sets. A suitable solution for $$$n = 12$$$ and $$$p = [4, 3, 1]$$$. A wrong solution: the first four filled cells should be consecutive. A wrong solution: there should be at least one empty cell before the last filled cell. Joseph found out that for some numbers $$$n$$$ and profiles $$$p$$$ there are lots of ways to fill the cells to satisfy the profile. Now he is in the process of solving a nonogram consisting of $$$n$$$ cells and a profile $$$p$$$. He has already created a mask of $$$p$$$ — he has filled all the cells that must be filled in every solution of the nonogram. The mask for $$$n = 12$$$ and $$$p = [4, 3, 1]$$$: all the filled cells above are filled in every solution. After a break, he lost the source profile $$$p$$$. He only has $$$n$$$ and the mask $$$m$$$. Help Joseph find any profile $$$p'$$$ with the mask $$$m$$$ or say that there is no such profile and Joseph has made a mistake.
If there is no profile with the mask $$$m$$$, output the number $$$-1$$$. Otherwise, on the first line, output an integer $$$k$$$ — the number of integers in the profile $$$p'$$$. On the second line, output $$$k$$$ integers of the profile $$$p'$$$.
The only line contains a string $$$m$$$ — the mask of the source profile $$$p$$$. The length of $$$m$$$ is $$$n$$$ ($$$1 \le n \le 100\,000$$$). The string $$$m$$$ consists of symbols # and _ — denoting filled and empty cells respectively.
standard output
standard input
PyPy 3
Python
2,700
train_099.jsonl
39bca825532bbcec505c933ae44d5f62
512 megabytes
["__#_____", "_#", "___"]
PASSED
import copy from collections import defaultdict as dd from collections import deque import math import sys import os # sys.setrecursionlimit(10**5) # This uses something like 128 MB RAM. I guess only play with this if I expect recursion depth problems. #region set up dbg commands # set up debug stuff. # remember .bashrc should contain `export PYTHON_CONTEST_HELPER="dummy"` if os.environ.get("PYTHON_CONTEST_HELPER"): OUT_RED_BOLD = "\033[31;1m" OUT_GREEN = "\033[32m" OUT_RESET = "\033[0m" OUT_BOLD = "\033[;1m" OUT_CYAN = "\033[36;1m" OUT_PURPLE = "\033[35;1m" OUT_YELLOW = "\033[33;1m" OUT_BACKGROUND = "\033[41;30;1m" def dbgBase(*args, **kwargs): color_helper = kwargs.pop('color', OUT_CYAN) print(f"{OUT_RED_BOLD}{sys._getframe().f_back.f_back.f_lineno: >20} {OUT_BOLD}: {color_helper}", end='', file=sys.stderr) end_maybe = kwargs.get('end', '\n') kwargs['end']=f"{OUT_RESET}{end_maybe}" print(*args, file=sys.stderr, **kwargs) def dbg(*args, **kwargs): dbgBase(color=OUT_CYAN, *args, **kwargs) dbgB = dbg def dbgG(*args, **kwargs): dbgBase(color=OUT_GREEN, *args, **kwargs) def dbgP(*args, **kwargs): dbgBase(color=OUT_PURPLE, *args, **kwargs) def dbgY(*args, **kwargs): dbgBase(color=OUT_YELLOW, *args, **kwargs) def dbgBackground(*args, **kwargs): dbgBase(color=OUT_BACKGROUND, *args, **kwargs) def el(n=1): print('\n'*n, file=sys.stderr, end='') else: def dbg(*args, **kwargs): pass def dbgB(*args, **kwargs): pass def dbgG(*args, **kwargs): pass def dbgP(*args, **kwargs): pass def dbgY(*args, **kwargs): pass def dbgBackground(*args, **kwargs): pass def el(n=1): pass #endregion #region FastIO 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") #endregion def nn(): return int(input()) def li(): return list(input()) def lm(): return list(map(int, input().split())) # To print while flushing output for interactive problems: # print(x, flush=True) ######################################################################### # Problem specific code usually goes below this line. ######################################################################### # ! Read the sample cases before writing code! def solve(testID): dat = input() dbg(dat) min_space = -1 if dat[0] == "#" or dat[-1] == "#": min_space = 0 curr_cell = 0 total_blocks = [] while curr_cell < len(dat): curr_spaces = 0 while curr_cell < len(dat) and dat[curr_cell] == "_": curr_spaces += 1 curr_cell += 1 if curr_spaces != 0 and (min_space == -1 or curr_spaces < min_space): min_space = curr_spaces curr_block_size = 0 start_cell = curr_cell while curr_cell < len(dat) and dat[curr_cell] == "#": curr_block_size += 1 curr_cell += 1 if curr_block_size > 0: total_blocks.append((start_cell, curr_block_size)) dbgB(min_space) dbgB(total_blocks) if len(total_blocks) == 0: print(0) print() return for slack in range(min_space + 1): last_allowed_spot = 0 success = True for pos, block_size in total_blocks: dbgP(slack, pos, block_size, last_allowed_spot) prior_empty_space = pos - last_allowed_spot space_to_fill = prior_empty_space - slack dbgY(space_to_fill) if space_to_fill < 0: success = False break if space_to_fill > 0 and slack == 0: success = False break if space_to_fill == 1: success = False break if space_to_fill % 2 == 1 and slack == 1: success = False break last_allowed_spot = pos + block_size + 1 dbgP(last_allowed_spot) if not success: continue remaining_space = len(dat) - last_allowed_spot + 1 - slack dbgG(remaining_space) if (remaining_space > 0 and slack == 0) or remaining_space < 0 or remaining_space == 1 or (remaining_space % 2 == 1 and slack == 1): success = False continue break if not success: print(-1) return dbgY(slack) profile_ints = [] last_allowed_spot = 0 for pos, block_size in total_blocks: space_to_fill = pos - last_allowed_spot - slack dbgB(space_to_fill) if space_to_fill % 2 == 1: profile_ints.append(2) space_to_fill -= 3 while space_to_fill > 0: profile_ints.append(1) space_to_fill -= 2 profile_ints.append(block_size + slack) last_allowed_spot = pos + block_size + 1 remaining_space = len(dat) - last_allowed_spot + 1 - slack dbgP(remaining_space) if remaining_space > 0: if remaining_space % 2 == 1: profile_ints.append(2) remaining_space -= 3 while remaining_space > 0: profile_ints.append(1) remaining_space -= 2 dbgG(profile_ints) print(len(profile_ints)) print(" ".join([str(x) for x in profile_ints])) return T = 1 # dbgBackground("Loading num cases!!!!!"); T = nn() # ! Comment this out for single-case problems! for testID in range(1, T+1): el() dbgBackground(f"Case {testID}") solve(testID)
1617523500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 2", "0 1", "3 1"]
d3bdb328e4d37de374cb3201c2a86eee
NoteThe simple cycle is a cycle that doesn't contain any vertex twice.
After Vitaly was expelled from the university, he became interested in the graph theory.Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.Two ways to add edges to the graph are considered equal if they have the same sets of added edges.Since Vitaly does not study at the university, he asked you to help him with this task.
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
The first line of the input contains two integers n and m ( — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
standard output
standard input
Python 3
Python
2,000
train_022.jsonl
7d1726ad951b396535227c8f1de213b7
256 megabytes
["4 4\n1 2\n1 3\n4 2\n4 3", "3 3\n1 2\n2 3\n3 1", "3 0"]
PASSED
n, m = [int(x) for x in input().split()] E = {i:[] for i in range(n)} for i in range(m): u, v = [int(x)-1 for x in input().split()] E[v].append(u) E[u].append(v) def dfs(): visited = [False for i in range(n)] colour = [0 for i in range(n)] ans = 0 for v in range(n): if visited[v]: continue stack = [(v, 0)] part = [0, 0] while stack: node, c = stack.pop() if not visited[node]: part[c] += 1 visited[node] = True colour[node] = c stack.extend((u,c^1) for u in E[node]) elif c != colour[node]: return (0, 1) ans += (part[0]*(part[0] - 1) + part[1]*(part[1] - 1)) // 2 return (1, ans) if m == 0: print(3, n*(n-1)*(n-2)//6) elif max(len(E[v]) for v in E) == 1: print(2, m*(n-2)) else: ans = dfs() print(ans[0], ans[1])
1435676400
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["1 1", "1 1", "1 1", "3 4"]
6b049bd466b050f2dd0a305a381bc0bf
NoteThe picture below shows the rectangles in the first and second samples. The possible answers are highlighted. The picture below shows the rectangles in the third and fourth samples.
You are given $$$n$$$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $$$(n-1)$$$ of the given $$$n$$$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.Find any point with integer coordinates that belongs to at least $$$(n-1)$$$ given rectangles.
Print two integers $$$x$$$ and $$$y$$$ — the coordinates of any point that belongs to at least $$$(n-1)$$$ given rectangles.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 132\,674$$$) — the number of given rectangles. Each the next $$$n$$$ lines contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9 \le x_1 &lt; x_2 \le 10^9$$$, $$$-10^9 \le y_1 &lt; y_2 \le 10^9$$$) — the coordinates of the bottom left and upper right corners of a rectangle.
standard output
standard input
PyPy 2
Python
1,600
train_008.jsonl
bf69563439d55a97172689024f59060f
256 megabytes
["3\n0 0 1 1\n1 1 2 2\n3 0 4 1", "3\n0 0 1 1\n0 1 1 2\n1 0 2 1", "4\n0 0 5 5\n0 0 4 4\n1 1 4 4\n1 1 4 4", "5\n0 0 10 8\n1 2 6 7\n2 3 5 6\n3 4 4 5\n8 1 9 2"]
PASSED
from sys import stdin def max_arr(a): tem = [(-float('inf'), -float('inf'), float('inf'), float('inf'))] for i in range(len(a) - 1, -1, -1): tem.append( (max(tem[-1][0], a[i][0]), max(tem[-1][1], a[i][1]), min(tem[-1][2], a[i][2]), min(tem[-1][3], a[i][3]))) return tem[::-1] valid = lambda p: p[2] - p[0] > -1 and p[3] - p[1] > -1 rints = lambda: [int(x) for x in stdin.readline().split()] rints_2d = lambda n: [rints() for _ in range(n)] n = int(input()) a = rints_2d(n) cum = max_arr(a) if valid(cum[0]): print('%d %d' % (cum[0][0], cum[0][1])) else: tem = [(-float('inf'), -float('inf'), float('inf'), float('inf'))] for i in range(n): cur = (max(tem[-1][0], cum[i + 1][0]), max(tem[-1][1], cum[i + 1][1]), min(tem[-1][2], cum[i + 1][2]), min(tem[-1][3], cum[i + 1][3])) if valid(cur): print('%d %d' % (cur[0], cur[1])) exit() else: tem.append((max(tem[-1][0], a[i][0]), max(tem[-1][1], a[i][1]), min(tem[-1][2], a[i][2]), min(tem[-1][3], a[i][3])))
1535387700
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
0.5 second
["33 109"]
9c9235394dceba81c8af6be02aa54fcc
null
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.For example, if X = 10910 = 11011012, Y = 4110 = 1010012, then: X xor Y  =  6810  =  10001002. Write a program, which takes two non-negative integers A and B as an input and finds two non-negative integers X and Y, which satisfy the following conditions: A = X + Y B  =  X xor Y, where xor is bitwise exclusive or. X is the smallest number among all numbers for which the first two conditions are true.
The only output line should contain two integer non-negative numbers X and Y. Print the only number -1 if there is no answer.
The first line contains integer number A and the second line contains integer number B (0 ≤ A, B ≤ 264 - 1).
standard output
standard input
PyPy 3
Python
1,700
train_002.jsonl
d1a84608421f164b8f3cc10e5767ff36
256 megabytes
["142\n76"]
PASSED
a = int(input()) b = int(input()) k = a - b if k % 2: print(-1) exit(0) k >>= 1 if k < 0: print(-1) exit(0) print(k, a - k)
1302609600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"]
27baf9b1241c0f8e3a2037b18f39fe34
NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold: at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.
Print the resulting hashtags in any of the optimal solutions.
The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.
standard output
standard input
Python 3
Python
1,800
train_023.jsonl
f1d9236bcb4d08dedd2a6468e7411e2e
256 megabytes
["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"]
PASSED
def cut_to_lexicographic(word_bigger, word_smaller): if len(word_bigger) > len(word_smaller): return word_bigger[:len(word_smaller)] for l in range(len(word_bigger)): if word_bigger[l] != word_smaller[l]: return word_smaller[:l] return word_bigger n = int(input()) array = [str(input()) for c in range(n)] b = n - 2 while b > -1: if array[b + 1] >= array[b]: b = b - 1 else: array[b] = cut_to_lexicographic(array[b], array[b+1]) print("\n".join(array))
1487930700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["YES", "NO", "NO"]
600b322b10cbde66ad8ffba5dc7d84e6
NoteThe graph corresponding to the first example:The graph corresponding to the second example:The graph corresponding to the third example:
As the name of the task implies, you are asked to do some work with segments and trees.Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.You are given $$$n$$$ segments $$$[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$$$, $$$l_i &lt; r_i$$$ for every $$$i$$$. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.Let's generate a graph with $$$n$$$ vertices from these segments. Vertices $$$v$$$ and $$$u$$$ are connected by an edge if and only if segments $$$[l_v, r_v]$$$ and $$$[l_u, r_u]$$$ intersect and neither of it lies fully inside the other one.For example, pairs $$$([1, 3], [2, 4])$$$ and $$$([5, 10], [3, 7])$$$ will induce the edges but pairs $$$([1, 2], [3, 4])$$$ and $$$([5, 7], [3, 10])$$$ will not.Determine if the resulting graph is a tree or not.
Print "YES" if the resulting graph is a tree and "NO" otherwise.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of segments. The $$$i$$$-th of the next $$$n$$$ lines contain the description of the $$$i$$$-th segment — two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i &lt; r_i \le 2n$$$). It is guaranteed that all segments borders are pairwise distinct.
standard output
standard input
PyPy 2
Python
2,100
train_053.jsonl
e7c658c57be950068a07962ba23666b5
256 megabytes
["6\n9 12\n2 11\n1 3\n6 10\n5 7\n4 8", "5\n1 3\n2 4\n5 9\n6 8\n7 10", "5\n5 8\n3 6\n2 9\n7 10\n1 4"]
PASSED
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 A = [0]*(2 * n) L = [] R = [] for i in range(n): l = inp[ii] - 1; ii += 1 r = inp[ii] - 1; ii += 1 L.append(l) R.append(r) A[l] = i A[r] = ~i class segtree: def __init__(self, n): m = 1 while m < n: m *= 2 self.m = m self.data = [0]*(2 * m) def add(self, i): i += self.m while i: self.data[i] += 1 i >>= 1 def finder(self, l, r): m = self.m data = self.data l += m r += m cand = [] while l < r: if l & 1: if data[l]: cand.append(l) l += 1 if r & 1: r -= 1 if data[r]: cand.append(r) l >>= 1 r >>= 1 ans = [] for i in cand: while i < m and data[i]: if data[2 * i]: cand.append(2 * i) i = 2 * i + 1 if data[i]: ans.append(i - m) return ans coupl = [[] for _ in range(n)] seg = segtree(2 * n) edges = 0 for j in range(2 * n): i = A[j] if i >= 0: for r_ind in seg.finder(j, R[i]): node = ~A[r_ind] coupl[i].append(node) coupl[node].append(i) edges += 1 if edges == n: print 'NO' sys.exit() seg.add(R[i]) if edges != n - 1: print 'NO' sys.exit() found = [0]*n found[0] = 1 bfs = [0] for node in bfs: for nei in coupl[node]: if not found[nei]: found[nei] = 1 bfs.append(nei) if all(found): print 'YES' else: print 'NO'
1576766100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
10c9b2d70030f7ed680297455d1f1bb0
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
standard output
standard input
Python 3
Python
1,300
train_002.jsonl
d4d3962c1c7559e61bf49f8d1b5ac2ba
256 megabytes
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
PASSED
for _ in range(int(input())): n=int(input()) s=input() s1=input() s=list(str(x) for x in s) s1=list(str(x) for x in s1) c=[] for i in range(n-1,-1,-1): if s[len(s)-1]==s1[i]: s=s[:len(s)-1] ##print(s,i) continue if int(s1[i])+int(s[0])==1: c.append(i+1) s=s[:i+1] for i in range(len(s)): if s[i]=='0': s[i]='1' else: s[i]='0' s=s[::-1] s=s[:len(s)-1] continue if s1[i]==s[0]: if s1[i]=='1': s[0]='0' c.append(1) else: c.append(1) s[0]='1' c.append(i + 1) s = s[:i + 1] ##print(s) for i in range(len(s)): if s[i] == '0': s[i] = '1' else: s[i] = '0' s = s[::-1] s=s[:len(s)-1] ##print(s) continue if len(c)==0: print(0) continue print(len(c),*c)
1595342100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2", "5", "20"]
b4341e1b0ec0b7341fdbe6edfe81a0d4
NoteIn the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to lfloor frac{100}{10} rfloor +  lfloor frac{100}{10} rfloor = 10 + 10 =  20.In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is .In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to .
Petya loves computer games. Finally a game that he's been waiting for so long came out!The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values ​​of for all i from 1 to n. The expression ⌊ x⌋ denotes the result of rounding the number x down to the nearest integer.At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.
The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using k or less improvement units.
The first line of the input contains two positive integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 107) — the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of n integers ai (0 ≤ ai ≤ 100), where ai characterizes the level of the i-th skill of the character.
standard output
standard input
Python 2
Python
1,400
train_004.jsonl
5bed3c1be610b42b888bf959b632ff60
256 megabytes
["2 4\n7 9", "3 8\n17 15 19", "2 2\n99 100"]
PASSED
n,k=map(int,raw_input().split()) t=map(int,raw_input().split()) li=[] for i in t: li+=[[10-i%10,i]] li.sort() for i in xrange(n): if(k>=li[i][0]): if(li[i][0]!=10): k-=li[i][0] li[i][1]+=li[i][0] else: break for i in xrange(n): while(k>9 and li[i][1]<100): li[i][1]+=10 k-=10 if(k<10): break s=0 for i in xrange(n): s+=li[i][1]/10 print s
1443430800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["18\n10\n0"]
4bcaa910cce687f0881a36231aa1a2c8
NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$.
Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty.
For each test case, print a single integer — the highest possible beauty.
The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. 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_097.jsonl
7cadc2c941678666d49d6b1410a69dee
256 megabytes
["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"]
PASSED
def compute(cycleSize, n): curr = n-1 res = 0 # print("n", n) for i in range(cycleSize-1): # print("add", curr) res += curr curr -= 1 # print("add", n-cycleSize//2) if cycleSize % 2 == 0: res += n - cycleSize//2 else: res += cycleSize//2 return res t = int(input()) for ti in range(t): n = int(input()) a = [int(e) for e in input().split(' ')] b = [int(e) for e in input().split(' ')] # if ti == 306: # print(a, b) # raise Exception(a, b) visited = set() edges = [None]*(n+1) for ai, bi in zip(a, b): edges[ai] = bi res = 0 cycles = [] for ai in a: if ai in visited: continue curr = ai l = 0 while l == 0 or curr != ai: visited.add(curr) curr = edges[curr] l += 1 # print("cycle size", l, ai) if l != 1: cycles.append(l) cycles = sorted(cycles) for cycle in cycles: c = compute(cycle, n) # print(cycle, n, c) res += c n -= cycle if cycle % 2 == 1: n += 1 # if t != 10000: print(res)
1652020500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4", "1", "0"]
ea6f55b3775076fcba6554b743b1a8ae
NoteIn the first sample there are four different valid pairs: p = "(", q = "))" p = "()", q = ")" p = "", q = "())" p = "", q = ")()" In the second sample the only way to obtain a desired string is choose empty p and q.In the third sample there is no way to get a valid sequence of brackets.
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109 + 7.
Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 109 + 7.
First line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively. The second line contains string s of length m consisting of characters '(' and ')' only.
standard output
standard input
PyPy 3
Python
2,000
train_036.jsonl
166da3d46ab92364324e17d8f14f3c43
256 megabytes
["4 1\n(", "4 4\n(())", "4 3\n((("]
PASSED
n, m = map(int, input().split()) s = input() mod = 10 ** 9 + 7 c, b, ans, d, k = 0, 0, 0, [[1]], n - m for i in s: c += (i == '(') * 2 - 1 b = min(c, b) for i in range(n - m): nd = d[-1][1:] + [0] * 2 for j in range(1, i + 2): nd[j] = (nd[j] + d[-1][j - 1]) % mod d.append(nd) for i in range(k + 1): for j in range(-b, min(k - i - c, i) + 1): ans = (ans + d[i][j] * d[k - i][j + c]) % mod print(ans)
1455986100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["99\n55\n11115", "385\n360\n792\n8360"]
b3108315889607dabcd3112bcfe3fb54
null
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is evenly divisible by d. At that, we assume that all ai's are greater than zero.Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives a1 sweets, the 2-nd one gives a2 sweets, ..., the n-th one gives an sweets. At the same time, for any i and j (1 ≤ i, j ≤ n) they want the GCD(ai, aj) not to be equal to 1. However, they also want the following condition to be satisfied: GCD(a1, a2, ..., an) = 1. One more: all the ai should be distinct.Help the friends to choose the suitable numbers a1, ..., an.
If there is no answer, print "-1" without quotes. Otherwise print a set of n distinct positive numbers a1, a2, ..., an. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them. Do not forget, please, that all of the following conditions must be true: For every i and j (1 ≤ i, j ≤ n): GCD(ai, aj) ≠ 1 GCD(a1, a2, ..., an) = 1 For every i and j (1 ≤ i, j ≤ n, i ≠ j): ai ≠ aj Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
The first line contains an integer n (2 ≤ n ≤ 50).
standard output
standard input
PyPy 3
Python
1,700
train_000.jsonl
7a21e907e5a05a060d05c5e7a9a905a4
256 megabytes
["3", "4"]
PASSED
def isprime(a): if(a==1 or a==0 or a==2 ): return 0 x=2 while x*x<=a: if a%x==0: return 0 x+=1 return 1 primes=[] m=1 cnt=0 for x in range(1,300): if(isprime(x)): primes.append(x) n=int(input()) if(n==2): print(-1) else : for i in range(0,n-1): print(2*primes[i]) m=m*primes[i] print(m)
1299513600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n2\n9\n1174\n1000000000000"]
e519e4495c9acef4c4a614aef73cb322
null
Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns": cells are numbered starting from one; cells are numbered from left to right by columns, and inside each column from top to bottom; number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \begin{matrix} 1 &amp; 4 &amp; 7 &amp; 10 &amp; 13 \\ 2 &amp; 5 &amp; 8 &amp; 11 &amp; 14 \\ 3 &amp; 6 &amp; 9 &amp; 12 &amp; 15 \\ \end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows": cells are numbered starting from one; cells are numbered from top to bottom by rows, and inside each row from left to right; number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \begin{matrix} 1 &amp; 2 &amp; 3 &amp; 4 &amp; 5 \\ 6 &amp; 7 &amp; 8 &amp; 9 &amp; 10 \\ 11 &amp; 12 &amp; 13 &amp; 14 &amp; 15 \\ \end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number $$$x$$$?
For each test case, output the cell number in the numbering "by rows".
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single line containing three integers $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le x \le n \cdot m$$$), where $$$n$$$ and $$$m$$$ are the number of rows and columns in the table, and $$$x$$$ is the cell number. Note that the numbers in some test cases do not fit into the $$$32$$$-bit integer type, so you must use at least the $$$64$$$-bit integer type of your programming language.
standard output
standard input
PyPy 3-64
Python
800
train_101.jsonl
5cb8253afe5729035dae4acb79573787
256 megabytes
["5\n1 1 1\n2 2 3\n3 5 11\n100 100 7312\n1000000 1000000 1000000000000"]
PASSED
for t in range(int(input())): n,m,k=map(int, input().split()) a=0 if int(k/n)==k/n: a = int(k/n) else: a = int(k/n)+1 k-=(int(k/n)*n) if k==0: k=n-1 else: k-=1 a+=(m*k) print(a)
1616682900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0\n8\n218"]
94ec011dc830661c226bd860b9d70de5
NoteIn the first test case, we can, for example, swap $$$a_3$$$ with $$$b_3$$$ and $$$a_4$$$ with $$$b_4$$$. We'll get arrays $$$a = [3, 3, 3, 3]$$$ and $$$b = [10, 10, 10, 10]$$$ with sum $$$3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0$$$.In the second test case, arrays already have minimum sum (described above) equal to $$$|1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10|$$$ $$$= 4 + 4 = 8$$$.In the third test case, we can, for example, swap $$$a_5$$$ and $$$b_5$$$.
You are given two arrays of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$.You can perform the following operation any number of times: Choose integer index $$$i$$$ ($$$1 \le i \le n$$$); Swap $$$a_i$$$ and $$$b_i$$$. What is the minimum possible sum $$$|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$$$ $$$+$$$ $$$|b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n|$$$ (in other words, $$$\sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$) you can achieve after performing several (possibly, zero) operations?
For each test case, print one integer — the minimum possible sum $$$\sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 4000$$$) — the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 25$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the array $$$b$$$.
standard output
standard input
Python 3
Python
800
train_092.jsonl
7516327b54b7793b095f76c3dbc30edc
256 megabytes
["3\n\n4\n\n3 3 10 10\n\n10 10 3 3\n\n5\n\n1 2 3 4 5\n\n6 7 8 9 10\n\n6\n\n72 101 108 108 111 44\n\n10 87 111 114 108 100"]
PASSED
for j in range(0,int(input())): n=int(input()) sum=0 l1=[int(x) for x in input().split()] l2=[int(x) for x in input().split()] for i in range(1,n): if(abs(l1[i]-l1[i-1])+abs(l2[i]-l2[i-1])>abs(l1[i-1]-l2[i])+abs(l2[i-1]-l1[i])): l1[i],l2[i]=l2[i],l1[i] sum+=(abs(l1[i]-l1[i-1])+abs(l2[i]-l2[i-1])) print(sum)
1649514900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "0", "2", "8"]
45c1dd4eeba668a454dabf0993cdecac
NoteIn the first test case, the only way to fill in the $$$\texttt{?}$$$s is to fill it in as such: 010111010 This can be accomplished by doing a single operation by choosing $$$(i,j)=(2,2)$$$.In the second test case, it can be shown that there is no sequence of operations that can produce that grid.
There is a grid with $$$r$$$ rows and $$$c$$$ columns, where the square on the $$$i$$$-th row and $$$j$$$-th column has an integer $$$a_{i, j}$$$ written on it. Initially, all elements are set to $$$0$$$. We are allowed to do the following operation: Choose indices $$$1 \le i \le r$$$ and $$$1 \le j \le c$$$, then replace all values on the same row or column as $$$(i, j)$$$ with the value xor $$$1$$$. In other words, for all $$$a_{x, y}$$$ where $$$x=i$$$ or $$$y=j$$$ or both, replace $$$a_{x, y}$$$ with $$$a_{x, y}$$$ xor $$$1$$$. You want to form grid $$$b$$$ by doing the above operations a finite number of times. However, some elements of $$$b$$$ are missing and are replaced with '?' instead.Let $$$k$$$ be the number of '?' characters. Among all the $$$2^k$$$ ways of filling up the grid $$$b$$$ by replacing each '?' with '0' or '1', count the number of grids, that can be formed by doing the above operation a finite number of times, starting from the grid filled with $$$0$$$. As this number can be large, output it modulo $$$998244353$$$.
Print a single integer representing the number of ways to fill up grid $$$b$$$ modulo $$$998244353$$$.
The first line contains two integers $$$r$$$ and $$$c$$$ ($$$1 \le r, c \le 2000$$$)  — the number of rows and columns of the grid respectively. The $$$i$$$-th of the next $$$r$$$ lines contain $$$c$$$ characters $$$b_{i, 1}, b_{i, 2}, \ldots, b_{i, c}$$$ ($$$b_{i, j} \in \{0, 1, ?\}$$$).
standard output
standard input
PyPy 3
Python
3,200
train_108.jsonl
5178c98fbee2bf661f6321b6f8e00552
256 megabytes
["3 3\n?10\n1??\n010", "2 3\n000\n001", "1 1\n?", "6 9\n1101011?0\n001101?00\n101000110\n001011010\n0101?01??\n00?1000?0"]
PASSED
# import io,os # read = io.BytesIO(os.read(0, os.fstat(0).st_size)) # I = lambda: [*map(int, read.readline().split())] import sys I=lambda:[*map(int,sys.stdin.readline().split())] M = 998244353 r, c = I() rows = [] for i in range(r): rows.append([*input()]) if r % 2 == 0 and c % 2 == 0: blanks = 0 for i in range(r): blanks += rows[i].count('?') print(pow(2, blanks, M)) elif r % 2 + c % 2 == 1: if r % 2 == 1: nrows = [] for i in range(c): nrows.append([rows[j][i] for j in range(r)]) rows = nrows ones = 1 zeroes = 1 for row in rows: unk = 0 xor = 0 for char in row: if char == '?': unk += 1 elif char == '1': xor = 1 - xor if unk == 0: if xor == 1: zeroes = 0 else: ones = 0 else: zeroes = zeroes * pow(2, unk - 1, M) % M ones = ones * pow(2, unk - 1, M ) % M print((ones + zeroes) % M) else: RC = [0] * (r + c) edges = [[] for i in range(r + c)] for i in range(r): for j in range(c): char = rows[i][j] if char == '?': edges[i].append(j + r) edges[j + r].append(i) elif char == '1': RC[i] = 1 - RC[i] RC[r + j] = 1 - RC[r + j] seen = [0] * (r + c) zeroes = [] ones = [] for i in range(r + c): if not seen[i]: component = [i] seen[i] = 1 j = 0 while j < len(component): if len(component) == r + c: break for v in edges[component[j]]: if not seen[v]: seen[v] = 1 component.append(v) j += 1 n = len(component) m = 0 x = 0 for v in component: m += len(edges[v]) x ^= RC[v] m //= 2 if n % 2 == 0: if x == 0: y = pow(2, m - n + 1, M) zeroes.append(y) ones.append(y) else: print(0) exit() else: y = pow(2, m - n + 1, M) if x == 0: zeroes.append(y) ones.append(0) else: ones.append(y) zeroes.append(0) zs = 1 for g in zeroes: zs = zs * g % M os = 1 for g in ones: os = os * g % M print((zs + os) % M)
1650722700
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["10 10 10\n10 10 10\n10 10 10", "4 4\n10 6", "-1 -1\n-1 -1"]
7b13ee633c81abdcf912542ba1779a45
NoteIn the first example, the answer is always $$$10$$$ no matter how you walk.In the second example, $$$answer_{21} = 10$$$, the path is $$$(2,1) \to (1,1) \to (1,2) \to (2,2) \to (2,1)$$$, the boredness is $$$4 + 1 + 2 + 3 = 10$$$.
You are wandering in the explorer space of the 2050 Conference.The explorer space can be viewed as an undirected weighted grid graph with size $$$n\times m$$$. The set of vertices is $$$\{(i, j)|1\le i\le n, 1\le j\le m\}$$$. Two vertices $$$(i_1,j_1)$$$ and $$$(i_2, j_2)$$$ are connected by an edge if and only if $$$|i_1-i_2|+|j_1-j_2|=1$$$.At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing $$$x$$$ exhibits, your boredness increases by $$$x$$$.For each starting vertex $$$(i, j)$$$, please answer the following question: What is the minimum possible boredness if you walk from $$$(i, j)$$$ and go back to it after exactly $$$k$$$ steps?You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex $$$(i, j)$$$ after $$$k$$$ steps, you can visit $$$(i, j)$$$ (or not) freely.
Output $$$n$$$ lines with $$$m$$$ numbers each. The $$$j$$$-th number in the $$$i$$$-th line, $$$answer_{ij}$$$, should be the minimum possible boredness if you walk from $$$(i, j)$$$ and go back to it after exactly $$$k$$$ steps. If you cannot go back to vertex $$$(i, j)$$$ after exactly $$$k$$$ steps, $$$answer_{ij}$$$ should be $$$-1$$$.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2\leq n, m\leq 500, 1\leq k\leq 20$$$). The $$$j$$$-th number ($$$1\le j \le m - 1$$$) in the $$$i$$$-th line of the following $$$n$$$ lines is the number of exibits on the edge between vertex $$$(i, j)$$$ and vertex $$$(i, j+1)$$$. The $$$j$$$-th number ($$$1\le j\le m$$$) in the $$$i$$$-th line of the following $$$n-1$$$ lines is the number of exibits on the edge between vertex $$$(i, j)$$$ and vertex $$$(i+1, j)$$$. The number of exhibits on each edge is an integer between $$$1$$$ and $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_101.jsonl
0403abc133f6b660468ad64c73d8b684
256 megabytes
["3 3 10\n1 1\n1 1\n1 1\n1 1 1\n1 1 1", "2 2 4\n1\n3\n4 2", "2 2 3\n1\n2\n3 4"]
PASSED
def roll(i,j): ways = [] if j: ways.append( 2 * horizontal[i][j-1] + grid[i][j-1]) if m-1-j: ways.append(2 * horizontal[i][j] + grid[i][j+1]) if i: ways.append(2 * vertical[i-1][j] + grid[i-1][j]) if n-1-i: ways.append(2 * vertical[i][j] + grid[i+1][j]) return min(ways) n , m , k = map(int, input().split()) horizontal = [list(map(int, input().split())) for _ in range(n)] vertical = [list(map(int, input().split())) for _ in range(n-1)] grid = [[0]*m for _ in range(n)] if k%2: for _ in range(n): print(" ".join(["-1"]*m)) else: for _ in range(k//2): new_grid = [[roll(i,j) for j in range(m)] for i in range(n)] grid = new_grid[:] for i in range(n): print(" ".join(map(str,grid[i])))
1619188500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1", "0", "4", "1"]
583168dfbaa91b79c623b44b7efee653
NoteIn the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab.In the fourth sample identificators intersect.
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!
Output the only number — the amount of different substrings of t that start with sbegin and end with send.
The input file consists of three lines. The first line contains string t. The second and the third lines contain the sbegin and send identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters.
standard output
standard input
Python 3
Python
2,000
train_014.jsonl
631060720a3500ab8de5900b33dcfdb0
256 megabytes
["round\nro\nou", "codeforces\ncode\nforca", "abababab\na\nb", "aba\nab\nba"]
PASSED
from functools import cmp_to_key def calc_lcp(s, sa): rank = [0 for _ in range(len(s))] for i in range(len(s)): rank[sa[i]] = i lcp = [0 for _ in range(len(s) - 1)] h = 0 for i in range(len(s)): if rank[i] < len(s) - 1: while max(i, sa[rank[i] + 1]) + h < len(s) and s[i + h] == s[sa[rank[i] + 1] + h]: h += 1 lcp[rank[i]] = h if h > 0: h -= 1 return lcp, rank def suffix_array(s): sa = [i for i in range(len(s))] rank = [ord(s[i]) for i in range(len(s))] k = 1 while k < len(s): key = [0 for _ in range(len(s))] base = max(rank) + 2 for i in range(len(s)): key[i] = rank[i] * base + (rank[i + k] + 1 if i + k < len(s) else 0) sa.sort(key=(lambda i: key[i])) rank[sa[0]] = 0 for i in range(1, len(s)): rank[sa[i]] = rank[sa[i - 1]] if key[sa[i - 1]] == key[sa[i]] else i k *= 2 # for i in sa: # print(s[i:]) return sa def kmp(s, p): pi = [0 for _ in range(len(p))] k = 0 for i in range(1, len(p)): while k > 0 and p[k] != p[i]: k = pi[k - 1] if p[k] == p[i]: k += 1 pi[i] = k k = 0 resp = [] for i in range(len(s)): while k > 0 and p[k] != s[i]: k = pi[k - 1] if p[k] == s[i]: k += 1 if k == len(p): resp.append(i - len(p) + 1) k = pi[k - 1] return resp def lower_bound(list, value): left = 0 right = len(list) while left < right: mid = int((left + right) / 2) if list[mid] < value: left = mid + 1 else: right = mid return left s = input() start = input() end = input() indStart = kmp(s, start) indEnd = kmp(s, end) if len(indStart) == 0 or len(indEnd) == 0: print(0) else: sa = suffix_array(s) lcp, rank = calc_lcp(s, sa) ind = rank[indStart[0]] for st in indStart: ind = min(ind, rank[st]) resp = len(indEnd) - lower_bound(indEnd, sa[ind] + max(0, len(start) - len(end))) while ind < len(lcp) and lcp[ind] >= len(start): ind += 1 resp += len(indEnd) - lower_bound(indEnd, sa[ind] + max(0, max(lcp[ind - 1] + 1, len(start)) - len(end))) print(resp) # Made By Mostafa_Khaled
1315494000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1", "2", "0"]
3583a9762191ee8f8c3c2a287cb1ec1d
NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.
Output a single integer — the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of actions Valentin did. The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types: Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said. Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said. Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter. All words consist only of lowercase English letters. The total length of all words does not exceed 105. It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.
standard output
standard input
Python 3
Python
1,600
train_003.jsonl
96b99887cdaf368867b4fdf5ee5731e1
256 megabytes
["5\n! abc\n. ad\n. b\n! cd\n? c", "8\n! hello\n! codeforces\n? c\n. o\n? d\n? h\n. l\n? e", "7\n! ababahalamaha\n? a\n? b\n? a\n? b\n? a\n? h"]
PASSED
'''input 5 ! abc . ad . b ! cd ? c ''' t = [0] * 26 e = 0 n = int(input()) if n == 1: print(0) quit() for i in range(n-1): x, y = input().split() if x == '!': if 1 in t: c = [ord(p) - 97 for p in set(y)] for x in range(26): if not(t[x] == 1 and x in c): t[x] = -1 else: for l in set(y): if t[ord(l) - 97] == 0: t[ord(l) - 97] = 1 elif x == '.': for l in set(y): t[ord(l) - 97] = -1 else: t[ord(y) - 97] = -1 if t.count(1) == 1 or (t.count(0) == 1 and max(t) == 0): break g = [False] * 26 for _ in range(i+1, n-1): x, y = input().split() if x == '!' or x == '?': e += 1 print(e)
1514037900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["13\n9\n3"]
113a43af2f1c5303f83eb842ef532040
NoteIn the first testcase, it's enough to consider the following modified paths: RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$; RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$; RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:
Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves: D — move one cell down; R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,900
train_108.jsonl
93b24e422cf9bba138e4ee5d5b6a6be5
256 megabytes
["3\n\n4\n\nRD\n\n5\n\nDRDRDRDR\n\n3\n\nD"]
PASSED
import sys from array import array import re input = lambda: sys.stdin.buffer.readline().decode().strip() inp = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)] inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)] ceil1 = lambda a, b: (a + b - 1) // b debug = lambda *x: print(*x, file=sys.stderr) out = [] for _ in range(int(input())): n, s = int(input()), input() if len(set(s)) == 1: out.append(n) continue ans = n * n pred, prer = array('i', [0]), array('i', [0]) for i in range(len(s)): pred.append(pred[-1] + (s[i] == 'D')) prer.append(prer[-1] + (s[i] == 'R')) for i, pat in enumerate(re.finditer('R+', s)): l, r = pat.span() ans -= (r - l) * pred[l] if i == 0: ans -= (n - prer[-1] - 1) * pred[l] for i, pat in enumerate(re.finditer('D+', s)): l, r = pat.span() ans -= (r - l) * prer[l] if i == 0: ans -= (n - pred[-1] - 1) * prer[l] out.append(ans) print('\n'.join(map(str, out)))
1645540500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5", "2", "0", "-1"]
a3a7515219ebb0154218ee3520e20d75
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
standard output
standard input
Python 3
Python
1,300
train_008.jsonl
a92c478d9a6acd1d61dff61f27b4d575
256 megabytes
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
PASSED
def rotate(s): n = len(s) return s[1:] + s[0] n = int(input()) a = [input() for _ in range(n)] s = a[0] n = len(s) min_cost = float('inf') for _ in range(n): s = rotate(s) cost = 0 for i in a: found = False for _ in range(n): if i == s: found = True break cost += 1 i = rotate(i) if not found: cost = -float('inf') min_cost = min(min_cost, cost) if min_cost < 0: min_cost = -1 print(min_cost)
1492785300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["4", "2", "4"]
fc057414df9fd8b61e01cda8bc5cdcaf
NoteIn the first and second examples initial positions of black tokens are shown with black points, possible positions of the white token (such that the black player wins) are shown with white points.The first example: The second example: In the third example the white tokens should be located in the inner square 2 × 2, to make the black player win.
Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates x and y.The players take turn making moves, white starts. On each turn, a player moves all tokens of their color by 1 to up, down, left or right. Black player can choose directions for each token independently.After a turn of the white player the white token can not be in a point where a black token is located. There are no other constraints on locations of the tokens: positions of black tokens can coincide, after a turn of the black player and initially the white token can be in the same point with some black point. If at some moment the white player can't make a move, he loses. If the white player makes 10100500 moves, he wins.You are to solve the following problem. You are given initial positions of all black tokens. It is guaranteed that initially all these positions are distinct. In how many places can the white token be located initially so that if both players play optimally, the black player wins?
Print the number of points where the white token can be located initially, such that if both players play optimally, the black player wins.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of black points. The (i + 1)-th line contains two integers xi, yi ( - 105 ≤ xi, yi,  ≤ 105) — the coordinates of the point where the i-th black token is initially located. It is guaranteed that initial positions of black tokens are distinct.
standard output
standard input
Python 2
Python
2,500
train_007.jsonl
f924891c3197a9a876a50a9ab2e2080b
256 megabytes
["4\n-2 -1\n0 1\n0 -3\n2 -1", "4\n-2 0\n-1 1\n0 -2\n1 -1", "16\n2 1\n1 2\n-1 1\n0 1\n0 0\n1 1\n2 -1\n2 0\n1 0\n-1 -1\n1 -1\n2 2\n0 -1\n-1 0\n0 2\n-1 2"]
PASSED
from sys import stdin from itertools import repeat def solve(a): inf = 1001001001 C = 400010 lmn = [inf] * 400010 lmx = [-inf] * 400010 for x, y in a: x = (x - 1) / 2 + 100005 if lmn[x] > y: lmn[x] = y if lmx[x] < y: lmx[x] = y rmn = lmn[:] rmx = lmx[:] for i in xrange(200009): if lmn[i+1] > lmn[i]: lmn[i+1] = lmn[i] for i in xrange(200009): if lmx[i+1] < lmx[i]: lmx[i+1] = lmx[i] for i in xrange(200009, 0, -1): if rmn[i-1] > rmn[i]: rmn[i-1] = rmn[i] for i in xrange(200009, 0, -1): if rmx[i-1] < rmx[i]: rmx[i-1] = rmx[i] for i in xrange(200010): if lmn[i] < rmn[i]: lmn[i] = rmn[i] for i in xrange(200010): if lmx[i] > rmx[i]: lmx[i] = rmx[i] ans = 0 for i in xrange(200009): if lmn[i] < lmn[i+1]: lmn[i] = lmn[i+1] for i in xrange(200009): if lmx[i] > lmx[i+1]: lmx[i] = lmx[i+1] for i in xrange(200009): if lmn[i] < lmx[i]: ans += (lmx[i] - lmn[i]) / 2 return ans def main(): n = int(stdin.readline()) dat = map(int, stdin.read().split(), repeat(10, 2 * n)) s = [[], []] for i in xrange(n): x, y = dat[i*2:i*2+2] s[(x+y)&1].append((-x+y, x+y)) print solve(s[0]) + solve(s[1]) main()
1520177700
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["8\n-1\n-1\n-1\n4\n1\n-1"]
07597a8d08b59d4f8f82369bb5d74a49
NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle.
Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person. A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.
For each test case output in a separate line a single integer $$$d$$$ — the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.
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 distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a,b,c \le 10^8$$$).
standard output
standard input
Python 3
Python
800
train_103.jsonl
994ed22a5a5cbb17090838f6abe68981
256 megabytes
["7\n6 2 4\n2 3 1\n2 4 10\n5 3 4\n1 3 2\n2 5 4\n4 3 2"]
PASSED
t=int(input()) qwe=[] for i in range(t): qwe.append(list(map(int,input().split()))) for j in range(t): a = qwe[j][0] b = qwe[j][1] c = qwe[j][2] if a > b: a, b = b, a h = b - a f = 2 * h if (f < b) or (c > f): d = -1 else: if (c + h) > f: d = c - h else: d = c + h print(d) # Sun Sep 12 2021 19:26:22 GMT+0300 (Москва, стандартное время)
1629297300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n0\n1\n3"]
7a724f327c6202735661be25ef9328d2
NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".
You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is: "()" is regular bracket sequence; if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence; if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.
standard output
standard input
Python 3
Python
1,000
train_032.jsonl
105ca32a1572ebe881f0dfe548135f10
256 megabytes
["4\n2\n)(\n4\n()()\n8\n())()()(\n10\n)))((((())"]
PASSED
t=int(input()) for i in range(t): n=int(input()) s=input() while '()' in s: s=s.replace('()','') m=s.count(')') print(m)
1593354900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["YES\nYES\nNO"]
9b9b01e5d2329291eee80356525eaf04
NoteIn the first query, you can perform two operations $$$s_1 = s_2$$$ (after it $$$s$$$ turns into "aabb") and $$$t_4 = t_3$$$ (after it $$$t$$$ turns into "aabb"). In the second query, the strings are equal initially, so the answer is "YES".In the third query, you can not make strings $$$s$$$ and $$$t$$$ equal. Therefore, the answer is "NO".
You are given two strings of equal length $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if $$$s$$$ is "acbc" you can get the following strings in one operation: "aabc" (if you perform $$$s_2 = s_1$$$); "ccbc" (if you perform $$$s_1 = s_2$$$); "accc" (if you perform $$$s_3 = s_2$$$ or $$$s_3 = s_4$$$); "abbc" (if you perform $$$s_2 = s_3$$$); "acbb" (if you perform $$$s_4 = s_3$$$); Note that you can also apply this operation to the string $$$t$$$.Please determine whether it is possible to transform $$$s$$$ into $$$t$$$, applying the operation above any number of times.Note that you have to answer $$$q$$$ independent queries.
For each query, print "YES" if it is possible to make $$$s$$$ equal to $$$t$$$, and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).
The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by two consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$) consisting of lowercase Latin letters.
standard output
standard input
Python 3
Python
1,000
train_000.jsonl
aa279198e77a2eb7deb7c6e43928baf1
256 megabytes
["3\nxabb\naabx\ntechnocup\ntechnocup\na\nz"]
PASSED
n=int(input()) for i in range (n): a,b=(input()),(input()) for i in b: if i in a: k="YES" break else: k="NO" print(k)
1570374300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["YES", "YES", "NO"]
447ebe088a0a60a7a44a3fc76056bc65
NoteIn the first sample .In the second sample .In the third sample .
A continued fraction of height n is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height n. Check if they are equal.
Print "YES" if these fractions are equal and "NO" otherwise.
The first line contains two space-separated integers p, q (1 ≤ q ≤ p ≤ 1018) — the numerator and the denominator of the first fraction. The second line contains integer n (1 ≤ n ≤ 90) — the height of the second fraction. The third line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1018) — the continued fraction. 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.
standard output
standard input
Python 3
Python
1,700
train_022.jsonl
5fad1e9b0b4077ba279ffa32b3481b45
256 megabytes
["9 4\n2\n2 4", "9 4\n3\n2 3 1", "9 4\n3\n1 2 4"]
PASSED
p,q = input().split() p = int(p) q = int(q) n = int(input()) A = input().split() a = 1 b = int(A[n-1]) i = n-2 while( i >= 0 ): aux = b b = a + b*int(A[i]) a = aux i = i-1 print ("YES" if p*a == q*b else "NO" )
1368968400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3", "3"]
c3c3ac7a8c9d2ce142e223309ab005e6
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
Print the single number — the number of Super Duper Secret Missile Silos that are located in Berland.
The first line contains three integers n, m and s (2 ≤ n ≤ 105, , 1 ≤ s ≤ n) — the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≤ l ≤ 109) — the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
standard output
standard input
Python 2
Python
1,900
train_034.jsonl
7d05cf904c01f04ba9a69d2aa39513e1
256 megabytes
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
PASSED
from heapq import * n,m,s=map(int,raw_input().split()) g=[[] for _ in range(n+1)] for _ in range(m): u,v,w=map(int,raw_input().split()) g[u].append((v,w)) g[v].append((u,w)) l=input() d=[10**10]*(n+1) d[s]=0 q=[(0,s)] while q: t,u=heappop(q) if t==d[u]: for v,w in g[u]: if d[v]>t+w: d[v]=t+w heappush(q,(d[v],v)) k=0 for u in xrange(1,n+1): for v,w in g[u]: if d[u]<l and d[u]+w>l: k+=2 if (l-d[u])+(l-d[v])<w else 1 if (l-d[u])+(l-d[v])==w else 0 print (k>>1)+d.count(l)
1326899100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["3", "0", "inf"]
749c290c48272a53e2e79730dab0538e
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≤ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
The first line of input contains four integers b1, q, l, m (-109 ≤ b1, q ≤ 109, 1 ≤ l ≤ 109, 1 ≤ m ≤ 105) — the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≤ ai ≤ 109) — numbers that will never be written on the board.
standard output
standard input
Python 2
Python
1,700
train_008.jsonl
ad6b114a251dfc728156c85cc083b945
256 megabytes
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
PASSED
b1, q, l, m = [int(x) for x in raw_input().split()] lst = [int(x) for x in raw_input().split()] st = set(lst) cur = b1 ans = 0 ok = False if abs(b1) > l: print 0 exit() for _ in xrange(64): if cur not in st: ans += 1 cur *= q if abs(cur) > l: ok = True break if not ok and q == 0: if 0 in st: print ans else: print "inf" elif not ok and abs(q) == 1: if ans == 0: print 0 else: print "inf" elif not ok and b1 == 0: if 0 in st: print 0 else: print "inf" else: print ans
1490803500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1.50000000000000000000", "2.00000000000000000000"]
85b78251160db9d7ca1786e90e5d6f21
NoteIn the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1 × (1 / 2) + 2 × (1 / 2) = 1.5In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
Print a single real number — the expectation of the number of steps in the described game. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
The first line contains integer n (1 ≤ n ≤ 105) — the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the nodes that are connected by the i-th edge. It is guaranteed that the given graph is a tree.
standard output
standard input
Python 2
Python
2,200
train_011.jsonl
af0b4b86f374570c2fc40e816116dee7
256 megabytes
["2\n1 2", "3\n1 2\n1 3"]
PASSED
n = input() edge = [[] for _ in range(n)] for i in range(n - 1): a, b = map(int, raw_input().split()) edge[a - 1].append(b - 1) edge[b - 1].append(a - 1) d = [0] * n d[0] = 1 p = [0] for u in p: for v in edge[u]: if not d[v]: d[v] = d[u] + 1 p.append(v) print sum((1. / x for x in d))
1362929400
[ "probabilities", "math", "trees" ]
[ 0, 0, 0, 1, 0, 1, 0, 1 ]
2 seconds
["0\n0\n3\n3", "0\n0\n0\n3\n3\n4\n4\n5", "0\n0\n0\n0\n3\n4\n4"]
d795e0f49617b1aa281c72f24a632f67
NoteIn the first example, $$$1,2,3$$$ can go on day $$$3$$$ and $$$4$$$. In the second example, $$$2,4,5$$$ can go on day $$$4$$$ and $$$5$$$. $$$1,2,4,5$$$ can go on day $$$6$$$ and $$$7$$$. $$$1,2,3,4,5$$$ can go on day $$$8$$$. In the third example, $$$1,2,5$$$ can go on day $$$5$$$. $$$1,2,3,5$$$ can go on day $$$6$$$ and $$$7$$$.
There are $$$n$$$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.We want to plan a trip for every evening of $$$m$$$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least $$$k$$$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $$$a$$$ and $$$b$$$ are friends and $$$b$$$ and $$$c$$$ are friends, it does not necessarily imply that $$$a$$$ and $$$c$$$ are friends.For each day, find the maximum number of people that can go on the trip on that day.
Print exactly $$$m$$$ lines, where the $$$i$$$-th of them ($$$1\leq i\leq m$$$) contains the maximum number of people that can go on the trip on the evening of the day $$$i$$$.
The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$$$, $$$1 \le k &lt; n$$$) — the number of people, the number of days and the number of friends each person on the trip should have in the group. The $$$i$$$-th ($$$1 \leq i \leq m$$$) of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1\leq x, y\leq n$$$, $$$x\ne y$$$), meaning that persons $$$x$$$ and $$$y$$$ become friends on the morning of day $$$i$$$. It is guaranteed that $$$x$$$ and $$$y$$$ were not friends before.
standard output
standard input
Python 3
Python
2,200
train_073.jsonl
10accb27649ab606e19aeacbd53bbb52
256 megabytes
["4 4 2\n2 3\n1 2\n1 3\n1 4", "5 8 2\n2 1\n4 2\n5 4\n5 2\n4 3\n5 1\n4 1\n3 2", "5 7 2\n1 5\n3 2\n2 5\n3 4\n1 2\n5 3\n1 3"]
PASSED
from collections import deque def solve(adj, m, k, uv): n = len(adj) nn = [len(a) for a in adj] q = deque() for i in range(n): if nn[i] < k: q.append(i) while q: v = q.popleft() for u in adj[v]: nn[u] -= 1 if nn[u] == k-1: q.append(u) res = [0]*m nk = len([1 for i in nn if i >= k]) res[-1] = nk for i in range(m-1, 0, -1): u1, v1 = uv[i] if nn[u1] < k or nn[v1] < k: res[i - 1] = nk continue if nn[u1] == k: q.append(u1) nn[u1] -= 1 if not q and nn[v1] == k: q.append(v1) nn[v1] -= 1 if not q: nn[u1] -= 1 nn[v1] -= 1 adj[u1].remove(v1) adj[v1].remove(u1) while q: v = q.popleft() nk -= 1 for u in adj[v]: nn[u] -= 1 if nn[u] == k - 1: q.append(u) res[i - 1] = nk return res n, m, k = map(int, input().split()) a = [set() for i in range(n)] uv = [] for i in range(m): u, v = map(int, input().split()) a[u - 1].add(v - 1) a[v - 1].add(u - 1) uv.append((u-1, v-1)) res = solve(a, m, k, uv) print(str(res)[1:-1].replace(' ', '').replace(',', '\n'))
1535898900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1\n2\n5\n2\n0", "8\n2\n9\n8"]
7e03c9e316f36c1d9487286237e24c6f
NoteAnswers on queries from the first example are described in the problem statement.
The only difference between the easy and the hard versions is the maximum value of $$$k$$$.You are given an infinite sequence of form "112123123412345$$$\dots$$$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $$$1$$$ to $$$1$$$, the second one — from $$$1$$$ to $$$2$$$, the third one — from $$$1$$$ to $$$3$$$, $$$\dots$$$, the $$$i$$$-th block consists of all numbers from $$$1$$$ to $$$i$$$. So the first $$$56$$$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $$$1$$$-st element of the sequence is $$$1$$$, the $$$3$$$-rd element of the sequence is $$$2$$$, the $$$20$$$-th element of the sequence is $$$5$$$, the $$$38$$$-th element is $$$2$$$, the $$$56$$$-th element of the sequence is $$$0$$$.Your task is to answer $$$q$$$ independent queries. In the $$$i$$$-th query you are given one integer $$$k_i$$$. Calculate the digit at the position $$$k_i$$$ of the sequence.
Print $$$q$$$ lines. In the $$$i$$$-th line print one digit $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — the answer to the query $$$i$$$, i.e. $$$x_i$$$ should be equal to the element at the position $$$k_i$$$ of the sequence.
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The $$$i$$$-th of the following $$$q$$$ lines contains one integer $$$k_i$$$ $$$(1 \le k_i \le 10^9)$$$ — the description of the corresponding query.
standard output
standard input
PyPy 3
Python
1,900
train_032.jsonl
e1aefc351f762be9d78167f3fac6bb43
256 megabytes
["5\n1\n3\n20\n38\n56", "4\n2132\n506\n999999999\n1000000000"]
PASSED
word = '' arr = [0] for i in range(1,22000): word = word + str(i) arr.append(arr[-1] + len(word)) def sol(k): d = 0 for i in range(1,22000): if arr[i] > k: d = i - 1 break k = k - arr[d] if k == 0: return str(d)[-1] else: return word[k - 1] for i in range(int(input())): print(sol(int(input())))
1569049500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2 4 2 0"]
8543bcd08ec0bbbf9a0a3682468287f4
NoteThe minimal possible total cost is $$$566 \cdot 1+239 \cdot 1+30 \cdot 1+1 \cdot 2+1 \cdot 2=839$$$:
Julia's $$$n$$$ friends want to organize a startup in a new country they moved to. They assigned each other numbers from 1 to $$$n$$$ according to the jobs they have, from the most front-end tasks to the most back-end ones. They also estimated a matrix $$$c$$$, where $$$c_{ij} = c_{ji}$$$ is the average number of messages per month between people doing jobs $$$i$$$ and $$$j$$$.Now they want to make a hierarchy tree. It will be a binary tree with each node containing one member of the team. Some member will be selected as a leader of the team and will be contained in the root node. In order for the leader to be able to easily reach any subordinate, for each node $$$v$$$ of the tree, the following should apply: all members in its left subtree must have smaller numbers than $$$v$$$, and all members in its right subtree must have larger numbers than $$$v$$$.After the hierarchy tree is settled, people doing jobs $$$i$$$ and $$$j$$$ will be communicating via the shortest path in the tree between their nodes. Let's denote the length of this path as $$$d_{ij}$$$. Thus, the cost of their communication is $$$c_{ij} \cdot d_{ij}$$$.Your task is to find a hierarchy tree that minimizes the total cost of communication over all pairs: $$$\sum_{1 \le i &lt; j \le n} c_{ij} \cdot d_{ij}$$$.
Output a description of a hierarchy tree that minimizes the total cost of communication. To do so, for each team member from 1 to $$$n$$$ output the number of the member in its parent node, or 0 for the leader. If there are many optimal trees, output a description of any one of them.
The first line contains an integer $$$n$$$ ($$$1 \le n \le 200$$$) – the number of team members organizing a startup. The next $$$n$$$ lines contain $$$n$$$ integers each, $$$j$$$-th number in $$$i$$$-th line is $$$c_{ij}$$$ — the estimated number of messages per month between team members $$$i$$$ and $$$j$$$ ($$$0 \le c_{ij} \le 10^9; c_{ij} = c_{ji}; c_{ii} = 0$$$).
standard output
standard input
PyPy 3-64
Python
2,100
train_091.jsonl
649315f68598a26f2a9b26cc6dd8f7e1
512 megabytes
["4\n0 566 1 0\n566 0 239 30\n1 239 0 1\n0 30 1 0"]
PASSED
n=int(input()) c=[] for _ in range(n): c.append(tuple(map(int,input().split()))) prefix_sum=[[0]*(n+1) for _ in range(n+1)] for i in range(1,n+1): temp=0 for j in range(1,n+1): temp+=c[i-1][j-1] prefix_sum[i][j]+=prefix_sum[i-1][j]+temp def get_rectangel_sum(x1,y1,x2,y2): return prefix_sum[x2+1][y2+1]-prefix_sum[x1][y2+1]-prefix_sum[x2+1][y1]+prefix_sum[x1][y1] def cost(x,y): if x>y: return 0 a=get_rectangel_sum(x,0,y,x-1) if x!=0 else 0 b=get_rectangel_sum(x,y+1,y,n-1) if y!=n-1 else 0 return a+b dp=[[float("INF")]*n for _ in range(n)] best_root_for_range=[[-1]*n for _ in range(n)] for i in range(n): dp[i][i]=0 best_root_for_range[i][i]=i def get_dp_cost(x,y): return dp[x][y] if x<=y else 0 for length in range(1,n): # actual length is length+1 for i in range(n-length): j=i+length for root in range(i,j+1): temp=cost(i,root-1)+cost(root+1,j)+get_dp_cost(i,root-1)+get_dp_cost(root+1,j) if temp<dp[i][j]: dp[i][j]=temp best_root_for_range[i][j]=root ans=[-1]*n def assign_ans(ansecstor,x,y): if x>y: return root=best_root_for_range[x][y] ans[root]=ansecstor assign_ans(root,x,root-1) assign_ans(root,root+1,y) assign_ans(-1,0,n-1) print(*[i+1 for i in ans]) # 3 # 0 1 2 # 1 0 3 # 2 3 0 # 4 # 0 1 2 3 # 1 0 5 7 # 2 5 0 4 # 3 7 4 0 # 6 # 0 100 20 37 14 73 # 100 0 17 13 20 2 # 20 17 0 1093 900 1 # 37 13 1093 0 2 4 # 14 20 900 2 0 1 # 73 2 1 4 1 0
1649837100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["YES\naccx\naegx\nbega\nbdda\nYES\naha\naha\nYES\nzz\naa\nzz\nNO\nYES\naaza\nbbza\nNO\nYES\nbbaabbaabbaabbaay\nddccddccddccddccy\nNO"]
a15f7324d545c26725324928eaaa645c
null
The only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem.There's a table of $$$n \times m$$$ cells ($$$n$$$ rows and $$$m$$$ columns). The value of $$$n \cdot m$$$ is even.A domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other).You need to place $$$\frac{nm}{2}$$$ dominoes on the table so that exactly $$$k$$$ of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table.
For each test case: print "NO" if it's not possible to place the dominoes on the table in the described way; otherwise, print "YES" on a separate line, then print $$$n$$$ lines so that each of them contains $$$m$$$ lowercase letters of the Latin alphabet — the layout of the dominoes on the table. Each cell of the table must be marked by the letter so that for every two cells having a common side, they are marked by the same letters if and only if they are occupied by the same domino. I.e. both cells of the same domino must be marked with the same letter, but two dominoes that share a side must be marked with different letters. If there are multiple solutions, print any of them.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of a single line. The line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n,m \le 100$$$, $$$0 \le k \le \frac{nm}{2}$$$, $$$n \cdot m$$$ is even) — the count of rows, columns and horizontal dominoes, respectively.
standard output
standard input
PyPy 3-64
Python
2,100
train_099.jsonl
7dcef7b2db9c1183b624f0a31f094345
256 megabytes
["8\n4 4 2\n2 3 0\n3 2 3\n1 2 0\n2 4 2\n5 2 2\n2 17 16\n2 1 1"]
PASSED
import sys from math import ceil input = sys.stdin.readline inf = float('inf') def getInt(): return int(input()) def getList(): return map(int, input().split()) def getStr(): return input().strip() t = getInt() # t = 1 def solve(): # what we are trying to accomplish here is to make the empty rectangle has even height # hence if n is odd first we must filled the first row with horizontal domino, if we can not return false # let k denotes the reamining horizontal dominoes , now we notice both n and m is even # if k is even, one viable strategy is to filled from to to bottom, because k is even and n, hence the reaming rectangles (at most two) has even side # if k is odd, no mattter how we assign, k is odd hence at least one rectalge must he of odd height hence it is not possible # if is also important to check if the filling exceed the width of the grid n, m, k = getList() extra = [] if n & 1: if k < m / 2: print("NO") return n -= 1 k -= m // 2 extra = 'mmnn'*m w = ceil(k/n) * 2 if n else 0 res = [[" "]*m for _ in range(n) ] if (k % 2 == 0 and w <= m): print("YES") for i in range(n): for j in range(k//n + (i < k%n)) : res[i][j*2] = res[i][j*2+1] = (i+j)&1 and 'a' or 'b' for j in range(w, m): for i in range(n//2): res[i*2][j] = res[i*2+1][j] = (i+j) & 1 and 'c' or 'd' if n and k % n : for i in range(k%n, n, 2): for j in w-2,w-1: res[i][j] = res[i+1][j] = (i//2+j) & 1 and 'e' or 'f' if extra: res.insert(0, extra[:m]) for i in res: print(*i, sep="") else: print("NO") # e f # e f for _ in range(t): solve() """ aabbaa bbaabb aabbaa bbaabb """
1627050900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4", "1", "0"]
6a3d6919435e5ba63bb95cd387a11b06
NoteIn the first sample, the four ways are to: Make everyone love each other Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≤ ai, bi ≤ n, ai ≠ bi, ). Each pair of people will be described no more than once.
standard output
standard input
Python 3
Python
2,200
train_010.jsonl
a2d4687aa2a2cf8406e82f48a03cccda
256 megabytes
["3 0", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 0", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 1"]
PASSED
class DSU(object): def __init__(self, n): self.father = list(range(n)) self.size = n def union(self, x, s): x = self.find(x) s = self.find(s) if x == s: return self.father[s] = x self.size -= 1 def find(self, x): xf = self.father[x] if xf != x: self.father[x] = self.find(xf) return self.father[x] def is_invalid(a, b, ds): return ds.find(a) == ds.find(b) n, k = map(int, input().split()) ds = DSU(n * 2) for i in range(k): first, second, color = map(int, input().split()) first -= 1 second -= 1 if color == 0: if is_invalid(first, second, ds): print(0) exit() ds.union(first, second + n) ds.union(first + n, second) else: if is_invalid(first, second + n, ds): print(0) exit() ds.union(first, second) ds.union(first + n, second + n) sum = 1 for i in range(ds.size // 2 - 1): sum = (sum * 2) % (10 ** 9 + 7) print(sum)
1435163400
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["6"]
414d1f0cef26fbbf4ede8eac32a1dd48
null
You are playing another computer game, and now you have to slay $$$n$$$ monsters. These monsters are standing in a circle, numbered clockwise from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th monster has $$$a_i$$$ health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $$$1$$$ (deals $$$1$$$ damage to it). Furthermore, when the health of some monster $$$i$$$ becomes $$$0$$$ or less than $$$0$$$, it dies and explodes, dealing $$$b_i$$$ damage to the next monster (monster $$$i + 1$$$, if $$$i &lt; n$$$, or monster $$$1$$$, if $$$i = n$$$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all $$$n$$$ monsters in the circle.
For each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.
The first line contains one integer $$$T$$$ ($$$1 \le T \le 150000$$$) — the number of test cases. Then the test cases follow, each test case begins with a line containing one integer $$$n$$$ ($$$2 \le n \le 300000$$$) — the number of monsters. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^{12}$$$) — the parameters of the $$$i$$$-th monster in the circle. It is guaranteed that the total number of monsters in all test cases does not exceed $$$300000$$$.
standard output
standard input
PyPy 3
Python
1,600
train_001.jsonl
72cd6ae417f3e5a3c274175c5e1ad52e
256 megabytes
["1\n3\n7 15\n2 14\n5 3"]
PASSED
import sys input = sys.stdin.buffer.readline T = int(input()) for _ in range(T): n = int(input()) a,b = [],[] for i in range(n): x,y = map(int,input().split()) a.append(x) b.append(y) for i in range(n): b[i] = min(a[(i+1)%n],b[i]) b[-1] = min(a[0],b[-1]) print(sum(a)-sum(b)+min(b))
1586529300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n3\n2"]
68b7567880b9980d793dae2bce690356
NoteIn the first test case, $$$a$$$ = $$$[6, 6, 6]$$$ and $$$a'$$$ = $$$[6, 6, 6]$$$. $$$\text{LIS}(a) = \text{LIS}(a')$$$ = $$$1$$$. Hence the beauty is $$$min(1, 1) = 1$$$.In the second test case, $$$a$$$ can be rearranged to $$$[2, 5, 4, 5, 4, 2]$$$. Then $$$a'$$$ = $$$[2, 4, 5, 4, 5, 2]$$$. $$$\text{LIS}(a) = \text{LIS}(a') = 3$$$. Hence the beauty is $$$3$$$ and it can be shown that this is the maximum possible beauty.In the third test case, $$$a$$$ can be rearranged to $$$[1, 2, 3, 2]$$$. Then $$$a'$$$ = $$$[2, 3, 2, 1]$$$. $$$\text{LIS}(a) = 3$$$, $$$\text{LIS}(a') = 2$$$. Hence the beauty is $$$min(3, 2) = 2$$$ and it can be shown that $$$2$$$ is the maximum possible beauty.
You are given an array $$$a$$$ of $$$n$$$ positive integers. Let $$$\text{LIS}(a)$$$ denote the length of longest strictly increasing subsequence of $$$a$$$. For example, $$$\text{LIS}([2, \underline{1}, 1, \underline{3}])$$$ = $$$2$$$. $$$\text{LIS}([\underline{3}, \underline{5}, \underline{10}, \underline{20}])$$$ = $$$4$$$. $$$\text{LIS}([3, \underline{1}, \underline{2}, \underline{4}])$$$ = $$$3$$$. We define array $$$a'$$$ as the array obtained after reversing the array $$$a$$$ i.e. $$$a' = [a_n, a_{n-1}, \ldots , a_1]$$$.The beauty of array $$$a$$$ is defined as $$$min(\text{LIS}(a),\text{LIS}(a'))$$$.Your task is to determine the maximum possible beauty of the array $$$a$$$ if you can rearrange the array $$$a$$$ arbitrarily.
For each test case, output a single integer  — the maximum possible beauty of $$$a$$$ after rearranging its elements arbitrarily.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4)$$$  — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 2\cdot 10^5)$$$  — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \ldots ,a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$  — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,400
train_101.jsonl
e28b9b4974cd149635d4eee98cee90e8
256 megabytes
["3\n\n3\n\n6 6 6\n\n6\n\n2 5 4 5 2 4\n\n4\n\n1 3 2 2"]
PASSED
import sys from collections import Counter from math import ceil sys.setrecursionlimit(10**5) def pro(arr): n=len(arr) dic = {} for i in range(n): dic[arr[i]]=dic.get(arr[i],0) + 1 a,b=0,0 for i,j in dic.items(): if(j>=2): b+=1 else: a+=1 print(b+ceil(a/2) ) # check i/o format # read q # ordering matters in q ?? t=int(input()) #arr=list(map(int,input().split())) for i in range(t): n=int(input()) arr=list(map(int,input().split())) #arr=list(input()) pro(arr)
1653230100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
a7da19d857ca09f052718cb69f2cea57
null
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
The only line contains odd integer n (1 ≤ n ≤ 49).
standard output
standard input
Python 2
Python
1,500
train_018.jsonl
cc3f25da0df27998828208b556c23193
256 megabytes
["1", "3"]
PASSED
#n = input() n = input() odds = [i for i in range(1,n*n+1) if i % 2 == 1] evens = [i for i in range(1,n*n+1) if i % 2 == 0] #print(odds) #print(evens) magic = [] for i in range(int(n/2)): magic.append(2*i+1) magic2 = magic[::-1] magic = magic + [n] + magic2 #print(magic) result = [] for i in range(n): temp = [] #2i + 1 odds # (n - 2i -1) / 2 numEvens = int((n-magic[i])/2) numOdds = magic[i] #print("numEvens =", numEvens) temp += evens[:numEvens] evens = evens[numEvens:] temp += odds[:numOdds] odds = odds[numOdds:] temp += evens[:numEvens] evens = evens[numEvens:] result += temp #print(result) #print(result) print(" ".join([str(x) for x in result])) #for l in result: #for j in l: #print(j,) #print()
1471875000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n5\n1"]
1a6881aeb197b8ed429f46850eb27b9c
NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.
Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.
For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.
standard output
standard input
Python 3
Python
800
train_102.jsonl
cc7ad02d3c50f0a742261a162b06840f
512 megabytes
["3\n121\n5\n1000000000"]
PASSED
nt = int(input()) for tt in range(nt): s = max(map(int, list(input()))) print(s)
1626532500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0.000000", "13.000000"]
c4609bd2b4652cb5c2482b16909ec64a
NoteIn the first test the sequence is already sorted, so the answer is 0.
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi &gt; pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi &lt; pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent.
In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation p. The numbers are separated by spaces.
standard output
standard input
Python 3
Python
1,900
train_004.jsonl
261e1491695a20540a455845278ef8dc
256 megabytes
["2\n1 2", "5\n3 5 2 4 1"]
PASSED
#!/usr/bin/python3 import sys class CumTree: def __init__(self, a, b): self.a = a self.b = b self.count = 0 if a == b: return mid = (a + b) // 2 self.levo = CumTree(a, mid) self.desno = CumTree(mid+1, b) def manjsi(self, t): if self.a >= t: return 0 if self.b < t: return self.count return self.levo.manjsi(t) + self.desno.manjsi(t) def vstavi(self, t): if self.a <= t <= self.b: self.count += 1 if self.a == self.b: return self.levo.vstavi(t) self.desno.vstavi(t) n = int(sys.stdin.readline()) p = [int(x) for x in sys.stdin.readline().strip().split()] ct = CumTree(1, 4096) vsota = 0 while len(p) > 0: x = p.pop() vsota += ct.manjsi(x) ct.vstavi(x) k, d = vsota // 2, vsota % 2 print("%f" % (4*k + d))
1380900600
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
1 second
["6\ntabbat", "6\noxxxxo", "0", "20\nababwxyzijjizyxwbaba"]
554115bec46bb436a0a1ddf8c05a2d08
NoteIn the first example, "battab" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 50$$$) — the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.
standard output
standard input
Python 3
Python
1,100
train_007.jsonl
f8d9d5e737d926b02d3d943ba12a857c
256 megabytes
["3 3\ntab\none\nbat", "4 2\noo\nox\nxo\nxx", "3 5\nhello\ncodef\norces", "9 4\nabab\nbaba\nabcd\nbcde\ncdef\ndefg\nwxyz\nzyxw\nijji"]
PASSED
x,y=map(int,input().split()) a=set() l=[] for i in range(x): l.append(input()) a.add(l[-1]) s=set() m='' for i in a: r=i[::-1] if i!=r and r in a and r not in s: s.add(i) elif r==i and len(i)>len(m): m=i s=''.join(list(s)) o=s+m+s[::-1] print(len(o)) print(o)
1581771900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48"]
140737ecea3ff1c71cdd5e51e6abf297
null
You are given three integers $$$a \le b \le c$$$.In one move, you can add $$$+1$$$ or $$$-1$$$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers $$$A \le B \le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer. In the first line print $$$res$$$ — the minimum number of operations you have to perform to obtain three integers $$$A \le B \le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$. On the second line print any suitable triple $$$A, B$$$ and $$$C$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line as three space-separated integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a \le b \le c \le 10^4$$$).
standard output
standard input
PyPy 2
Python
2,000
train_001.jsonl
0d1806a7713772b6b558ba99f1f732bc
256 megabytes
["8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46"]
PASSED
for _ in xrange(input()): a, b, c = map(int, raw_input().strip().split()) ans = float('inf') A, B, C = 0, 0, 0 for x in xrange(1, 2 * a + 1): for y in xrange(x, 2 * b + 1, x): z1 = (c / y) * y z2 = z1 + y z = [z1, z2] cur = [abs(a - x) + abs(b - y) + abs(c - z[i]) for i in xrange(2)] if (cur[0] < cur[1]): z = z1 else: z = z2 cur = min(cur) if ans > cur: ans = cur A, B, C = x, y, z print ans print A, B, C
1582554900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["baba\naaaaaa\n-1"]
710c7211d23cf8c01fae0b476a889276
NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.
Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.
For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.
The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.
standard output
standard input
Python 3
Python
1,000
train_106.jsonl
0a429e6459b1b35894a02ad19c0e97b5
256 megabytes
["3\nbaba\nba\naa\naaa\naba\nab"]
PASSED
def lcm(a,b): if a<b: sm=a else: sm=b for i in range(1,sm+1): if a%i==0 and b%i==0: hcf=i return int(a*b/hcf) T=int(input()) for i in range(T): t=str(input()) s=str(input()) p=s q=t l1=int(lcm(int(len(s)),int(len(t)))/int(len(s))) l2=int(lcm(int(len(s)),int(len(t)))/int(len(t))) for j in range(l1-1): s+=p for k in range(l2-1): t+=q if (s==t): print(s,"\n") else: print("-1\n")
1610634900
[ "number theory", "math", "strings" ]
[ 0, 0, 0, 1, 1, 0, 1, 0 ]
2 seconds
["9", "8"]
f010eebcf35357f8c791a1c6101189ba
NoteIn the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.
Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.
The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.
standard output
standard input
Python 3
Python
2,200
train_074.jsonl
b3b362d8ee8d5790f5f91b32ef29d636
256 megabytes
["5 2 3\n1 2\n1 3\n3 4\n5 3", "5 3 2\n1 2\n1 3\n3 4\n5 3"]
PASSED
from collections import defaultdict from collections import deque from functools import reduce n, x, y = [int(x) for x in input().split()] E = defaultdict(set) for i in range(n-1): u, v = [int(x) for x in input().split()] E[u].add(v) E[v].add(u) if x > y: for v in E: if len(E[v]) == n-1: print((n-2)*y + x) break elif len(E[v]) > 1: print((n-1)*y) break else: visited = {v : False for v in E} stack = [1] topsorted = deque() while stack: v = stack.pop() if visited[v]: continue visited[v] = True topsorted.appendleft(v) stack.extend(E[v]) chopped = set() ans = 0 for v in topsorted: ans += max(0, len(E[v])-2) if len(E[v]) > 2: S = E[v].intersection(chopped) S1 = {S.pop(), S.pop()} for u in E[v]: if not u in S1: E[u].remove(v) E[v].clear() E[v].update(S1) chopped.add(v) print(ans*y + (n-1-ans)*x)
1454087400
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["YES\nNO\nYES\nYES\nYES\nNO\nYES\nYES\nYES\nYES\nYES\nYES\nNO"]
7975af65a23bad6a0997921c7e31d3ca
NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers.
Nezzar's favorite digit among $$$1,\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$, for each $$$1 \le i \le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.
For each integer in each test case, print "YES" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower).
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 9$$$) — the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q \le 10^4$$$, $$$1 \le d \le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$ ($$$1 \le a_i \le 10^9$$$).
standard output
standard input
PyPy 3-64
Python
1,100
train_087.jsonl
ada615f7bea1f69afd5027fd58bf1110
512 megabytes
["2\n3 7\n24 25 27\n10 7\n51 52 53 54 55 56 57 58 59 60"]
PASSED
def islucky(num,k): f=False while num>0: r=num%10 if r==k: f=True break num=num//10 return f t=int(input()) for _ in range(t): n,k=map(int,input().split()) ar=list(map(int,input().split())) for x in range(n): num=ar[x] if num>=10*k: print("YES") else: x=0 s=num m=False while x<num: if islucky(x,k) and islucky(s,k): m=True break elif x%k==0 and islucky(s,k): m=True break elif islucky(x,k) and s%k==0: m=True break elif x%k==0 and s%k==0: m=True break else: x+=1 s-=1 if m: print("YES") else: print("NO")
1611844500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6 14 1 25", "12 10 12"]
f41be1fcb6164181c49b37ed9313696e
null
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
standard output
standard input
PyPy 3
Python
2,000
train_004.jsonl
6b530b28de0ae51d3e22876fe461e697
256 megabytes
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
PASSED
from __future__ import division, print_function py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') def readnumbers(self, n,zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1 curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) while len(A)<n: if curpos>=buffsize: buffsize += len(self.read2buffer()) if curpos==buffsize: break small_buff = min(32,buffsize-curpos) s = self.stream.read(small_buff) i = 0 while i<small_buff and len(A)<n: if s[i] >= b'0'[0]: numb = 10 * numb + (conv(s[i]) - 48) elif s[i] != b'\r'[0]: A.append(sign*numb); numb = zero; sign = 1 elif s[i] == b'-'[0]: sign = -1 i += 1 curpos += i if curpos == buffsize and len(A)<n: A.append(sign*numb) assert(len(A)==n) if self.stream.tell()!=curpos: self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3*m, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0]-1) u = int(inp[_*3+1]-1) w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) inp = sys.stdin.readnumbers(n, 0.0) best = [inp[i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ')
1518793500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["..X", ".X.X.X", "...XX"]
94f52d78b1347fd04c9d39e8789a73ec
NoteThe lexicographical comparison of is performed by the &lt; operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai &lt; bi, and for any j (1 ≤ j &lt; i) aj = bj.
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner. Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one. More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots). Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
For each query print "." if the slot should be empty and "X" if the slot should be charged.
The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
standard output
standard input
Python 2
Python
1,900
train_036.jsonl
fe8711e230a503d5c9532532f5e4cc45
256 megabytes
["3 1 3\n1\n2\n3", "6 3 6\n1\n2\n3\n4\n5\n6", "5 2 5\n1\n2\n3\n4\n5"]
PASSED
#!/usr/bin/python def query(n, k, x): if k == 0: return 0 if k == n: return 1 if n % 2 == 0: evens = max(2, n - 2*k + 2) odds = n + 1 k -= n/2 if k > 0: odds = n - 1 - 2*k + 2 if x % 2 == 0: return int(x >= evens) else: return int(x >= odds) else: if x == n: return 1 k -= 1 evens = max(2, n - 1 - 2*k + 2) odds = n + 1 k -= n/2 if k > 0: odds = n - 2 - 2*k + 2 if x % 2 == 0: return int(x >= evens) else: return int(x >= odds) def solve(): n, k, p = map(int, tuple(raw_input().split())) res = "" for i in xrange(p): x = int(raw_input()) res += ".X"[query(n, k, x)] print res solve() #def testit(): #for n in xrange(1, 10): #for k in xrange(0, n + 1): #res = "" #for i in xrange(1, n + 1): #res += ".X"[query(n, k, i)] #print n, k, res #testit()
1312714800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n7\n0\n1"]
2f12b2bb23497119bb70ca0839991d68
null
You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \le i &lt; j \le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \le a_i + a_j \le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable: $$$i=1$$$ and $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$); $$$i=1$$$ and $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$).
For each test case, output a single integer — the number of index pairs $$$(i, j)$$$ ($$$i &lt; j$$$), such that $$$l \le a_i + a_j \le r$$$.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,300
train_097.jsonl
ad8c38b2611f4b80a5ad0735bdebfc1a
256 megabytes
["4\n3 4 7\n5 1 2\n5 5 8\n5 1 2 4 3\n4 100 1000\n1 1 1 1\n5 9 13\n2 5 5 1 1"]
PASSED
# _ ##################################################################################################################### def nPairs(lengthOfArray, l, r, array): iFinal = lengthOfArray - 1 array.sort() total = 0 for i in range(iFinal): curr_l, curr_r = l - array[i], r - array[i] if curr_r < array[i+1]: break elif curr_l > array[-1]: continue if curr_l <= array[i]: iFirst = i + 1 else: iFirst = binSearchLowBound(curr_l, i+1, lengthOfArray, array) if curr_r >= array[-1]: iLast = iFinal else: iLast = binSearchUpBound(curr_r, i+1, lengthOfArray, array) # print(curr_l, curr_r, iFirst, iLast) total += iLast - iFirst + 1 return total def binSearchLowBound(value, iLow, iHigh, array): iEstimated = (iLow + iHigh)//2 if array[iEstimated] < value: return binSearchLowBound(value, iEstimated+1, iHigh, array) elif array[iEstimated - 1] >= value: return binSearchLowBound(value, iLow, iEstimated, array) return iEstimated def binSearchUpBound(value, iLow, iHigh, array): iEstimated = (iLow + iHigh)//2 if array[iEstimated] > value: return binSearchUpBound(value, iLow, iEstimated, array) elif array[iEstimated+1] <= value: return binSearchUpBound(value, iEstimated+1, iHigh, array) return iEstimated def testCase_1538c(): return map(int, input().split(' ')), list(map(int, input().split(' '))) nTestCases = int(input()) testCases = tuple(testCase_1538c() for x in range(nTestCases)) tuple(print(nPairs(*testCase[0], testCase[1])) for testCase in testCases)
1623335700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["11122", "21122", "111111", "2212222"]
43336ae43d65a11c80337d0b6ea6b934
NoteBelow you can see the tree in the first sample : If $$$k = 1$$$ then the first player can cut the edge $$$(1, 2)$$$.If $$$k = 2$$$ or $$$k = 3$$$, the first player can cut the edge $$$(2, 4)$$$, after that only the edges $$$(1, 2)$$$ and $$$(2, 3)$$$ remain. After the second players move, there will be a single edge left for the first player to cut. So first player wins.
After many unsuccessful tries, Mashtali decided to copy modify an AtCoder problem. So here is his copied new problem:There is a tree with $$$n$$$ vertices and some non-empty set of the vertices are pinned to the ground.Two players play a game against each other on the tree. They alternately perform the following action: Remove an edge from the tree, then remove every connected component that has no pinned vertex.The player who cannot move loses(every edge has been deleted already). You are given the tree, but not the set of the pinned vertices. Your task is to determine, for each $$$k$$$, the winner of the game, if only the vertices $$$1, 2, 3, \ldots, k$$$ are pinned and both players play optimally.
Print a string of length $$$n$$$. The $$$i$$$-th character should be '1' if the first player wins the $$$i$$$-th scenario, and '2' otherwise.
The first line of input contains an integer $$$n$$$ — the number of vertices ($$$1 \le n \le 3 \cdot 10^5$$$). The $$$i$$$-th of the following $$$n-1$$$ lines contains two integers $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — the endpoints of the $$$i$$$-th edge. It's guaranteed that these edges form a tree.
standard output
standard input
PyPy 3-64
Python
3,100
train_085.jsonl
0a0e63651df7f1ebcba6908ebee9c109
256 megabytes
["5\n1 2\n2 3\n2 4\n4 5", "5\n1 2\n2 3\n1 4\n4 5", "6\n1 2\n2 4\n5 1\n6 3\n3 2", "7\n1 2\n3 7\n4 6\n2 3\n2 4\n1 5"]
PASSED
import sys input = sys.stdin.buffer.readline N = int(input()) T = [[] for i in range(N)] for i in range(1, N): u, v = map(int, input().split()) u -= 1 v -= 1 T[u].append(v) T[v].append(u) stk = [(1, 0)] par = [-1] * N dp = [0] * N while stk: t, u = stk.pop() if t == 1: stk.append((2, u)) for v in T[u]: if v == par[u]: continue par[v] = u stk.append((1, v)) else: for v in T[u]: if v == par[u]: continue dp[u] ^= dp[v] + 1 vis = [False] * N vis[0] = True ans = dp[0] res = [] for i in range(N): u = i while not vis[u]: ans ^= (dp[u] + 1) ^ dp[u] ^ 1 vis[u] = True u = par[u] res.append('2' if ans == 0 else '1') print('%s' % "".join(res))
1637678100
[ "games", "trees" ]
[ 1, 0, 0, 0, 0, 0, 0, 1 ]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
6709c8078cd29e69cf1be285071b2527
null
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
standard output
standard input
Python 3
Python
1,200
train_013.jsonl
3423f3eafa77e4ca2d087dbeafbf72b5
256 megabytes
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
PASSED
for _ in range(int(input())): a = input() b = input() l1,l2 = len(a),len(b) f = 1 i,j = 0,0 while i < l1: last = a[i] c = 0 while i < l1 and a[i] == last: c += 1 i += 1 p = 0 while j < l2 and b[j] == last: p += 1 j += 1 if p < c: f = 0 break #print(i,j) if f and j == l2: print("YES") else: print("NO")
1560955500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["YES\nNO"]
941adee47c2a28588ebe7dfe16e0c91a
NoteIn the first test case one of the reorders could be $$$[1, 2, 5]$$$. The sum is equal to $$$(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$$$. The brackets denote the inner sum $$$\sum_{j=i}^{n}{\frac{a_j}{j}}$$$, while the summation of brackets corresponds to the sum over $$$i$$$.
For a given array $$$a$$$ consisting of $$$n$$$ integers and a given integer $$$m$$$ find if it is possible to reorder elements of the array $$$a$$$ in such a way that $$$\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$$$ equals $$$m$$$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $$$\frac{5}{2}=2.5$$$.
For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.
The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 100$$$). The test cases follow, each in two lines. The first line of a test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$). The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the elements of the array.
standard output
standard input
Python 3
Python
800
train_000.jsonl
c6369d45756b7a324a1962585eb1df08
256 megabytes
["2\n3 8\n2 5 1\n4 4\n0 1 2 3"]
PASSED
t = int(input()) while t>0: t = t-1 n,m = map(int,input().split()) arr = list(map(int,input().split())) if (sum(arr) == m): print("Yes") else: print("No")
1603548300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n2\n21\n121\n212"]
1a5f266b49aadbeef59e19bcf5524a57
NoteThe only numbers with the sum of digits equal to $$$2$$$ without zeros are $$$2$$$ and $$$11$$$. But the last one has two ones in a row, so it's not valid. That's why the answer is $$$2$$$.The only numbers with the sum of digits equal to $$$3$$$ without zeros are $$$111$$$, $$$12$$$, $$$21$$$, and $$$3$$$. The first one has $$$2$$$ ones in a row, so it's not valid. So the maximum valid number is $$$21$$$.The only numbers with the sum of digits equals to $$$4$$$ without zeros are $$$1111$$$, $$$211$$$, $$$121$$$, $$$112$$$, $$$13$$$, $$$31$$$, $$$22$$$, and $$$4$$$. Numbers $$$1111$$$, $$$211$$$, $$$112$$$, $$$22$$$ aren't valid, because they have some identical digits in a row. So the maximum valid number is $$$121$$$.
Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $$$n$$$.Madoka is too tired of math to solve it herself, so help her to solve this problem!
For each test case print the maximum number you can obtain.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the required sum of the digits.
standard output
standard input
PyPy 3
Python
800
train_096.jsonl
bceffa82c363e842171628c41d2a1582
256 megabytes
["5\n1\n2\n3\n4\n5"]
PASSED
from math import inf from collections import * import math, os, sys, heapq, bisect, random from functools import lru_cache from itertools import * def inp(): return sys.stdin.readline().rstrip("\r\n") def out(var): sys.stdout.write(str(var)) # for fast output, always take string def inpu(): return int(inp()) def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) M,M1=1000000007,998244353 def main(): how_much_noob_I_am = 1 how_much_noob_I_am = inpu() for i in range(how_much_noob_I_am): n = inpu() ans="1" p=1 while(p<n): if ans[-1]=="1": ans+="2" p+=2 else: ans+="1" p+=1 ans2="2" p2=2 while(p2<n): if ans2[-1]=="1": ans2+="2" p2+=2 else: ans2+="1" p2+=1 if p==n and p2==n: print(max(int(ans),int(ans2))) continue if p==n: print(ans) else: print(ans2) if __name__ == '__main__': main()
1647009300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4", "7", "12"]
a569cd5f8bf8aaf011858f839e91848a
NoteIn the first test case it's optimal to install two towers with efficiencies $$$2$$$ at vertices $$$1$$$ and $$$3$$$.In the second test case it's optimal to install a tower with efficiency $$$1$$$ at vertex $$$1$$$ and two towers with efficiencies $$$3$$$ at vertices $$$2$$$ and $$$5$$$.In the third test case it's optimal to install two towers with efficiencies $$$6$$$ at vertices $$$1$$$ and $$$2$$$.
You are given a tree with $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The height of the $$$i$$$-th vertex is $$$h_i$$$. You can place any number of towers into vertices, for each tower you can choose which vertex to put it in, as well as choose its efficiency. Setting up a tower with efficiency $$$e$$$ costs $$$e$$$ coins, where $$$e &gt; 0$$$.It is considered that a vertex $$$x$$$ gets a signal if for some pair of towers at the vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$, but it is allowed that $$$x = u$$$ or $$$x = v$$$) with efficiencies $$$e_u$$$ and $$$e_v$$$, respectively, it is satisfied that $$$\min(e_u, e_v) \geq h_x$$$ and $$$x$$$ lies on the path between $$$u$$$ and $$$v$$$.Find the minimum number of coins required to set up towers so that you can get a signal at all vertices.
Print one integer — the minimum required number of coins.
The first line contains an integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$h_i$$$ ($$$1 \le h_i \le 10^9$$$) — the heights of the vertices. Each of the next $$$n - 1$$$ lines contain a pair of numbers $$$v_i, u_i$$$ ($$$1 \le v_i, u_i \le n$$$) — an edge of the tree. It is guaranteed that the given edges form a tree.
standard output
standard input
PyPy 3-64
Python
2,500
train_090.jsonl
786ea06f699169284910a078e5e27b97
256 megabytes
["3\n1 2 1\n1 2\n2 3", "5\n1 3 3 1 3\n1 3\n5 4\n4 3\n2 3", "2\n6 1\n1 2"]
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") from collections import defaultdict as dd from collections import deque import bisect import heapq def ri(): return int(input()) def rl(): return list(map(int, input().split())) def solve(): n = ri() H = rl() G = dd(list) P = dd(lambda:-1) for i in range(n - 1): u, v = rl() u -= 1 v -= 1 G[u].append(v) G[v].append(u) root = 0 highest = 0 for i in range(n): if H[i] > highest: root = i highest = H[i] P[root] = root curr = [root] while curr: node = curr.pop() for nbr in G[node]: if P[nbr] == -1: P[nbr] = node curr.append(nbr) maxbelow = [0] * n # def dfs(u): # for v in G[u]: # if v != P[u]: # dfs(v) # maxbelow[u] = max(maxbelow[u], maxbelow[v], H[v]) # # # dfs(root) layers = [root] curr = [root] while curr: nxt = [] for node in curr: for nbr in G[node]: if nbr != P[node]: nxt.append(nbr) layers += nxt curr = nxt for u in layers[::-1]: for v in G[u]: if v != P[u]: maxbelow[u] = max(maxbelow[u], maxbelow[v], H[v]) ans = 0 for i in range(n): if i == root: continue ans += max(0, H[i] - maxbelow[i]) paths = [] for v in G[root]: paths.append(max(H[v], maxbelow[v])) if len(paths) == 1: ans += H[root] + H[root] - paths[0] else: paths.sort() ans += 2 * H[root] - paths[-1] - paths[-2] print (ans) mode = 's' if mode == 'T': t = ri() for i in range(t): solve() else: solve()
1644676500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["3"]
de87bb6ffd3c703d8845d4dd301bdbf5
NoteThe answer for the first test sample is subsequence [1, 2, 3].
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Print the length of the longest common subsequence.
The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.
standard output
standard input
Python 3
Python
1,900
train_008.jsonl
8713fe1256830155b10308bdc1b64283
256 megabytes
["4 3\n1 4 2 3\n4 1 2 3\n1 2 4 3"]
PASSED
# ========== //\\ //|| ||====//|| # || // \\ || || // || # || //====\\ || || // || # || // \\ || || // || # ========== // \\ ======== ||//====|| # code def solve(): n, k = map(int, input().split()) c = [ [-1 for i in range(n + 1)] for i in range(k)] dp = [0 for i in range(n + 1)] a = [] for i in range(k): b = list(map(int, input().split())) for j, v in enumerate(b): c[i][v] = j a.append(b) for i in range(n): curpos = a[0][i] dp[i] = 1 for j in range(i): prevpos = a[0][j] ok = True for p in range(k): if c[p][curpos] < c[p][prevpos]: ok = False break if ok: dp[i] = max(dp[i], dp[j] + 1) print(max(dp)) return def main(): t = 1 # t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main()
1409383800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["0 \n1 -1 1"]
a89c585ebd9608141399c813385c04c6
NoteIn the first test case of the example, both teams get $$$1$$$ point since the game between them is a tie.In the second test case of the example, team $$$1$$$ defeats team $$$2$$$ (team $$$1$$$ gets $$$3$$$ points), team $$$1$$$ loses to team $$$3$$$ (team $$$3$$$ gets $$$3$$$ points), and team $$$2$$$ wins against team $$$3$$$ (team $$$2$$$ gets $$$3$$$ points).
A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game: the game may result in a tie, then both teams get $$$1$$$ point; one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.
For each test case, print $$$\frac{n(n - 1)}{2}$$$ integers describing the results of the games in the following order: the first integer should correspond to the match between team $$$1$$$ and team $$$2$$$, the second — between team $$$1$$$ and team $$$3$$$, then $$$1$$$ and $$$4$$$, ..., $$$1$$$ and $$$n$$$, $$$2$$$ and $$$3$$$, $$$2$$$ and $$$4$$$, ..., $$$2$$$ and $$$n$$$, and so on, until the game between the team $$$n - 1$$$ and the team $$$n$$$. The integer corresponding to the game between the team $$$x$$$ and the team $$$y$$$ should be $$$1$$$ if $$$x$$$ wins, $$$-1$$$ if $$$y$$$ wins, or $$$0$$$ if the game results in a tie. All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case is described by one line containing one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of teams.
standard output
standard input
PyPy 3-64
Python
1,500
train_082.jsonl
2e26d2be2d21d8ed4210d12a08904773
256 megabytes
["2\n2\n3"]
PASSED
for _ in range(int(input())): n = int(input()) if n % 2 == 1: cnt = 1 for i in range(n * (n - 1) // 2): print(cnt, end=" ") if cnt == 1: cnt = -1 else: cnt = 1 print() else: for i in range(n): for j in range(i + 1, n): if j - i == n / 2: print(0, end=" ") elif j - i <= (n - 2) / 2: print(1, end=" ") else: print(-1, end=" ") print()
1613399700
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["NO\nNO\nYES\nNO\nYES\nYES\nNO\nYES"]
ee27020ca43546993b82357527585831
NoteIn the first example, $$$6$$$ can be represented as $$$6$$$, $$$1 \cdot 6$$$, $$$2 \cdot 3$$$. But $$$3$$$ and $$$1$$$ are not a good numbers because they are not divisible by $$$2$$$, so there is only one way.In the second example, $$$12$$$ can be represented as $$$6 \cdot 2$$$, $$$12$$$, $$$3 \cdot 4$$$, or $$$3 \cdot 2 \cdot 2$$$. The first option is suitable. The second is— no, because $$$12$$$ is not beautiful number ($$$12 = 6 \cdot 2$$$). The third and fourth are also not suitable, because $$$3$$$ is not good number.In the third example, $$$36$$$ can be represented as $$$18 \cdot 2$$$ and $$$6 \cdot 6$$$. Therefore it can be decomposed in at least two ways.
Madoka is going to enroll in "TSUNS PTU". But she stumbled upon a difficult task during the entrance computer science exam: A number is called good if it is a multiple of $$$d$$$. A number is called beatiful if it is good and it cannot be represented as a product of two good numbers. Notice that a beautiful number must be good.Given a good number $$$x$$$, determine whether it can be represented in at least two different ways as a product of several (possibly, one) beautiful numbers. Two ways are different if the sets of numbers used are different.Solve this problem for Madoka and help her to enroll in the best school in Russia!
For each set of input data, output "NO" if the number cannot be represented in at least two ways. Otherwise, output "YES". You can output each letter in any case (for example, "YES", "Yes", "yes", "yEs", "yEs" will be recognized as a positive answer).
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — number of test cases. Below comes their description. Each test case consists of two integers $$$x$$$ and $$$d$$$, separated by a space ($$$2 \leq x, d \leq 10^9$$$). It is guaranteed that $$$x$$$ is a multiple of $$$d$$$.
standard output
standard input
Python 3
Python
1,900
train_096.jsonl
c4c7b447b1bf2ea91ece296c562df2e5
256 megabytes
["8\n\n6 2\n\n12 2\n\n36 2\n\n8 2\n\n1000 10\n\n2376 6\n\n128 4\n\n16384 4"]
PASSED
t = int(input()) def isPrime(x): i = 2 while (i*i <= x): if (x % i == 0): return False i += 1 return True def solve(x, d): cnt = 0 # print(x,d) while (x % d == 0): cnt += 1 x //= d if (cnt <= 1): print("NO") return d_is_prime = isPrime(d) # print("d is prime", d_is_prime) x_is_prime = isPrime(x) # print("x is prime", x_is_prime) if (not x_is_prime): print("YES") return # x is prime and cnt >= 2 if (d_is_prime): print("NO") return # x is prime and d is not prime cnt >= 2 if (cnt > 3): print("YES") return # x is prime and d is not prime 2 >= cnt >= 3 i = 2 c = 0 while (i*i <= d): if (d % i == 0): if (i*x != d or (d//i)*x != d): c += 1 i += 1 # print("hard", x, d, cnt, c) if (c > 0 and cnt == 3): print("YES") else: print("NO") for i in range(t): x, d = [int(i) for i in input().split(" ")] solve(x, d) # solve(6, 2) # NO # print("-------------------------------") # solve(12, 2) # NO # print("-------------------------------") # solve(36, 2) # YES # print("-------------------------------") # solve(8, 2) # NO # print("-------------------------------") # solve(1000, 10) # YES # print("-------------------------------") # solve(2376, 6) # YES # print("-------------------------------") # solve(128, 4) # NO # print("-------------------------------") # solve(16384, 4) # YES # print("-------------------------------") # solve(28629151, 31) # NO # print("-------------------------------") # solve(19683, 9) # YES # print("-------------------------------") # solve(130321, 361) # NO # print("-------------------------------")
1647009300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["7", "2"]
b3d093272fcb289108fe45be8c72f38e
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
standard output
standard input
Python 3
Python
1,900
train_001.jsonl
9c3b3af8a5de182cb68e237b62d1e00e
256 megabytes
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
PASSED
import bisect; 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=int(input()); a=getIntList(); anums=[(a[i], i) for i in range(n)]; anums.sort(); location=0; length=0; k=1; pieces=[]; def upgrade(x): curr=(x, x+1) i=bisect.bisect(pieces, curr); joinLeft=False; joinRight=False; if i>0 and pieces[i-1][1]==x: joinLeft=True; if i<len(pieces) and pieces[i][0]==x+1: joinRight=True; if joinLeft: if joinRight: pieces[i-1]=(pieces[i-1][0], pieces[i][1]) pieces.pop(i); else: pieces[i-1]=(pieces[i-1][0], x+1); return pieces[i-1][1]-pieces[i-1][0]; else: if joinRight: pieces[i]=(x, pieces[i][1]) else: pieces.insert(i, curr); return pieces[i][1]-pieces[i][0]; currLength=0; currSum=0; for x in anums: currSum+=1; val, num=x; l=upgrade(num); #print(pieces); currLength=max(currLength, l); #print(currLength,"*",len(pieces),"==",currSum) if currLength*len(pieces)==currSum: currK=val+1; currLocation=len(pieces); if currLocation>location: location=currLocation; k=currK; if (location+2)*currLength-1>n: break; print(k);
1526574900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
5 seconds
["124780545", "798595483"]
b4f8a6f5b1d1fa641514e10d18c316f7
null
Santa Claus has received letters from $$$n$$$ different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the $$$i$$$-th kid asked Santa to give them one of $$$k_i$$$ different items as a present. Some items could have been asked by multiple kids.Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following: choose one kid $$$x$$$ equiprobably among all $$$n$$$ kids; choose some item $$$y$$$ equiprobably among all $$$k_x$$$ items kid $$$x$$$ wants; choose a kid $$$z$$$ who will receive the present equipropably among all $$$n$$$ kids (this choice is independent of choosing $$$x$$$ and $$$y$$$); the resulting triple $$$(x, y, z)$$$ is called the decision of the Bot. If kid $$$z$$$ listed item $$$y$$$ as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Print the probatility that the Bot produces a valid decision as follows: Let this probability be represented as an irreducible fraction $$$\frac{x}{y}$$$. You have to print $$$x \cdot y^{-1} \mod 998244353$$$, where $$$y^{-1}$$$ is the inverse element of $$$y$$$ modulo $$$998244353$$$ (such integer that $$$y \cdot y^{-1}$$$ has remainder $$$1$$$ modulo $$$998244353$$$).
The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of kids who wrote their letters to Santa. Then $$$n$$$ lines follow, the $$$i$$$-th of them contains a list of items wanted by the $$$i$$$-th kid in the following format: $$$k_i$$$ $$$a_{i, 1}$$$ $$$a_{i, 2}$$$ ... $$$a_{i, k_i}$$$ ($$$1 \le k_i, a_{i, j} \le 10^6$$$), where $$$k_i$$$ is the number of items wanted by the $$$i$$$-th kid, and $$$a_{i, j}$$$ are the items themselves. No item is contained in the same list more than once. It is guaranteed that $$$\sum \limits_{i = 1}^{n} k_i \le 10^6$$$.
standard output
standard input
PyPy 2
Python
1,700
train_001.jsonl
d8d1d4b8782cbc4c1ac1a99b704407ae
256 megabytes
["2\n2 2 1\n1 1", "5\n2 1 2\n2 3 1\n3 2 4 3\n2 1 4\n3 4 3 2"]
PASSED
# template begins ##################################### # import libraries for input/ output handling # on generic level import atexit, io, sys # A stream implementation using an in-memory bytes # buffer. It inherits BufferedIOBase. buffer = io.BytesIO() sys.stdout = buffer # print via here @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) n=input() v=998244353 from fractions import Fraction as f b=[] k=[] for _ in range(n): c=map(int,raw_input().split()) b.append(c[0]) k.append(c[1:]) m={} for j in range(n): for i in k[j]: if i in m: m[i]+=1 else: m[i]=1 s=f(0,1) for j in range(n): p=0 for i in k[j]: p+=m[i] s+=f(p,b[j]) c=s.denominator c=c*((n*n)%v)%v c=pow(c,v-2,v) print (s.numerator*c)%v
1577457600
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
3 seconds
["2 3 5 7 11", "10 3 7"]
bf8bbbb225813cdf42e7a2e454f0b787
NoteNote that in the second sample, the array is already pairwise coprime so we printed it.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that: b is lexicographically greater than or equal to a. bi ≥ 2. b is pairwise coprime: for every 1 ≤ i &lt; j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z. Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?An array x is lexicographically greater than an array y if there exists an index i such than xi &gt; yi and xj = yj for all 1 ≤ j &lt; i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Output n space-separated integers, the i-th of them representing bi.
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b. The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
standard output
standard input
Python 3
Python
1,900
train_035.jsonl
d5c08d93def8fe7aba2270e294e86e97
256 megabytes
["5\n2 3 5 4 13", "3\n10 3 7"]
PASSED
import atexit import io import sys # Buffering IO _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) ppp = ('2 3 5 7 11 13 17 19 23 29 ' + '31 37 41 43 47 53 59 61 67 71 ' + '73 79 83 89 97 101 103 107 109 113 ' +'127 131 137 139 149 151 157 163 167 173 ' +'179 181 191 193 197 199 211 223 227 229 ' +'233 239 241 251 257 263 269 271 277 281 ' +'283 293 307 311 313 317 ') pp = [int(x) for x in ppp.split()] xx = [False] * 1500000 def f(aa): t = [] for p in pp: if aa % p == 0: while aa%p == 0: aa = aa//p t.append(p) if aa == 1: break if aa != 1: t.append(aa) for tt in t: for i in range(tt, 1500000, tt): xx[i]=True def main(): n = input() a = [int(x) for x in input().split()] b = [] for aa in a: if xx[aa] == False: b.append(aa) f(aa) else: kk = aa + 1 while xx[kk] == True: kk += 1 b.append(kk) f(kk) break t = 2 while len(b) < len(a): while xx[t] == True: t+=1 b.append(t) f(t) print(' '.join(str(x) for x in b)) if __name__ == '__main__': main()
1522771500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["1", "642377629"]
8508d39c069936fb402e4f4433180465
NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$.
William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i &lt; j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners.
Output a single integer  — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x &lt; M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$)  — the strengths of teams participating in a match.
standard output
standard input
PyPy 3-64
Python
2,500
train_107.jsonl
8b2d744a149d3800c66a18d088e48849
256 megabytes
["2\n1 2", "5\n1 5 2 11 14"]
PASSED
import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import cycle, permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) mod = 10**9 + 7 N = 2*10**6 inverse = [1]*(N+1) for i in range( 2, N + 1 ): inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) inverse[0]=0 N = int(input()) A = li() win_prop = [[1 for S in range(1<<N)] for i in range(N)] for i in range(N): for n in range(N): t = 1<<n for S in range(1<<n,1<<(n+1)): win_prop[i][S] = win_prop[i][S-t] * (A[i] * inverse[A[i]+A[n]] % mod) % mod dp = [1 for i in range(1<<N)] for S in range(1,1<<N): tmp = (S-1)&S while tmp: T,U = tmp,S-tmp val = dp[T] for i in range(N): if T>>i & 1: val *= win_prop[i][U] val %= mod dp[S] -= val dp[S] %= mod tmp = (tmp-1)&S res = 0 for S in range(1,1<<N): n = bin(S).count("1") prop = dp[S] for i in range(N): for j in range(N): if S>>i & 1 and (not S>>j & 1): prop *= A[i] * inverse[A[i]+A[j]] prop %= mod res += n * prop res %= mod print(res)
1630247700
[ "probabilities", "math", "graphs" ]
[ 0, 0, 1, 1, 0, 1, 0, 0 ]
1 second
["0", "2"]
10efa17a66af684dbc13c456ddef1b1b
null
You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair (ik, jk) meets the following conditions: ik + jk is an odd number and 1 ≤ ik &lt; jk ≤ n.In one operation you can perform a sequence of actions: take one of the good pairs (ik, jk) and some integer v (v &gt; 1), which divides both numbers a[ik] and a[jk]; divide both numbers by v, i. e. perform the assignments: and . Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.
Output the answer for the problem.
The first line contains two space-separated integers n, m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100). The second line contains n space-separated integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — the description of the array. The following m lines contain the description of good pairs. The k-th line contains two space-separated integers ik, jk (1 ≤ ik &lt; jk ≤ n, ik + jk is an odd number). It is guaranteed that all the good pairs are distinct.
standard output
standard input
PyPy 3
Python
2,100
train_003.jsonl
caa0ae34e1ca58574edf92dcd1bacb61
256 megabytes
["3 2\n8 3 8\n1 2\n2 3", "3 2\n8 12 8\n1 2\n2 3"]
PASSED
def g(i): u[i] = 0 for j in p[i]: if v[j] < 0 or u[v[j]] and g(v[j]): v[j] = i return 1 return 0 f = lambda: map(int, input().split()) n, m = f() s = k = 0 d = [[]] for i in f(): j = 2 t = [] while j * j <= i: while i % j == 0: t.append((j, k)) k += 1 i //= j j += 1 if i > 1: t.append((i, k)) k += 1 d.append(t) p = [[] for i in range(k)] for q in range(m): a, b = f() if b % 2: a, b = b, a for x, i in d[a]: for y, j in d[b]: if x == y: p[i].append(j) v = [-1] * k for i in range(k): u = [1] * k s += g(i) print(s)
1419438600
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["1\n-1\n1\n5"]
8d9fc054fb1541b70991661592ae70b1
NoteExplanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal.Explanation of the second test case: There are $$$n=3$$$ athletes. Athlete $$$1$$$ is superior to athlete $$$2$$$. Indeed athlete $$$1$$$ ranks better than athlete $$$2$$$ in the marathons $$$1$$$, $$$2$$$ and $$$3$$$. Athlete $$$2$$$ is superior to athlete $$$3$$$. Indeed athlete $$$2$$$ ranks better than athlete $$$3$$$ in the marathons $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$. Athlete $$$3$$$ is superior to athlete $$$1$$$. Indeed athlete $$$3$$$ ranks better than athlete $$$1$$$ in the marathons $$$3$$$, $$$4$$$ and $$$5$$$. Explanation of the third test case: There are $$$n=3$$$ athletes. Athlete $$$1$$$ is superior to athletes $$$2$$$ and $$$3$$$. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete $$$2$$$ is superior to athlete $$$3$$$. Athlete $$$3$$$ is not superior to any other athlete. Explanation of the fourth test case: There are $$$n=6$$$ athletes. Athlete $$$1$$$ is superior to athletes $$$3$$$, $$$4$$$, $$$6$$$. Athlete $$$2$$$ is superior to athletes $$$1$$$, $$$4$$$, $$$6$$$. Athlete $$$3$$$ is superior to athletes $$$2$$$, $$$4$$$, $$$6$$$. Athlete $$$4$$$ is not superior to any other athlete. Athlete $$$5$$$ is superior to athletes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$6$$$. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete $$$6$$$ is only superior to athlete $$$4$$$.
The Olympic Games have just started and Federico is eager to watch the marathon race.There will be $$$n$$$ athletes, numbered from $$$1$$$ to $$$n$$$, competing in the marathon, and all of them have taken part in $$$5$$$ important marathons, numbered from $$$1$$$ to $$$5$$$, in the past. For each $$$1\le i\le n$$$ and $$$1\le j\le 5$$$, Federico remembers that athlete $$$i$$$ ranked $$$r_{i,j}$$$-th in marathon $$$j$$$ (e.g., $$$r_{2,4}=3$$$ means that athlete $$$2$$$ was third in marathon $$$4$$$).Federico considers athlete $$$x$$$ superior to athlete $$$y$$$ if athlete $$$x$$$ ranked better than athlete $$$y$$$ in at least $$$3$$$ past marathons, i.e., $$$r_{x,j}&lt;r_{y,j}$$$ for at least $$$3$$$ distinct values of $$$j$$$.Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.
For each test case, print a single integer — the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print $$$-1$$$. If there is more than such one athlete, print any of them.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 50\,000$$$) — the number of athletes. Then $$$n$$$ lines follow, each describing the ranking positions of one athlete. The $$$i$$$-th of these lines contains the $$$5$$$ integers $$$r_{i,1},\,r_{i,2},\,r_{i,3},\,r_{i,4},\, r_{i,5}$$$ ($$$1\le r_{i,j}\le 50\,000$$$) — the ranking positions of athlete $$$i$$$ in the past $$$5$$$ marathons. It is guaranteed that, in each of the $$$5$$$ past marathons, the $$$n$$$ athletes have distinct ranking positions, i.e., for each $$$1\le j\le 5$$$, the $$$n$$$ values $$$r_{1,j},\, r_{2, j},\, \dots,\, r_{n, j}$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$50\,000$$$.
standard output
standard input
PyPy 3-64
Python
1,500
train_098.jsonl
addf45c7cc607dec8191bc4280e147fc
256 megabytes
["4\n1\n50000 1 50000 50000 50000\n3\n10 10 20 30 30\n20 20 30 10 10\n30 30 10 20 20\n3\n1 1 1 1 1\n2 2 2 2 2\n3 3 3 3 3\n6\n9 5 3 7 1\n7 4 1 6 8\n5 6 7 3 2\n6 7 8 8 6\n4 2 2 4 5\n8 3 6 9 4"]
PASSED
def win(a, b): cnt = 0 for i in range(5): if a[i] < b[i]: cnt += 1 if cnt >= 3: return a return b for _ in range(int(input())): n = int(input()) l = [] for i in range(n): l.append(list(map(int, input().split()))) ini = l[0] idx = 0 for i in range(1, n): if ini != win(ini, l[i]): idx = i ini = l[i] f = 1 for i in range(n): if ini != win(ini, l[i]): f = 0 for i in range(n): if ini != win(l[i], ini): f = 0 if not f: print(-1) else: print(idx+1)
1627223700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
0.5 seconds
["YES\n2 2 1 1", "YES\n2 1 2 1 1", "NO"]
973ef4e00b0489261fce852af11aa569
null
You are given an array of $$$n$$$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.Both groups have to be non-empty.
In the first line print "YES" (without quotes), if it is possible to split the integers into two groups as required, and "NO" (without quotes) otherwise. If it is possible to split the integers, in the second line print $$$n$$$ integers, where the $$$i$$$-th integer is equal to $$$1$$$ if the integer $$$a_i$$$ should be in the first group, and $$$2$$$ otherwise. If there are multiple solutions, print any.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.
standard output
standard input
PyPy 3
Python
2,900
train_069.jsonl
d0fb462219c501f38659407c24be1fd3
256 megabytes
["4\n2 3 6 7", "5\n6 15 35 77 22", "5\n6 10 15 1000 75"]
PASSED
import sys def gcd(l): if len(l)==0: return 0 if len(l)==1: return l[0] if len(l)==2: if l[1]==0: return l[0] return gcd([l[1],l[0]%l[1]]) return gcd([gcd(l[:-1]),l[-1]]) def brute_force(l1,l2,l,sol): if len(l)==0: g1=gcd(l1) g2=gcd(l2) return g1==1 and g2==1,sol res,s=brute_force(l1+[l[0]],l2,l[1:],sol+[1]) if res: return True,s return brute_force(l1,l2+[l[0]],l[1:],sol+[2]) def factor(n): res=[] i=2 while i*i<=n: if n%i==0: res.append(i) while n%i==0: n=int(n/i) i+=1 if n!=1: res.append(n) return res def dumpsol(sol): for v in sol: print(v,end=' ') n=int(sys.stdin.readline()) l=sys.stdin.readline().strip().split(" ")[0:n] l=[int(x) for x in l] if n<12: ret,sol=brute_force([],[],l,[]) if ret: print("YES") dumpsol(sol) else: print("NO") sys.exit() factors={} for i in range(10): for key in factor(l[i]): factors[key]=0 flists={} for f in factors: flists[f]=[] pos=0 found=False for v in l: if v%f!=0: found=True factors[f]+=1 flists[f].append(pos) if (factors[f]>9): break pos+=1 if not found: print("NO") sys.exit() oftf=[] isoftf={} for f in factors: if factors[f]==0: print("NO") sys.exit() if factors[f]<10: oftf.append(f) isoftf[f]=1 #print(oftf) sol=[1 for i in range(len(l))] x=l[0] sol[0]=2 oxf=factor(x) #print(oxf) xf=[] nxf=0 isxoftf={} for f in oxf: if f in isoftf: nxf+=1 isxoftf[f]=1 xf.append(f) else: sol[flists[f][0]]=2 nonxf=[] for f in oftf: if not f in isxoftf: nonxf.append(f) masks={} pos=0 #print(xf) #print(nonxf) for f in xf+nonxf: for v in flists[f]: if not v in masks: masks[v]=0 masks[v]|=1<<pos pos+=1 vals=[{} for i in range(len(masks)+1)] vals[0][0]=0 pos=0 mlist=[] for mask in masks: mlist.append(mask) cmask=masks[mask] cmask1=cmask<<10 #print(vals) for v in vals[pos]: vals[pos+1][v|cmask]=v # first number is always in group2 if (mask!=0): vals[pos+1][v|cmask1]=v pos+=1 #print(vals) #print(masks) #print(sol) test_val=((1<<len(xf))-1)|(((1<<len(oftf))-1)<<10) #print(test_val) for v in vals[pos]: if (v&test_val)==test_val: print("YES") #print(pos) while (pos!=0): #print(v) #print(vals[pos]) nv=vals[pos][v] #print(nv) if (nv^v<1024 and nv^v!=0): sol[mlist[pos-1]]=2 v=nv pos-=1 dumpsol(sol) sys.exit() print("NO") #print(oftf) #print(masks)
1564497300
[ "number theory", "probabilities" ]
[ 0, 0, 0, 0, 1, 1, 0, 0 ]
2 seconds
["90.0000000000", "135.0000000000", "270.0000000000", "36.8698976458"]
a67cdb7501e99766b20a2e905468c29c
NoteSolution for the first sample test is shown below: Solution for the second sample test is shown below: Solution for the third sample test is shown below: Solution for the fourth sample test is shown below:
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.
Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10 - 6.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of mannequins. Next n lines contain two space-separated integers each: xi, yi (|xi|, |yi| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.
standard output
standard input
Python 2
Python
1,800
train_005.jsonl
b6599d88f0d03dd7ce38328fb2b09053
256 megabytes
["2\n2 0\n0 2", "3\n2 0\n0 2\n-2 2", "4\n2 0\n0 2\n-2 0\n0 -2", "2\n2 1\n1 2"]
PASSED
def subtract(a1, a2): if a1 > a2 + 0.0000001: return a1-a2 elif abs(a1-a2) <= 0.0000001: return 0 return 360+a1-a2 def angle(a1, a2): import math return math.atan2(a2,a1)*180/math.pi def start(): n = input() degreesPositive = [] for _ in xrange(n): a1, a2 = map(int, raw_input().split()) degree = angle(a1, a2) if degree < 0: degreesPositive.append(degree+360) else: degreesPositive.append(degree) degreesPositive.sort() maxValue = abs(subtract(degreesPositive[len(degreesPositive)-1],degreesPositive[len(degreesPositive)-2])) for x in xrange(0, len(degreesPositive)-1): maxValue = abs(max(maxValue, subtract(degreesPositive[x], degreesPositive[x-1]))) if maxValue == 0: maxValue = 360 print "%.12f" % (360-maxValue) start()
1357659000
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 2 3 4 5 \n-1\n1 3 2 \n1 2 \n-1"]
88c8376ad65c5c932c15dc09d6c4d75f
null
A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was given four integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n)$$$ and $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$) and asked to find a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ that satisfies the following condition: $$$s = p_l + p_{l+1} + \ldots + p_r$$$. For example, for $$$n=5$$$, $$$l=3$$$, $$$r=5$$$, and $$$s=8$$$, the following permutations are suitable (not all options are listed): $$$p = [3, 4, 5, 2, 1]$$$; $$$p = [5, 2, 4, 3, 1]$$$; $$$p = [5, 2, 1, 3, 4]$$$. But, for example, there is no permutation suitable for the condition above for $$$n=4$$$, $$$l=1$$$, $$$r=1$$$, and $$$s=5$$$.Help Polycarp, for the given $$$n$$$, $$$l$$$, $$$r$$$, and $$$s$$$, find a permutation of numbers from $$$1$$$ to $$$n$$$ that fits the condition above. If there are several suitable permutations, print any of them.
For each test case, output on a separate line: $$$n$$$ integers — a permutation of length $$$n$$$ that fits the condition above if such a permutation exists; -1, otherwise. If there are several suitable permutations, print any of them.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$). Then $$$t$$$ test cases follow. Each test case consist of one line with four integers $$$n$$$ ($$$1 \le n \le 500$$$), $$$l$$$ ($$$1 \le l \le n$$$), $$$r$$$ ($$$l \le r \le n$$$), $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$). It is guaranteed that the sum of $$$n$$$ for all input data sets does not exceed $$$500$$$.
standard output
standard input
PyPy 3
Python
1,600
train_107.jsonl
2f5f644247eb261b1be9ac81041e2884
256 megabytes
["5\n5 2 3 5\n5 3 4 1\n3 1 2 4\n2 2 2 2\n2 1 1 3"]
PASSED
for _ in range(int(input())): n,l,r,s = map(int,input().split()) x = r-l +1 t = [] p = 1 b = True while x>1: t.append(p) s -= p if s<=0: b = False break p += 1 x -= 1 t.append(s) # print(t) if s<p: b = False # print(t) if t[-1]>n: if len(t)>1: k = t[-1]-n t[-1] = n to_add = k//(len(t)-1) tt = k%(len(t)-1) for i in range(len(t)-1): t[i] += to_add i = len(t)-2 while tt: t[i] += 1 i -= 1 tt -= 1 for i in t: if i>n or i<1: b = False break if len(set(t))<len(t): b = False if not b: print(-1) else: ans = [0]*n c = 0 v = set([i for i in range(1,n+1)]) for i in range(l-1,r): ans[i] = t[c] c += 1 v.discard(ans[i]) v = list(v) for i in range(n): if ans[i]==0: ans[i] = v.pop() print(*ans)
1618065300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]