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
["576", "34"]
e6fcbe3f102b694a686c0295edbc35e9
NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.
Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.
In the single line print a single number — the answer to the problem.
The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).
standard output
standard input
Python 3
Python
1,500
train_043.jsonl
db4095f95a6f208da1e27c62cdbbaa80
256 megabytes
["3 4 4 19 1\n42 3 99", "4 7 2 3 9\n1 2 3 4"]
PASSED
#!/usr/bin/python3 import sys n, l, r, ql, qr = map(int, sys.stdin.readline().strip().split()) w = [int(x) for x in sys.stdin.readline().strip().split()] s = [0] for i in range(0, n): s.append(s[-1] + w[i]) def cost(left): right = n - left diff = left - right bonus = 0 if diff > 0: # left part is larger bonus = ql * (diff - 1) elif diff < 0: # right part is larger bonus = qr * (-diff - 1) return bonus + l * s[left] + r * (s[n] - s[left]) best = cost(0) for left in range(1, n+1): c = cost(left) if c < best: best = c print(best)
1381678200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0 2\n3 0\n2 0\n0 1\n1 0"]
7f71bea1c62b0a027c8d55431fbc7db7
NoteIn the first case, the maximal value of the product is $$$2$$$. Thus, we can either delete the first three elements (obtain array $$$[2]$$$), or the last two and one first element (also obtain array $$$[2]$$$), or the last two elements (obtain array $$$[1, 2]$$$). Thus, in the first case, the answers fit: "3 0", or "1 2", or "0 2".In the second case, the maximum value of the product is $$$1$$$. Then we can remove all elements from the array because the value of the product on the empty array will be $$$1$$$. So the answer is "3 0", but there are other possible answers.In the third case, we can remove the first two elements of the array. Then we get the array: $$$[-2, 2, -1]$$$. The product of the elements of the resulting array is $$$(-2) \cdot 2 \cdot (-1) = 4$$$. This value is the maximum possible value that can be obtained. Thus, for this case the answer is: "2 0".
You are given an array $$$a$$$ consisting of $$$n$$$ integers. For each $$$i$$$ ($$$1 \le i \le n$$$) the following inequality is true: $$$-2 \le a_i \le 2$$$.You can remove any number (possibly $$$0$$$) of elements from the beginning of the array and any number (possibly $$$0$$$) of elements from the end of the array. You are allowed to delete the whole array.You need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is maximal. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output any of them. The product of elements of an empty array (array of length $$$0$$$) should be assumed to be $$$1$$$.
For each test case, output two non-negative numbers $$$x$$$ and $$$y$$$ ($$$0 \le x + y \le n$$$) — such that the product (multiplication) of the array numbers, after removing $$$x$$$ elements from the beginning and $$$y$$$ elements from the end, is maximal. If there is more than one way to get the maximal product, it is allowed to output any of them. Consider the product of numbers on empty array to be $$$1$$$.
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Then the descriptions of the input test cases follow. The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) —the length of array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_i| \le 2$$$) — elements of 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
PyPy 3-64
Python
1,600
train_105.jsonl
de60d951b5320e2432508e8681c2011c
256 megabytes
["5\n4\n1 2 -1 2\n3\n1 1 -2\n5\n2 0 -2 2 -1\n3\n-2 -1 -1\n3\n-1 -2 -2"]
PASSED
import math from sys import stdin input = stdin.readline #// - remember to add .strip() when input is a string t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int,input().split())) new = [] temp = [] for i in range(len(arr)): if arr[i] == 0: if len(temp) > 0: new.append(temp) temp = [] else: temp.append(arr[i]) if i == len(arr) - 1: if len(temp) > 0: new.append(temp) maxans = 0 lensub = 0 for i in new: first_neg = -1 last_neg = -1 pref_prod = 0 suff_prod = 0 prod = 0 count_neg = 0 for j in range(len(i)): if abs(i[j]) == 2: prod += 1 suff_prod += 1 if first_neg == -1: if abs(i[j]) == 2: pref_prod += 1 if i[j] < 0: last_neg = j count_neg += 1 if first_neg == -1: first_neg = j suff_prod = 0 if i[j] == -2: suff_prod = 1 if count_neg % 2 == 0: if prod > maxans: maxans = prod lensub = len(i) #elif count_neg == 1: #pass else: if pref_prod > suff_prod: prod = prod - suff_prod if prod > maxans: maxans = prod lensub = last_neg else: prod = prod - pref_prod if prod > maxans: maxans = prod lensub = len(i) - first_neg-1 #print("GSaWAaa",maxans, lensub) zero = 0 prod = 0 negs = 0 for i in range(lensub): if arr[i] < 0: negs += 1 if arr[i] == 0: zero += 1 if abs(arr[i]) == 2: prod += 1 if prod == maxans and zero == 0 and negs % 2 == 0: if lensub == 0: print(0, len(arr)) else: print(0, len(arr)-(lensub-1)-1) else: for i in range(lensub,len(arr)): if arr[i-lensub] == 0: zero -= 1 if arr[i-lensub] < 0: negs -= 1 if abs(arr[i-lensub]) == 2: prod -= 1 if arr[i] == 0: zero += 1 if arr[i] < 0: negs += 1 if abs(arr[i]) == 2: prod += 1 if prod == maxans and zero == 0 and negs % 2 == 0: if lensub == 0: print(0, len(arr)) else: print(i-lensub+1, len(arr)-i-1) break
1648737300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0\n2\n1\n-1"]
03e5f71810b10318fed344878d226a10
NoteIn the first test case, $$$n=3876$$$, which is already an even number. Polycarp doesn't need to do anything, so the answer is $$$0$$$.In the second test case, $$$n=387$$$. Polycarp needs to do $$$2$$$ operations: Select $$$l=2$$$ and reverse the prefix $$$\underline{38}7$$$. The number $$$n$$$ becomes $$$837$$$. This number is odd. Select $$$l=3$$$ and reverse the prefix $$$\underline{837}$$$. The number $$$n$$$ becomes $$$738$$$. This number is even.It can be shown that $$$2$$$ is the minimum possible number of operations that Polycarp needs to do with his number to make it even.In the third test case, $$$n=4489$$$. Polycarp can reverse the whole number (choose a prefix of length $$$l=4$$$). It will become $$$9844$$$ and this is an even number.In the fourth test case, $$$n=3$$$. No matter how hard Polycarp tried, he would not be able to make an even number.
Polycarp has an integer $$$n$$$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: Reverse the prefix of length $$$l$$$ (in other words, $$$l$$$ leftmost digits) of $$$n$$$. So, the leftmost digit is swapped with the $$$l$$$-th digit from the left, the second digit from the left swapped with ($$$l-1$$$)-th left, etc. For example, if $$$n=123456789$$$ and $$$l=5$$$, then the new value of $$$n$$$ will be $$$543216789$$$.Note that for different operations, the values of $$$l$$$ can be different. The number $$$l$$$ can be equal to the length of the number $$$n$$$ — in this case, the whole number $$$n$$$ is reversed.Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.Help Polycarp. Determine the minimum number of operations he needs to perform with the number $$$n$$$ to make it even or determine that this is impossible.You need to answer $$$t$$$ independent test cases.
Print $$$t$$$ lines. On each line print one integer — the answer to the corresponding test case. If it is impossible to make an even number, print -1.
The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains one integer $$$n$$$ ($$$1 \le n &lt; 10^9$$$). It is guaranteed that the given number doesn't contain the digit 0.
standard output
standard input
PyPy 3-64
Python
800
train_093.jsonl
0840806bd61333712c4d5cca923e6735
256 megabytes
["4\n3876\n387\n4489\n3"]
PASSED
for _ in range(int(input())): n = input() if int(n[-1]) % 2 == 0: print(0) elif int(n[0]) % 2 == 0: print(1) elif any(not (int(e) % 2) for e in n): print(2) else: print(-1)
1637850900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["YES\n3 4", "NO", "YES\n1 1"]
6493e146ea8d931582d77bb1b0f06e53
null
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $$$i$$$-th of them will start during the $$$x_i$$$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $$$x_1, x_2, \dots, x_n$$$, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as $$$y$$$) and the interval between two consecutive signals (let's denote it by $$$p$$$). After the clock is set, it will ring during minutes $$$y, y + p, y + 2p, y + 3p$$$ and so on.Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of $$$p$$$. He has to pick it among the given values $$$p_1, p_2, \dots, p_m$$$ (his phone does not support any other options for this setting).So Ivan has to choose the first minute $$$y$$$ when the alarm clock should start ringing and the interval between two consecutive signals $$$p_j$$$ in such a way that it will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$ (and it does not matter if his alarm clock will ring in any other minutes).Your task is to tell the first minute $$$y$$$ and the index $$$j$$$ such that if Ivan sets his alarm clock with properties $$$y$$$ and $$$p_j$$$ it will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.
If it's impossible to choose such values $$$y$$$ and $$$j$$$ so all constraints are satisfied, print "NO" in the first line. Otherwise print "YES" in the first line. Then print two integers $$$y$$$ ($$$1 \le y \le 10^{18}$$$) and $$$j$$$ ($$$1 \le j \le m$$$) in the second line, where $$$y$$$ is the first minute Ivan's alarm clock should start ringing and $$$j$$$ is the index of the option for the interval between two consecutive signals (options are numbered from $$$1$$$ to $$$m$$$ in the order they are given input). These values should be chosen in such a way that the alarm clock will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$. If there are multiple answers, you can print any.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5, 1 \le m \le 3 \cdot 10^5$$$) — the number of events and the number of possible settings for the interval between signals. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^{18}$$$), where $$$x_i$$$ is the minute when $$$i$$$-th event starts. It is guaranteed that all $$$x_i$$$ are given in increasing order (i. e. the condition $$$x_1 &lt; x_2 &lt; \dots &lt; x_n$$$ holds). The third line of the input contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_j \le 10^{18}$$$), where $$$p_j$$$ is the $$$j$$$-th option for the interval between two consecutive signals.
standard output
standard input
Python 3
Python
1,300
train_009.jsonl
d018b510e8a073586cba1b3161660675
256 megabytes
["3 5\n3 12 18\n2 6 5 3 3", "4 2\n1 5 17 19\n4 5", "4 2\n1 5 17 19\n2 1"]
PASSED
from math import gcd n,m = map(int,input().split()) l = list(map(int,input().split())) r = list(map(int,input().split())) k = [] for i in range(n-1): k.append(l[i+1]-l[i]) s = 0 for i in range(len(k)): s = gcd(s,k[i]) for i in range(m): if s%r[i] == 0: print("YES") t = l[0]%r[i] if t == 0: t = r[i] print(t,i+1) exit() print("NO")
1555943700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["01111", "0011111011"]
2bf41400fa51f472f1d3904baa06d6a8
NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12&gt;11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
standard output
standard input
PyPy 3
Python
2,400
train_103.jsonl
eb2eb917905ed8eda46d42fc52287692
256 megabytes
["5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6"]
PASSED
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n,m=map(int,input().split()) EDGE=[tuple(map(int,input().split())) for i in range(m)] # UnionFind Group = [i for i in range(n+1)] # グループ分け Nodes = [1]*(n+1) # 各グループのノードの数 def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): if Nodes[find(x)] < Nodes[find(y)]: Nodes[find(y)] += Nodes[find(x)] Nodes[find(x)] = 0 Group[find(x)] = find(y) else: Nodes[find(x)] += Nodes[find(y)] Nodes[find(y)] = 0 Group[find(y)] = find(x) USE=[0]*m for i in range(m): x,y=EDGE[i] if find(x)==find(y): USE[i]=0 else: USE[i]=1 Union(x,y) E=[[] for i in range(n+1)] OK=[0]*(n+1) for i in range(m): if USE[i]==1: x,y = EDGE[i] E[x].append(y) E[y].append(x) OK[x]=1 OK[y]=1 # 木のHL分解+LCA N=n+1 ROOT=1 QUE=[ROOT] Parent=[-1]*(N+1) Height=[-1]*(N+1) Parent[ROOT]=N # ROOTの親を定めておく. Height[ROOT]=0 Child=[[] for i in range(N+1)] TOP_SORT=[] # トポロジカルソート while QUE: # トポロジカルソートと同時に親を見つける x=QUE.pop() TOP_SORT.append(x) for to in E[x]: if Parent[to]==-1: Parent[to]=x Height[to]=Height[x]+1 Child[x].append(to) QUE.append(to) Children=[1]*(N+1) for x in TOP_SORT[::-1]: #(自分を含む)子ノードの数を調べる Children[Parent[x]]+=Children[x] USE=[0]*N Group=[i for i in range(N)] for x in TOP_SORT: # HL分解によるグループ分け USE[x]=1 MAX_children=0 select_node=0 for to in E[x]: if USE[to]==0 and Children[to]>MAX_children: select_node=to MAX_children=Children[to] for to in E[x]: if USE[to]==0 and to==select_node: Group[to]=Group[x] def LCA(a,b): # HL分解を利用してLCAを求める while Group[a]!=Group[b]: if Children[Parent[Group[a]]]<Children[Parent[Group[b]]]: a=Parent[Group[a]] else: b=Parent[Group[b]] if Children[a]>Children[b]: return a else: return b Parents=[Parent] for i in range(30): X=[-1]*(N+1) for i in range(N+1): X[i]=Parents[-1][Parents[-1][i]] Parents.append(X) def LCA_mae(x,y): while Height[x]>Height[y]+1: for i in range(30): k=Parents[i][x] if k==-1 or k>=n or Height[k]<=Height[y]: x=Parents[i-1][x] break return x DOWN=[0]*(N+1) score=0 for x,y in EDGE: if OK[x]==1 and OK[y]==1: if Parent[x]==y or Parent[y]==x: continue k=LCA(x,y) if k==x: DOWN[y]+=1 k=LCA_mae(y,x) DOWN[k]-=1 elif k==y: DOWN[x]+=1 k=LCA_mae(x,y) DOWN[k]-=1 else: score+=1 DOWN[x]+=1 DOWN[y]+=1 for x in TOP_SORT[1:]: DOWN[x]+=DOWN[Parent[x]] ANS=[0]*N for i in range(N): if OK[i]==1 and DOWN[i]==score: ANS[i]=1 print("".join(map(str,ANS[1:N])))
1657982100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["1\n2", "0"]
679f7243fe1e072af826a779c44b5056
null
Boy Dima gave Julian a birthday present — set $$$B$$$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $$$i$$$ and $$$j$$$ with an edge if $$$|i - j|$$$ belongs to $$$B$$$.Unfortunately, Julian doesn't like the graph, that was built using $$$B$$$. Alex decided to rectify the situation, so he wants to erase some numbers from $$$B$$$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from $$$B$$$ so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
In the first line print single integer $$$k$$$ – the number of erased elements. In the second line print $$$k$$$ integers — values of erased elements. If there are multiple answers, print any of them.
First line contains an integer $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — size of $$$B$$$ Second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18})$$$ — numbers of $$$B$$$, all $$$b_i$$$ are unique
standard output
standard input
PyPy 3
Python
1,900
train_057.jsonl
c1f47a2ab7a63a58bd754e91cab68b4e
256 megabytes
["3\n1 2 3", "2\n2 6"]
PASSED
n = int(input()) B = list(map(int, input().split())) A = [] for i in range(100): A.append([]) for i in B: x = i c = 0 while x % 2 == 0: x //= 2 c += 1 A[c].append(i) mlen = 0 f = 1 for lst in A: mlen = max(mlen, len(lst)) ans = [] for lst in A: if len(lst) == mlen and f: f = 0 else: for x in lst: ans.append(x) print(len(ans)) print(' '.join(list(map(str, ans))))
1568822700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["1 1 2 \n1 2 1", "-1"]
4dddcf0ded11672a4958fb0d391dbaf5
NoteNote that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.
If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.
The first line of input contains three space-separated integers n, k, d (1 ≤ n, d ≤ 1000; 1 ≤ k ≤ 109).
standard output
standard input
Python 3
Python
1,900
train_025.jsonl
f3867638f2d5dc9ddd1bfeca4451685c
256 megabytes
["3 2 2", "3 2 1"]
PASSED
n,k,d=map(int,input().split()) if n>k**d:print(-1);exit() K=1 for j in range(d): print(" ".join([str(i//K%k +1) for i in range(n)])) K*=k
1408116600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["11\n4 1\n2 5\n1 3\n5 2\n3 4"]
c151fe26b4152474c78fd71c7ab49c88
NoteThe first test from the statement the match looks as follows: bill  →  bilbo (lcp = 3) galya  →  galadriel (lcp = 3) gennady  →  gendalf (lcp = 3) toshik  →  torin (lcp = 2) boris  →  smaug (lcp = 0)
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as . Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.Find the matching between students and pseudonyms with the maximum quality.
In the first line print the maximum possible quality of matching pseudonyms to students. In the next n lines describe the optimal matching. Each line must have the form a b (1 ≤ a, b ≤ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input. The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
The first line contains number n (1 ≤ n ≤ 100 000) — the number of students in the summer school. Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating. The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating. The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
standard output
standard input
PyPy 3
Python
2,300
train_001.jsonl
57da54098f153a43ca0403ea32fc9552
256 megabytes
["5\ngennady\ngalya\nboris\nbill\ntoshik\nbilbo\ntorin\ngendalf\nsmaug\ngaladriel"]
PASSED
import sys SIGMA = 26 nodes = [] pairs = [] res = 0 class Node: def __init__(self): self.ch = {} self.a = [] self.b = [] self.d = 0 def add(self, s, i): t = self for c in s: v = ord(c) - ord('a') if not v in t.ch: t.ch[v] = Node() t.ch[v].d = t.d + 1 nodes.append(t.ch[v]) t = t.ch[v] t.a.append(i) def inc(self, s, i): t = self for c in s: v = ord(c) - ord('a') if not v in t.ch: break t = t.ch[v] t.b.append(i) def solve(self): global pairs global res for i in range(SIGMA): if i in self.ch: self.a.extend(self.ch[i].a) self.b.extend(self.ch[i].b) k = min(len(self.a), len(self.b)) for i in range(k): pairs.append(str(self.a[-1]) + ' ' + str(self.b[-1])) self.a.pop() self.b.pop() res += self.d return res sys.setrecursionlimit(2000000) _input = sys.stdin.readlines() _input = [s[:-1] for s in _input] N = int(_input[0]) A = _input[1 : N + 1] B = _input[N + 1 :] T = Node() nodes.append(T) for i, s in enumerate(A): T.add(s, i + 1) for i, s in enumerate(B): T.inc(s, i + 1) for n in reversed(nodes): n.solve() print(res) print('\n'.join(pairs))
1438273200
[ "trees", "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 1 ]
1 second
["Yes\nNo\nYes\nNo\nYes"]
30cfce44a7a0922929fbe54446986748
NoteIn the first test case of the example, we can assume that each grain weighs $$$17$$$ grams, and a pack $$$119$$$ grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs $$$16$$$ grams, and a pack $$$128$$$ grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that $$$3$$$ grains of rice weigh $$$2$$$, $$$2$$$, and $$$3$$$ grams, and a pack is $$$7$$$ grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains.
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped $$$n$$$ grains. Nastya read that each grain weighs some integer number of grams from $$$a - b$$$ to $$$a + b$$$, inclusive (numbers $$$a$$$ and $$$b$$$ are known), and the whole package of $$$n$$$ grains weighs from $$$c - d$$$ to $$$c + d$$$ grams, inclusive (numbers $$$c$$$ and $$$d$$$ are known). The weight of the package is the sum of the weights of all $$$n$$$ grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $$$i$$$-th grain weighs some integer number $$$x_i$$$ $$$(a - b \leq x_i \leq a + b)$$$, and in total they weigh from $$$c - d$$$ to $$$c + d$$$, inclusive ($$$c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$$$).
For each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if $$$n$$$ grains with masses from $$$a - b$$$ to $$$a + b$$$ cannot make a package with a total mass from $$$c - d$$$ to $$$c + d$$$.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$  — the number of test cases. The next $$$t$$$ lines contain descriptions of the test cases, each line contains $$$5$$$ integers: $$$n$$$ $$$(1 \leq n \leq 1000)$$$  — the number of grains that Nastya counted and $$$a, b, c, d$$$ $$$(0 \leq b &lt; a \leq 1000, 0 \leq d &lt; c \leq 1000)$$$  — numbers that determine the possible weight of one grain of rice (from $$$a - b$$$ to $$$a + b$$$) and the possible total weight of the package (from $$$c - d$$$ to $$$c + d$$$).
standard output
standard input
Python 2
Python
900
train_003.jsonl
16e50d0d9fdc4640b1a7a3973a09dec2
256 megabytes
["5\n7 20 3 101 18\n11 11 10 234 2\n8 9 7 250 122\n19 41 21 321 10\n3 10 8 6 1"]
PASSED
from sys import stdin, stdout read = stdin.readline write = stdout.write xr = xrange def main(): for tc in xr(int(read())): n,a,b,c,d = map(int, read().split()) if n * (a + b ) < c - d or n * (a - b) > c + d: write('No\n') else: write('Yes\n') if __name__ == "__main__": main()
1587653100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["Petr"]
a9cc20ba7d6e31706ab1743bdde97669
NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
standard output
standard input
Python 3
Python
1,800
train_016.jsonl
7f29a2332a99c99b781e781f2e339027
256 megabytes
["5\n2 4 5 1 3"]
PASSED
n=int(input()) a=[0]+list(map(int,input().split())) ans=0 for i in range(1,len(a)): if a[i]==-1: continue j=i while a[j]!=-1: prev=j j=a[j] a[prev]=-1 ans+=1 if n%2==0: #n even ans also even even number of swaps required #3*n if ans%2==0: print("Petr") else: print("Um_nik") else: #n us odd ans is even odd number of swaps required if ans%2==0: print("Petr") else: print("Um_nik")
1527608100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n0\n4"]
29e84addbc88186bce40d68cf124f5da
NoteFirst test case considered in the statement.In the second test case integers $$$a$$$ and $$$b$$$ are already equal, so you don't need to perform any operations.In the third test case you have to apply the first, the second, the third and the fourth operation to $$$b$$$ ($$$b$$$ turns into $$$20 + 1 + 2 + 3 + 4 = 30$$$).
You are given two integers $$$a$$$ and $$$b$$$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $$$1$$$; during the second operation you choose one of these numbers and increase it by $$$2$$$, and so on. You choose the number of these operations yourself.For example, if $$$a = 1$$$ and $$$b = 3$$$, you can perform the following sequence of three operations: add $$$1$$$ to $$$a$$$, then $$$a = 2$$$ and $$$b = 3$$$; add $$$2$$$ to $$$b$$$, then $$$a = 2$$$ and $$$b = 5$$$; add $$$3$$$ to $$$a$$$, then $$$a = 5$$$ and $$$b = 5$$$. Calculate the minimum number of operations required to make $$$a$$$ and $$$b$$$ equal.
For each test case print one integer — the minimum numbers of operations required to make $$$a$$$ and $$$b$$$ equal.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
standard output
standard input
Python 3
Python
1,500
train_002.jsonl
42ace6bb6ebe9fcab0d0631a21b2b0e3
256 megabytes
["3\n1 3\n11 11\n30 20"]
PASSED
import sys import collections from collections import Counter import itertools import math import timeit #input = sys.stdin.readline ######################### # imgur.com/Pkt7iIf.png # ######################### def sieve(n): if n < 2: return list() prime = [True for _ in range(n + 1)] p = 3 while p * p <= n: if prime[p]: for i in range(p * 2, n + 1, p): prime[i] = False p += 2 r = [2] for p in range(3, n + 1, 2): if prime[p]: r.append(p) return r def divs(n, start=1): divisors = [] for i in range(start, int(math.sqrt(n) + 1)): if n % i == 0: if n / i == i: divisors.append(i) else: divisors.extend([i, n // i]) return divisors def divn(n, primes): divs_number = 1 for i in primes: if n == 1: return divs_number t = 1 while n % i == 0: t += 1 n //= i divs_number *= t def flin(d, x, default = -1): left = right = -1 for i in range(len(d)): if d[i] == x: if left == -1: left = i right = i if left == -1: return (default, default) else: return (left, right) def ceil(n, k): return int(n // k + (n % k != 0)) def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) def lcm(a, b): return abs(a * b) // math.gcd(a, b) def prr(a, sep=' '): print(sep.join(map(str, a))) def dd(): return collections.defaultdict(int) def ddl(): return collections.defaultdict(list) t = ii() for _ in range(t): a, b = mi() m = abs(a - b) x = ceil(math.sqrt(8*m + 1) - 1, 2) r = x * (x + 1) // 2 if r == m or (r - m) % 2 == 0: print(x) elif (r - m) % 2 and x % 2 == 0: print(x + 1) else: print(x + 2)
1576766100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "0", "3", "1"]
6c9cbe714f8f594654ebc59b6059b30a
NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way: The first group (of two people) and the seventh group (of one person), The second group (of two people) and the sixth group (of one person), The third group (of two people) and the fourth group (of one person).
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.
Print the maximum number of teams of three people the coach can form.
The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.
standard output
standard input
PyPy 3
Python
800
train_008.jsonl
9df1426cd3ea06597734b15fd3c9ed60
256 megabytes
["4\n1 1 2 1", "2\n2 2", "7\n2 2 2 1 1 1 1", "3\n1 1 1"]
PASSED
n=int(input()) l=list(map(int,input().split())) x=l.count(2) y=l.count(1) m=min(x,y) c=(y-m)//3 print(c+m)
1513492500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6\n11\n18"]
1277cf54097813377bf37be445c06e7e
NoteConsider the second test case of the example. It looks like that:There are $$$11$$$ different simple paths: $$$[1, 2]$$$; $$$[2, 3]$$$; $$$[3, 4]$$$; $$$[2, 4]$$$; $$$[1, 2, 4]$$$; $$$[1, 2, 3]$$$; $$$[2, 3, 4]$$$; $$$[2, 4, 3]$$$; $$$[3, 2, 4]$$$; $$$[1, 2, 3, 4]$$$; $$$[1, 2, 4, 3]$$$.
You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
standard output
standard input
PyPy 3
Python
null
train_000.jsonl
0b26e06b30873946c2a17d161ccba4a1
256 megabytes
["3\n3\n1 2\n2 3\n1 3\n4\n1 2\n2 3\n3 4\n4 2\n5\n1 2\n2 3\n1 3\n2 5\n4 3"]
PASSED
from collections import deque from sys import stdin, gettrace if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def readGraph(n, m): adj = [[] for _ in range(n)] for _ in range(m): u,v = map(int, inputi().split()) adj[u-1].append(v-1) adj[v-1].append(u-1) return adj def solve(): n = int(inputi()) adj = readGraph(n, n) parent = [None] * n depth = [0]*n q = deque() q.append(0) loop = deque() while not loop: c = q.popleft() for a in adj[c]: if a != parent[c]: if parent[a] != None: loop.append(a) loop.append(c) break else: parent[a] = c depth[a] = depth[c]+1 q.append(a) while loop[0] != loop[-1]: if depth[loop[0]] > depth[loop[-1]]: loop.appendleft(parent[loop[0]]) else: loop.append(parent[loop[-1]]) loop = list(loop)[:-1] ls = len(loop) lc = [] for i in range(ls): l = loop[i] q = deque() q.append(l) count = 0 visited = {loop[(i-1)%ls], l, loop[(i+1)%ls]} while q: for a in adj[q.popleft()]: if a not in visited: count += 1 visited.add(a) q.append(a) lc.append(count) treecount = (n*(n-1))//2 loopcount = (ls*(ls-1))//2 lt = (ls-1)*(n - ls) tt = sum(c * (n - c - ls) for c in lc)//2 res = treecount+loopcount+lt+tt print(res) def main(): t = int(inputi()) for _ in range(t): solve() if __name__ == "__main__": main()
1606228500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["0\n1\n999999999\n2"]
db0e6e67ca1184c5759fc488a3dff24e
null
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $$$k$$$-th layer of the triangle contains $$$k$$$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $$$(r, c)$$$ ($$$1 \le c \le r$$$), where $$$r$$$ is the number of the layer, and $$$c$$$ is the number of the point in the layer. From each point $$$(r, c)$$$ there are two directed edges to the points $$$(r+1, c)$$$ and $$$(r+1, c+1)$$$, but only one of the edges is activated. If $$$r + c$$$ is even, then the edge to the point $$$(r+1, c)$$$ is activated, otherwise the edge to the point $$$(r+1, c+1)$$$ is activated. Look at the picture for a better understanding. Activated edges are colored in black. Non-activated edges are colored in gray. From the point $$$(r_1, c_1)$$$ it is possible to reach the point $$$(r_2, c_2)$$$, if there is a path between them only from activated edges. For example, in the picture above, there is a path from $$$(1, 1)$$$ to $$$(3, 2)$$$, but there is no path from $$$(2, 1)$$$ to $$$(1, 1)$$$.Initially, you are at the point $$$(1, 1)$$$. For each turn, you can: Replace activated edge for point $$$(r, c)$$$. That is if the edge to the point $$$(r+1, c)$$$ is activated, then instead of it, the edge to the point $$$(r+1, c+1)$$$ becomes activated, otherwise if the edge to the point $$$(r+1, c+1)$$$, then instead if it, the edge to the point $$$(r+1, c)$$$ becomes activated. This action increases the cost of the path by $$$1$$$; Move from the current point to another by following the activated edge. This action does not increase the cost of the path. You are given a sequence of $$$n$$$ points of an infinite triangle $$$(r_1, c_1), (r_2, c_2), \ldots, (r_n, c_n)$$$. Find the minimum cost path from $$$(1, 1)$$$, passing through all $$$n$$$ points in arbitrary order.
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) is the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) is the number of points to visit. The second line contains $$$n$$$ numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$1 \le r_i \le 10^9$$$), where $$$r_i$$$ is the number of the layer in which $$$i$$$-th point is located. The third line contains $$$n$$$ numbers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le r_i$$$), where $$$c_i$$$ is the number of the $$$i$$$-th point in the $$$r_i$$$ layer. It is guaranteed that all $$$n$$$ points are distinct. It is guaranteed that there is always at least one way to traverse all $$$n$$$ points. 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
Python
2,000
train_101.jsonl
98fd731ad23200f3ceefd7a2f9b1f8a4
256 megabytes
["4\n3\n1 4 2\n1 3 1\n2\n2 4\n2 3\n2\n1 1000000000\n1 1000000000\n4\n3 10 5 8\n2 5 2 4"]
PASSED
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n = int(input()) R = list(map(int, input().split())) C = list(map(int, input().split())) go = sorted([(1, 1)] + list(zip(R, C))) ans = 0 for i in range(n): c1 = go[i][0] - go[i][1] + 1 c2 = go[i + 1][0] - go[i + 1][1] + 1 k1 = c1 // 2 k2 = c2 // 2 if c1 % 2 == 0 and c2 % 2 == 0: ans += k2 - k1 if c1 % 2 == 0 and c2 % 2 == 1: ans += k2 - k1 + 1 if c1 % 2 == 1 and c2 % 2 == 0: ans += k2 - k1 - 1 if c1 % 2 == 1 and c2 % 2 == 1: if k1 == k2: ans += go[i + 1][0] - go[i][0] else: ans += k2 - k1 print(ans)
1616682900
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
1 second
["YES\n3 3 3", "NO"]
0b204773f8d06362b7569bd82224b218
null
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
standard output
standard input
PyPy 3
Python
1,800
train_073.jsonl
56ff02deb056fa397f513143ff0e1027
256 megabytes
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 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") MAX = 1000001 bitscount = 30 prefix_count = [[0]*(10**5+1) for i in range(30)] def findPrefixCount(arr, n): for i in range(0, bitscount): prefix_count[i][0] = ((arr[0] >> i) & 1) for j in range(1, n): prefix_count[i][j] = ((arr[j] >> i) & 1) prefix_count[i][j] += prefix_count[i][j - 1] def rangeOr(l, r): ans = 0 for i in range(bitscount): x = 0 if (l == 0): x = prefix_count[i][r] else: x = prefix_count[i][r] - prefix_count[i][l - 1] # Condition for ith bit # of answer to be set if (x == r - l + 1): ans = (ans | (1 << i)) return ans n, m = map(int, input().split()) a = [[0] * n for i in range(30)] query = [] for i in range(m): l, r, q = map(int, input().split()) query.append([l-1, r-1, q]) c = bin(q)[2:][::-1] b = [] for j in c: b.append(int(j)) j = 0 while (j < len(b)): if b[j] == 1: a[j][l - 1] += 1 if r != n: a[j][r] -= 1 j += 1 for i in range(30): j = 1 while (j < n): a[i][j] += a[i][j - 1] j += 1 j = 0 while (j < n): if a[i][j] > 0: a[i][j] = 1 j += 1 res=[] for i in range(n): s = "" j=29 while(j>=0): s += str(a[j][i]) j+=-1 res.append(int(s,2)) findPrefixCount(res, n) f=0 for j in query: if rangeOr(j[0],j[1])!=j[2]: f=1 break if f==1: print("NO") else: print("YES") print(*res)
1414170000
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["4361", "60", "3250", "768500592"]
8f34d2a146ff44ff4ea82fb6481d10e2
NoteHere is the graph for the first example: Some maximum weight paths are: length $$$1$$$: edges $$$(1, 7)$$$ — weight $$$3$$$; length $$$2$$$: edges $$$(1, 2), (2, 3)$$$ — weight $$$1+10=11$$$; length $$$3$$$: edges $$$(1, 5), (5, 6), (6, 4)$$$ — weight $$$2+7+15=24$$$; length $$$4$$$: edges $$$(1, 5), (5, 6), (6, 4), (6, 4)$$$ — weight $$$2+7+15+15=39$$$; $$$\dots$$$ So the answer is the sum of $$$25$$$ terms: $$$3+11+24+39+\dots$$$In the second example the maximum weight paths have weights $$$4$$$, $$$8$$$, $$$12$$$, $$$16$$$ and $$$20$$$.
You are given a simple weighted connected undirected graph, consisting of $$$n$$$ vertices and $$$m$$$ edges.A path in the graph of length $$$k$$$ is a sequence of $$$k+1$$$ vertices $$$v_1, v_2, \dots, v_{k+1}$$$ such that for each $$$i$$$ $$$(1 \le i \le k)$$$ the edge $$$(v_i, v_{i+1})$$$ is present in the graph. A path from some vertex $$$v$$$ also has vertex $$$v_1=v$$$. Note that edges and vertices are allowed to be included in the path multiple times.The weight of the path is the total weight of edges in it.For each $$$i$$$ from $$$1$$$ to $$$q$$$ consider a path from vertex $$$1$$$ of length $$$i$$$ of the maximum weight. What is the sum of weights of these $$$q$$$ paths?Answer can be quite large, so print it modulo $$$10^9+7$$$.
Print a single integer — the sum of the weights of the paths from vertex $$$1$$$ of maximum weights of lengths $$$1, 2, \dots, q$$$ modulo $$$10^9+7$$$.
The first line contains a three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$2 \le n \le 2000$$$; $$$n - 1 \le m \le 2000$$$; $$$m \le q \le 10^9$$$) — the number of vertices in the graph, the number of edges in the graph and the number of lengths that should be included in the answer. Each of the next $$$m$$$ lines contains a description of an edge: three integers $$$v$$$, $$$u$$$, $$$w$$$ ($$$1 \le v, u \le n$$$; $$$1 \le w \le 10^6$$$) — two vertices $$$v$$$ and $$$u$$$ are connected by an undirected edge with weight $$$w$$$. The graph contains no loops and no multiple edges. It is guaranteed that the given edges form a connected graph.
standard output
standard input
PyPy 2
Python
2,700
train_024.jsonl
1aa1977df1e9fafb49fafd64efeb470a
256 megabytes
["7 8 25\n1 2 1\n2 3 10\n3 4 2\n1 5 2\n5 6 7\n6 4 15\n5 3 1\n1 7 3", "2 1 5\n1 2 4", "15 15 23\n13 10 12\n11 14 12\n2 15 5\n4 10 8\n10 2 4\n10 7 5\n3 10 1\n5 6 11\n1 13 8\n9 15 4\n4 2 9\n11 15 1\n11 12 14\n10 8 12\n3 6 11", "5 10 10000000\n2 4 798\n1 5 824\n5 2 558\n4 1 288\n3 4 1890\n3 1 134\n2 3 1485\n4 5 284\n3 5 1025\n1 2 649"]
PASSED
import sys range = xrange input = raw_input n,m,q = [int(x) for x in input().split()] V = [] W = [] coupl = [[] for _ in range(n)] for _ in range(m): a,b,w = [int(x) - 1 for x in input().split()] w += 1 W.append(w) eind = len(V) V.append(b) V.append(a) coupl[a].append(eind) coupl[b].append(eind ^ 1) DP = [[-1]*n for _ in range(n)] DP[0][0] = 0 for j in range(1, n): prevDP = DP[j - 1] newDP = DP[j] for node in range(n): if prevDP[node] == -1: continue for eind in coupl[node]: nei = V[eind] newDP[nei] = max(newDP[nei], prevDP[node] + W[eind >> 1]) ans = 0 for dp in DP: ans += max(dp) M = DP[-1] K = [] for node in range(n): K.append(max(W[eind >> 1] for eind in coupl[node])) K = [K[i] for i in range(n) if M[i] >= 0] M = [M[i] for i in range(n) if M[i] >= 0] def solve(K, M, a, b): hulli, hullx = convex_hull(K, M) def sqsum(n): return n * (n + 1) >> 1 n = len(hulli) ans = 0 # iterate over all n intervalls for i in range(n): j = hulli[i] k,m = K[j],M[j] l = max(a, hullx[i - 1] + 1 if i else a) r = min(b - 1, hullx[i] if i + 1 < n else b - 1) if l <= r: ans += m * (r - l + 1) ans += k * (sqsum(r) - sqsum(l - 1)) return ans # hulli[0] hulli[1] hulli[-1] # # (inf, hullx[0]], (hullx[0], hullx[1]], ..., (hullx[-1], inf) # def convex_hull(K, M, integer = True): # assert len(K) == len(M) if integer: intersect = lambda i,j: (M[j] - M[i]) // (K[i] - K[j]) else: intersect = lambda i,j: (M[j] - M[i]) / (K[i] - K[j]) hulli = [] hullx = [] order = sorted(range(len(K)), key = K.__getitem__) for i in order: while True: if not hulli: hulli.append(i) hullx.append(-1) break elif K[hulli[-1]] == K[i]: if M[hulli[-1]] >= M[i]: break hulli.pop() hullx.pop() else: x = intersect(i, hulli[-1]) if len(hulli) > 1 and x <= hullx[-1]: hullx.pop() hulli.pop() else: hullx.append(x) hulli.append(i) break return hulli, hullx[1:] ans += solve(K, M, 1, q - (n - 1) + 1) print ans % (10 ** 9 + 7)
1591886100
[ "geometry", "graphs" ]
[ 0, 1, 1, 0, 0, 0, 0, 0 ]
1 second
["0\n1\n1\n3\n88005553"]
8e4194b356500cdaacca2b1d49c2affb
NoteThe first interesting number is equal to $$$9$$$.
Let's define $$$S(x)$$$ to be the sum of digits of number $$$x$$$ written in decimal system. For example, $$$S(5) = 5$$$, $$$S(10) = 1$$$, $$$S(322) = 7$$$.We will call an integer $$$x$$$ interesting if $$$S(x + 1) &lt; S(x)$$$. In each test you will be given one integer $$$n$$$. Your task is to calculate the number of integers $$$x$$$ such that $$$1 \le x \le n$$$ and $$$x$$$ is interesting.
Print $$$t$$$ integers, the $$$i$$$-th should be the answer for the $$$i$$$-th test case.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) for the $$$i$$$-th test case.
standard output
standard input
Python 3
Python
800
train_105.jsonl
dc24dfb920ba16f5194cb37f6ced2e86
256 megabytes
["5\n1\n9\n10\n34\n880055535"]
PASSED
t = int(input()) vet= [] for _ in range(0,t): res = 0 n = int(input()) if n >=10: res = int(n/10) n = int(n%10) if n >=9: res +=1 vet.append(res) print(*vet, sep='\n')
1626964500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["YES\n.#.#\n#.#.\nNO\nYES\n....#\n...#.\n..#..\n.#...\n#....\nYES\n#..\n.#.\n#.#\n..."]
2bd60c4d46c9af426f1a700c8749cdde
null
Monocarp is playing Minecraft and wants to build a wall of cacti. He wants to build it on a field of sand of the size of $$$n \times m$$$ cells. Initially, there are cacti in some cells of the field. Note that, in Minecraft, cacti cannot grow on cells adjacent to each other by side — and the initial field meets this restriction. Monocarp can plant new cacti (they must also fulfil the aforementioned condition). He can't chop down any of the cacti that are already growing on the field — he doesn't have an axe, and the cacti are too prickly for his hands.Monocarp believes that the wall is complete if there is no path from the top row of the field to the bottom row, such that: each two consecutive cells in the path are adjacent by side; no cell belonging to the path contains a cactus. Your task is to plant the minimum number of cacti to build a wall (or to report that this is impossible).
For each test case, print NO in the first line if it is impossible to build a cactus wall without breaking the rules. Otherwise, print YES in the first line, then print $$$n$$$ lines of $$$m$$$ characters each — the field itself, where the $$$j$$$-th character of the $$$i$$$-th line is equal to '#', if there is a cactus on the intersection of the $$$i$$$-th row and the $$$j$$$-th column, otherwise it is '.'. If there are multiple optimal answers, print any of them.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$; $$$n \times m \le 4 \cdot 10^5$$$) — the number of rows and columns, respectively. Then $$$n$$$ rows follow, $$$i$$$-th row contains a string $$$s_i$$$ of length $$$m$$$, where $$$s_{i, j}$$$ is '#', if a cactus grows at the intersection of the $$$i$$$-th row and the $$$j$$$-th column. Otherwise, $$$s_{i, j}$$$ is '.'. The sum of $$$n \times m$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,400
train_090.jsonl
9befd4b760b1741faf21aaf7ff4c7aa9
256 megabytes
["4\n\n2 4\n\n.#..\n\n..#.\n\n3 3\n\n#.#\n\n...\n\n.#.\n\n5 5\n\n.....\n\n.....\n\n.....\n\n.....\n\n.....\n\n4 3\n\n#..\n\n.#.\n\n#.#\n\n..."]
PASSED
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): return u * m + v def g(u): return u // m, u % m def bfs(): dist = [inf] * l q, q0 = [], [] k, k0 = 0, 0 for i in range(0, l, m): if not ng[i]: dist[i] = s[i] if not dist[i]: q.append(i) else: q0.append(i) parent = [-1] * l for d in range(l + 1): while len(q) ^ k: u = q[k] i, j = g(u) for di, dj in v2: ni, nj = i + di, j + dj if not 0 <= ni < n or not 0 <= nj < m: continue v = f(ni, nj) if ng[v] or dist[v] ^ inf: continue dist[v] = d + s[v] parent[v] = u if not s[v]: q.append(v) else: q0.append(v) k += 1 q, q0 = q0, q k, k0 = k0, k return dist, parent t = int(input()) ans = [] v = [(1, 0), (0, 1), (-1, 0), (0, -1)] v2 = [(1, 1), (1, -1), (-1, 1), (-1, -1)] inf = pow(10, 9) + 1 for _ in range(t): n, m = map(int, input().split()) l = n * m s = [] ng = [0] * l for i in range(n): s0 = list(input().rstrip()) for j in range(m): if s0[j] & 1: for di, dj in v: ni, nj = i + di, j + dj if not 0 <= ni < n or not 0 <= nj < m: continue ng[f(ni, nj)] = 1 for j in s0: s.append((j & 1) ^ 1) dist, parent = bfs() mi = inf for i in range(m - 1, l, m): if mi > dist[i]: mi, u = dist[i], i if mi == inf: ans0 = "NO" ans.append(ans0) continue s[u] = 0 while not parent[u] == -1: u = parent[u] s[u] = 0 ans0 = "YES" ans.append(ans0) for i in range(n): ans0 = ["." if s[j] else "#" for j in range(i * m, (i + 1) * m)] ans.append("".join(ans0)) sys.stdout.write("\n".join(ans))
1666276500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["Yes\nabacaba\nYes\nabacaba\nYes\nabadabacaba\nYes\nabacabadaba\nNo\nNo"]
f6b7ad10382135b293bd3f2f3257d4d3
NoteIn first example there is exactly one occurrence of a string "abacaba" in the string "abacaba" as a substring.In second example seven question marks can be replaced with any seven lowercase English letters and with "abacaba" in particular.In sixth example there are two occurrences of a string "abacaba" as a substring.
Acacius is studying strings theory. Today he came with the following problem.You are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once?Each question mark should be replaced with exactly one lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc".Occurrence of a string $$$t$$$ of length $$$m$$$ in the string $$$s$$$ of length $$$n$$$ as a substring is a index $$$i$$$ ($$$1 \leq i \leq n - m + 1$$$) such that string $$$s[i..i+m-1]$$$ consisting of $$$m$$$ consecutive symbols of $$$s$$$ starting from $$$i$$$-th equals to string $$$t$$$. For example string "ababa" has two occurrences of a string "aba" as a substring with $$$i = 1$$$ and $$$i = 3$$$, but there are no occurrences of a string "aba" in the string "acba" as a substring.Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once.
For each test case output an answer for it. In case if there is no way to replace question marks in string $$$s$$$ with a lowercase English letters in such a way that there is exactly one occurrence of a string "abacaba" in the resulting string as a substring output "No". Otherwise output "Yes" and in the next line output a resulting string consisting of $$$n$$$ lowercase English letters. If there are multiple possible strings, output any. You may print every letter in "Yes" and "No" in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).
First line of input contains an integer $$$T$$$ ($$$1 \leq T \leq 5000$$$), number of test cases. $$$T$$$ pairs of lines with test case descriptions follow. The first line of a test case description contains a single integer $$$n$$$ ($$$7 \leq n \leq 50$$$), length of a string $$$s$$$. The second line of a test case description contains string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks.
standard output
standard input
PyPy 2
Python
1,500
train_008.jsonl
43ae8fd04fa92cd777368b0f479adf68
512 megabytes
["6\n7\nabacaba\n7\n???????\n11\naba?abacaba\n11\nabacaba?aba\n15\nasdf???f???qwer\n11\nabacabacaba"]
PASSED
# raw_input() # map(int,raw_input().split()) # for _ in xrange(input()): # print "Case #"+str(_+1)+": "+ if __name__ == "__main__": for _ in xrange(input()): x=list('abacaba') n=input() s=list(raw_input()) q=sum(s[i:i+7]==x for i in xrange(n-6)) if q>1: print 'NO' elif q==1: print 'YES' print ''.join(['d' if i=='?' else i for i in s]) else: b=True for i in xrange(n-6): if all(s[i+j] in (x[j],'?') for j in xrange(7)): t=s[i:i+7] s[i:i+7]=x z=['d' if k=='?' else k for k in s] q=sum(z[k:k+7]==x for k in xrange(n-6)) if q==1: print 'YES' print ''.join(z) b=False break s[i:i+7]=t if b: print 'NO'
1595149200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["YES\nYES\nYES\nNO"]
1c597da89880e87ffe791dd6b9fb2ac7
NoteIn the first test case, the initial array is $$$[5,10]$$$. You can perform $$$2$$$ operations to reach the goal: Choose $$$i=2$$$, and the array becomes $$$[5,5]$$$. Choose $$$i=2$$$, and the array becomes $$$[5,0]$$$. In the second test case, the initial array is $$$[1,2,3]$$$. You can perform $$$4$$$ operations to reach the goal: Choose $$$i=3$$$, and the array becomes $$$[1,2,1]$$$. Choose $$$i=2$$$, and the array becomes $$$[1,1,1]$$$. Choose $$$i=3$$$, and the array becomes $$$[1,1,0]$$$. Choose $$$i=2$$$, and the array becomes $$$[1,0,0]$$$. In the third test case, you can choose indices in the order $$$4$$$, $$$3$$$, $$$2$$$.
You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.You are allowed to perform this operation any number of times (possibly, zero): choose an index $$$i$$$ ($$$2 \le i \le n$$$), and change $$$a_i$$$ to $$$a_i - a_{i-1}$$$. Is it possible to make $$$a_i=0$$$ for all $$$2\le i\le n$$$?
For each test case, print "YES" (without quotes), if it is possible to change $$$a_i$$$ to $$$0$$$ for all $$$2 \le i \le n$$$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower).
The input consists 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 the test cases follows. The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$).
standard output
standard input
PyPy 3
Python
800
train_109.jsonl
4f0316775f4affe3c43f6ae30e56a757
256 megabytes
["4\n\n2\n\n5 10\n\n3\n\n1 2 3\n\n4\n\n1 1 1 1\n\n9\n\n9 9 8 2 4 4 3 5 3"]
PASSED
for _ in range(int(input())): n = int(input()) a = [int(i) for i in input().split()] for _ in range(n): for i in range(n-1, 0, -1): q = a[i]%a[i-1] if q == 0 : q = a[i-1] a[i] = q if len(set(a)) == 1 : print("YES") else : print("NO")
1657982100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["PATH\n4 \n1 5 3 6\nPAIRING\n2\n1 6\n2 4\nPAIRING\n3\n1 8\n2 5\n4 10\nPAIRING\n4\n1 7\n2 9\n3 11\n4 5"]
378f944b6839376dc71d85059d8efd2f
NoteThe path outputted in the first case is the following. The pairing outputted in the second case is the following. Here is an invalid pairing for the same graph  — the subgraph $$$\{1,3,4,5\}$$$ has $$$3$$$ edges. Here is the pairing outputted in the third case. It's valid because — The subgraph $$$\{1,8,2,5\}$$$ has edges ($$$1$$$,$$$2$$$) and ($$$1$$$,$$$5$$$). The subgraph $$$\{1,8,4,10\}$$$ has edges ($$$1$$$,$$$4$$$) and ($$$4$$$,$$$10$$$). The subgraph $$$\{4,10,2,5\}$$$ has edges ($$$2$$$,$$$4$$$) and ($$$4$$$,$$$10$$$). Here is the pairing outputted in the fourth case.
You have a simple and connected undirected graph consisting of $$$n$$$ nodes and $$$m$$$ edges.Consider any way to pair some subset of these $$$n$$$ nodes such that no node is present in more than one pair. This pairing is valid if for every pair of pairs, the induced subgraph containing all $$$4$$$ nodes, two from each pair, has at most $$$2$$$ edges (out of the $$$6$$$ possible edges). More formally, for any two pairs, $$$(a,b)$$$ and $$$(c,d)$$$, the induced subgraph with nodes $$$\{a,b,c,d\}$$$ should have at most $$$2$$$ edges. Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.Now, do one of the following: Find a simple path consisting of at least $$$\lceil \frac{n}{2} \rceil$$$ nodes. Here, a path is called simple if it does not visit any node multiple times. Find a valid pairing in which at least $$$\lceil \frac{n}{2} \rceil$$$ nodes are paired. It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.
For each test case, the output format is as follows. If you have found a pairing, in the first line output "PAIRING" (without quotes). Then, output $$$k$$$ ($$$\lceil \frac{n}{2} \rceil \le 2\cdot k \le n$$$), the number of pairs in your pairing. Then, in each of the next $$$k$$$ lines, output $$$2$$$ integers $$$a$$$ and $$$b$$$  — denoting that $$$a$$$ and $$$b$$$ are paired with each other. Note that the graph does not have to have an edge between $$$a$$$ and $$$b$$$! This pairing has to be valid, and every node has to be a part of at most $$$1$$$ pair. Otherwise, in the first line output "PATH" (without quotes). Then, output $$$k$$$ ($$$\lceil \frac{n}{2} \rceil \le k \le n$$$), the number of nodes in your path. Then, in the second line, output $$$k$$$ integers, $$$v_1, v_2, \ldots, v_k$$$, in the order in which they appear on the path. Formally, $$$v_i$$$ and $$$v_{i+1}$$$ should have an edge between them for every $$$i$$$ ($$$1 \le i &lt; k$$$). This path has to be simple, meaning no node should appear more than once.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains $$$2$$$ integers $$$n, m$$$ ($$$2 \le n \le 5\cdot 10^5$$$, $$$1 \le m \le 10^6$$$), denoting the number of nodes and edges, respectively. The next $$$m$$$ lines each contain $$$2$$$ integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), denoting that there is an undirected edge between nodes $$$u$$$ and $$$v$$$ in the given graph. It is guaranteed that the given graph is connected, and simple  — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3
Python
2,600
train_038.jsonl
56cb239809abb94829712810f4e67a79
256 megabytes
["4\n6 5\n1 4\n2 5\n3 6\n1 5\n3 5\n6 5\n1 4\n2 5\n3 6\n1 5\n3 5\n12 14\n1 2\n2 3\n3 4\n4 1\n1 5\n1 12\n2 6\n2 7\n3 8\n3 9\n4 10\n4 11\n2 4\n1 3\n12 14\n1 2\n2 3\n3 4\n4 1\n1 5\n1 12\n2 6\n2 7\n3 8\n3 9\n4 10\n4 11\n2 4\n1 3"]
PASSED
# Fast IO (only use in integer input) import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline t = int(input()) for _ in range(t): n,m = map(int,input().split()) connectionList = [] for _ in range(n): connectionList.append([]) for _ in range(m): u,v = map(int,input().split()) connectionList[u-1].append(v-1) connectionList[v-1].append(u-1) DFSLevel = [-1] * n DFSParent = [-1] * n vertexStack = [] vertexStack.append((0,1,-1)) # vertex depth and parent while vertexStack: vertex,depth,parent = vertexStack.pop() if DFSLevel[vertex] != -1: continue DFSLevel[vertex] = depth DFSParent[vertex] = parent for nextV in connectionList[vertex]: if DFSLevel[nextV] == -1: vertexStack.append((nextV,depth + 1,vertex)) if max(DFSLevel) >= n//2 + n % 2: for i in range(n): if DFSLevel[i] >= (n//2 + n%2): break longPath = [str(i + 1)] while DFSParent[i] != -1: longPath.append(str(DFSParent[i] + 1)) i = DFSParent[i] print("PATH") print(len(longPath)) print(" ".join(longPath)) else: levelWithVertex = list(enumerate(DFSLevel)) levelWithVertex.sort(key = lambda x: x[1]) i = 0 pair = [] while i < len(levelWithVertex) - 1: if levelWithVertex[i][1] == levelWithVertex[i + 1][1]: pair.append([levelWithVertex[i][0],levelWithVertex[i + 1][0]]) i += 2 else: i += 1 print("PAIRING") print(len(pair)) for elem in pair: print(str(elem[0] + 1)+" "+str(elem[1] + 1))
1596983700
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["8", "6", "0"]
9dc500c1f7fe621351c1d5359e71fda4
NoteThere are four collisions $$$(1,2,T-0.5)$$$, $$$(1,3,T-1)$$$, $$$(2,4,T+1)$$$, $$$(3,4,T+0.5)$$$, where $$$(u,v,t)$$$ means a collision happened between ghosts $$$u$$$ and $$$v$$$ at moment $$$t$$$. At each collision, each ghost gained one experience point, this means that $$$GX = 4 \cdot 2 = 8$$$.In the second test, all points will collide when $$$t = T + 1$$$. The red arrow represents the 1-st ghost velocity, orange represents the 2-nd ghost velocity, and blue represents the 3-rd ghost velocity.
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.There are $$$n$$$ ghosts in the universe, they move in the $$$OXY$$$ plane, each one of them has its own velocity that does not change in time: $$$\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j}$$$ where $$$V_{x}$$$ is its speed on the $$$x$$$-axis and $$$V_{y}$$$ is on the $$$y$$$-axis.A ghost $$$i$$$ has experience value $$$EX_i$$$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $$$GX = \sum_{i=1}^{n} EX_i$$$ will never increase.Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $$$T$$$, and magically all the ghosts were aligned on a line of the form $$$y = a \cdot x + b$$$. You have to compute what will be the experience index of the ghost kind $$$GX$$$ in the indefinite future, this is your task for today.Note that when Tameem took the picture, $$$GX$$$ may already be greater than $$$0$$$, because many ghosts may have scared one another at any moment between $$$[-\infty, T]$$$.
Output one line: experience index of the ghost kind $$$GX$$$ in the indefinite future.
The first line contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \leq n \leq 200000$$$, $$$1 \leq |a| \leq 10^9$$$, $$$0 \le |b| \le 10^9$$$) — the number of ghosts in the universe and the parameters of the straight line. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$V_{xi}$$$, $$$V_{yi}$$$ ($$$-10^9 \leq x_i \leq 10^9$$$, $$$-10^9 \leq V_{x i}, V_{y i} \leq 10^9$$$), where $$$x_i$$$ is the current $$$x$$$-coordinate of the $$$i$$$-th ghost (and $$$y_i = a \cdot x_i + b$$$). It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all $$$(i,j)$$$ $$$x_i \neq x_j$$$ for $$$i \ne j$$$.
standard output
standard input
Python 3
Python
2,000
train_071.jsonl
ea12c670bf1e4ff6452ef6f314d7d3fa
256 megabytes
["4 1 1\n1 -1 -1\n2 1 1\n3 1 1\n4 -1 -1", "3 1 0\n-1 1 0\n0 0 -1\n1 -1 -2", "3 1 0\n0 0 0\n1 0 0\n2 0 0"]
PASSED
import sys input = sys.stdin.readline N,A,B = map(int,input().split()) POS = {} for _ in range(N): x,vx,vy = map(int,input().split()) v = (vx,vy) score = vy - A*vx if score not in POS: POS[score] = {} if v not in POS[score]: POS[score][v] = 0 POS[score][v] += 1 COL = 0 for x in POS: size = sum([POS[x][v] for v in POS[x]]) COL += size*(size-1)//2 - sum([max(0,POS[x][v]*(POS[x][v]-1)//2) for v in POS[x]]) COL *= 2 print(COL)
1525183500
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["166666673", "500000010"]
1d01c01bec67572f9c1827ffabcc9793
NoteLet's describe all possible values of $$$x$$$ for the first sample: $$$[1, 1, 1]$$$: $$$B(x) = 1$$$, $$$B^2(x) = 1$$$; $$$[1, 1, 2]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[1, 1, 3]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[1, 2, 1]$$$: $$$B(x) = 3$$$, $$$B^2(x) = 9$$$; $$$[1, 2, 2]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[1, 2, 3]$$$: $$$B(x) = 3$$$, $$$B^2(x) = 9$$$; So $$$E = \frac{1}{6} (1 + 4 + 4 + 9 + 4 + 9) = \frac{31}{6}$$$ or $$$31 \cdot 6^{-1} = 166666673$$$.All possible values of $$$x$$$ for the second sample: $$$[3, 4, 5]$$$: $$$B(x) = 3$$$, $$$B^2(x) = 9$$$; $$$[3, 4, 6]$$$: $$$B(x) = 3$$$, $$$B^2(x) = 9$$$; $$$[3, 5, 5]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[3, 5, 6]$$$: $$$B(x) = 3$$$, $$$B^2(x) = 9$$$; $$$[4, 4, 5]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[4, 4, 6]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[4, 5, 5]$$$: $$$B(x) = 2$$$, $$$B^2(x) = 4$$$; $$$[4, 5, 6]$$$: $$$B(x) = 3$$$, $$$B^2(x) = 9$$$; So $$$E = \frac{1}{8} (9 + 9 + 4 + 9 + 4 + 4 + 4 + 9) = \frac{52}{8}$$$ or $$$13 \cdot 2^{-1} = 500000010$$$.
Let $$$x$$$ be an array of integers $$$x = [x_1, x_2, \dots, x_n]$$$. Let's define $$$B(x)$$$ as a minimal size of a partition of $$$x$$$ into subsegments such that all elements in each subsegment are equal. For example, $$$B([3, 3, 6, 1, 6, 6, 6]) = 4$$$ using next partition: $$$[3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6]$$$.Now you don't have any exact values of $$$x$$$, but you know that $$$x_i$$$ can be any integer value from $$$[l_i, r_i]$$$ ($$$l_i \le r_i$$$) uniformly at random. All $$$x_i$$$ are independent.Calculate expected value of $$$(B(x))^2$$$, or $$$E((B(x))^2)$$$. It's guaranteed that the expected value can be represented as rational fraction $$$\frac{P}{Q}$$$ where $$$(P, Q) = 1$$$, so print the value $$$P \cdot Q^{-1} \mod 10^9 + 7$$$.
Print the single integer — $$$E((B(x))^2)$$$ as $$$P \cdot Q^{-1} \mod 10^9 + 7$$$.
The first line contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the array $$$x$$$. The second line contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$1 \le l_i \le 10^9$$$). The third line contains $$$n$$$ integers $$$r_1, r_2, \dots, r_n$$$ ($$$l_i \le r_i \le 10^9$$$).
standard output
standard input
PyPy 3
Python
2,500
train_001.jsonl
d358b6e05c476041e40eb84a023596cc
256 megabytes
["3\n1 1 1\n1 2 3", "3\n3 4 5\n4 5 6"]
PASSED
mod = 10 ** 9 + 7 def pow_(x, y, p) : res = 1 x = x % p if x == 0: return 0 while y > 0: if (y & 1) == 1: res = (res * x) % p y = y >> 1 x = (x * x) % p return res def reverse(x, mod): return pow_(x, mod-2, mod) def prob(l_arr, r_arr): l_, r_ = max(l_arr), min(r_arr) if l_ > r_: return 1 p = (r_-l_+1) for l, r in zip(l_arr, r_arr): p *= reverse(r-l+1 ,mod) return (1-p) % mod n = int(input()) L = list(map(int, input().split())) R = list(map(int, input().split())) EX, EX2 = 0, 0 P = [0] * n pre = [0] * n for i in range(1, n): P[i] = prob(L[i-1: i+1], R[i-1: i+1]) pre[i] = (pre[i-1] + P[i]) % mod if i >= 2: pA, pB, pAB = 1-P[i-1], 1-P[i], 1-prob(L[i-2: i+1], R[i-2: i+1]) p_ = 1 - (pA+pB-pAB) EX2 += 2 * (P[i]*pre[i-2] + p_) % mod EX = sum(P) % mod EX2 += EX ans = (EX2 + 2*EX + 1) % mod print(ans)
1561905900
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["1 1 3", "1 2", "1"]
cadff0864835854f4f1e0234f2fd3edf
NoteIn the first sample the answer may be achieved this way: Append GCD$$$(1, 2, 3) = 1$$$, remove $$$2$$$. Append GCD$$$(1, 3) = 1$$$, remove $$$1$$$. Append GCD$$$(3) = 3$$$, remove $$$3$$$. We get the sequence $$$[1, 1, 3]$$$ as the result.
Let's call the following process a transformation of a sequence of length $$$n$$$.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $$$n$$$ integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence $$$1, 2, \dots, n$$$. Find the lexicographically maximum result of its transformation.A sequence $$$a_1, a_2, \ldots, a_n$$$ is lexicographically larger than a sequence $$$b_1, b_2, \ldots, b_n$$$, if there is an index $$$i$$$ such that $$$a_j = b_j$$$ for all $$$j &lt; i$$$, and $$$a_i &gt; b_i$$$.
Output $$$n$$$ integers  — the lexicographically maximum result of the transformation.
The first and only line of input contains one integer $$$n$$$ ($$$1\le n\le 10^6$$$).
standard output
standard input
Python 2
Python
1,600
train_020.jsonl
7347168d9576696fc6bb6f222daa672c
256 megabytes
["3", "2", "1"]
PASSED
N = input() ls = range(1,N+1) while len(ls) > 3: nls = ls[1::2] for i in xrange(len(ls) - len(nls)): print ls[0], ls = nls if len(ls)==3: print ls[0], ls[0], ls[2] elif len(ls)==2: print ls[0], ls[1] else: print ls[0]
1538750100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n3\n-1"]
36099a612ec5bbec1b95f2941e759c00
NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?
You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.
For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print $$$-1$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.
standard output
standard input
PyPy 3
Python
1,600
train_005.jsonl
51a68eedaaf699575a5c415c0a395a8f
256 megabytes
["3\n3 10\n6 3\n8 2\n1 4\n4 10\n4 1\n3 2\n2 6\n1 100\n2 15\n10 11\n14 100"]
PASSED
for i in range(int(input())): n,x = map(int,input().split()) mx = 0 mind = 1000000000000000000 d1 = 0 for i in range(n): d,h = map(int,input().split()) if d - h > mx: mx = d-h d1 = max(d1,d) import math d = d1 if x <= d1: print(1) continue if mx <= 0: print(-1) continue k = math.ceil((x-d)/mx) + 1 print(k)
1567694100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["aaaacbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nac"]
419ef3579fe142c295ec4d89ee7becfc
NoteIn the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence.
You are given strings $$$S$$$ and $$$T$$$, consisting of lowercase English letters. It is guaranteed that $$$T$$$ is a permutation of the string abc. Find string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.String $$$a$$$ is a permutation of string $$$b$$$ if the number of occurrences of each distinct character is the same in both strings.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
For each test case, output a single string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.
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 first line of each test case contains a string $$$S$$$ ($$$1 \le |S| \le 100$$$), consisting of lowercase English letters. The second line of each test case contains a string $$$T$$$ that is a permutation of the string abc. (Hence, $$$|T| = 3$$$). Note that there is no limit on the sum of $$$|S|$$$ across all test cases.
standard output
standard input
Python 3
Python
800
train_100.jsonl
5fcc132f12fbb7038f9009b0b4f2a589
256 megabytes
["7\nabacaba\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabc\nac\nabc"]
PASSED
import sys;input=sys.stdin.readline for _ in range(int(input())): a=sorted(input().strip()) t=input().strip() one=a.count(t[0]) two=a.count(t[1]) thr=a.count(t[2]) if one>0 and two>0 and thr>0: if t[0]=='a':print(t[0]*one+t[2]*thr+t[1]*two,end='') else:print('a'*a.count('a')+'b'*a.count('b')+'c'*a.count('c'),end='') elif one+two+thr==0:print('',end='') elif one+two==0:print(t[2]*thr,end='') elif one+thr==0:print(t[1]*two,end='') elif two+thr==0:print(t[0]*one,end='') elif one==0: if t[1]>t[2]:print(t[2]*thr+t[1]*two,end='') else:print(t[1]*two+t[2]*thr,end='') elif two==0: if t[0]>t[2]:print(t[2]*thr+t[0]*one,end='') else:print(t[0]*one+t[2]*thr,end='') elif thr==0: if t[1]>t[0]:print(t[0]*one+t[1]*two,end='') else:print(t[1]*two+t[0]*one,end='') print(''.join(a[one+two+thr:]))
1639661700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n3\n0\n0\n1\n3"]
b18dac401b655c06bee331e71eb3e4de
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
standard output
standard input
PyPy 3
Python
1,200
train_004.jsonl
82a54b80089295636bb6ec8e10302853
256 megabytes
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
PASSED
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 def numTeam(c, m, x): cmMin = min(c, m) # max(c,m) >= x >= min(c,m): Somente min(c,n) times com 1 de cada if x >= cmMin: return cmMin # max(c,m) >= min(c,m) > x: Times podem ter 2 c ou 2 m else: return min((c+m+x)//3, cmMin) # times = x # a, b = max(c-x, m-x), min(c-x, m-x) # while(True): # b -= 1 # a -= 2 # if b >= 0 and a >= 0: # times += 1 # a, b = max(a, b), min(a, b) # else: # break # return times for i in range(int(input())): coder, mathMan, normalMan = map(int, input().split()) print(numTeam(coder, mathMan, normalMan))
1568903700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nYES\nNO\nYES\nNO\nNO\nYES"]
2d011ba7eaa16642d77dade98966b54a
NoteIn the first test case: Initially $$$s_1 = \mathtt{cbc}$$$, $$$s_2 = \mathtt{aba}$$$. Operation with $$$k = 1$$$, after the operation $$$s_1 = \mathtt{abc}$$$, $$$s_2 = \mathtt{abc}$$$. In the second test case: Initially $$$s_1 = \mathtt{abcaa}$$$, $$$s_2 = \mathtt{cbabb}$$$. Operation with $$$k = 2$$$, after the operation $$$s_1 = \mathtt{bbcaa}$$$, $$$s_2 = \mathtt{cbaab}$$$. Operation with $$$k = 3$$$, after the operation $$$s_1 = \mathtt{aabaa}$$$, $$$s_2 = \mathtt{cbbbc}$$$. Operation with $$$k = 1$$$, after the operation $$$s_1 = \mathtt{cabaa}$$$, $$$s_2 = \mathtt{cbbba}$$$. Operation with $$$k = 2$$$, after the operation $$$s_1 = \mathtt{babaa}$$$, $$$s_2 = \mathtt{cbbca}$$$. Operation with $$$k = 1$$$, after the operation $$$s_1 = \mathtt{aabaa}$$$, $$$s_2 = \mathtt{cbbcb}$$$. Operation with $$$k = 2$$$, after the operation $$$s_1 = \mathtt{cbbaa}$$$, $$$s_2 = \mathtt{cbbaa}$$$. In the third test case, it's impossible to make strings equal.
You have two strings $$$s_1$$$ and $$$s_2$$$ of length $$$n$$$, consisting of lowercase English letters. You can perform the following operation any (possibly zero) number of times: Choose a positive integer $$$1 \leq k \leq n$$$. Swap the prefix of the string $$$s_1$$$ and the suffix of the string $$$s_2$$$ of length $$$k$$$. Is it possible to make these two strings equal by doing described operations?
For each test case, print "YES" if it is possible to make the strings equal, and "NO" otherwise.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the strings $$$s_1$$$ and $$$s_2$$$. The second line contains the string $$$s_1$$$ of length $$$n$$$, consisting of lowercase English letters. The third line contains the string $$$s_2$$$ of length $$$n$$$, consisting of lowercase English letters. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,200
train_091.jsonl
66cd98d4dc6d9d24a1d8e5aef40b1341
256 megabytes
["7\n\n3\n\ncbc\n\naba\n\n5\n\nabcaa\n\ncbabb\n\n5\n\nabcaa\n\ncbabz\n\n1\n\na\n\na\n\n1\n\na\n\nb\n\n6\n\nabadaa\n\nadaaba\n\n8\n\nabcabdaa\n\nadabcaba"]
PASSED
for _ in range(int(input())): n = int(input()) w1 = input() w2 = input()[::-1] pairs = {} odd = 0 for x in range(n): tmp_l = sorted([w1[x], w2[x]]) tmp = f'{tmp_l[0]}{tmp_l[1]}' if tmp not in pairs: pairs[tmp] = 1 else: pairs[tmp] += 1 for k, v in pairs.items(): if v % 2 == 1: if k[0] == k[1]: odd += 1 else: odd += 2 break if odd <= 1: print('YES') else: print('NO')
1664116500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["6.5", "20.0"]
9df3a94dfa537cabdc52388a771cd24f
NoteIn the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for . Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for . Thus, after four minutes the chicken will be cooked for . Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready .In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.
Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9. Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if .
The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).
standard output
standard input
Python 3
Python
1,700
train_004.jsonl
9c599dba93945d3720cdb2ec162ef9d1
256 megabytes
["3 2 6", "4 2 20"]
PASSED
import math k, d, t = map(int, input().split()) if d >= k: off = d - k else: off = math.ceil(k / d) * d - k times = t // (off / 2 + k) t1 = times * (off + k) t2 = t % (off / 2 + k) if t2 > k: t2 = k + (t2 - k) * 2 ans = t1 + t2 print (ans)
1519574700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["9.0000000000", "10.0000000000", "28964.2857142857"]
838e643a978adbeed791a24ac1046ab5
NoteIn the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day.The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is .You should write a program which will calculate average sleep times of Polycarp over all weeks.
Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point.
The first line contains two integer numbers n and k (1 ≤ k ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
standard output
standard input
Python 3
Python
1,300
train_000.jsonl
b8d62886bdafce7fc2f7705d3d221e04
256 megabytes
["3 2\n3 4 7", "1 1\n10", "8 2\n1 2 4 100000 123 456 789 1"]
PASSED
a,b=map(int,input().split()) x=list(map(int,input().split())) y=[a-b+1]*a z=list(range(1,a+1)) w=z[::-1] c=[] for i in range(a): c.append(min(y[i],z[i],w[i],b)) s=0 for i in range(a): s+=c[i]*x[i] print(s/(a-b+1))
1494860700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2 2", "1 4", "2 4", "0 1"]
63eb7dc9077b88df505e52fa4bba5851
NoteIn the first example, FJ can line up the cows as follows to achieve $$$2$$$ sleeping cows: Cow $$$1$$$ is lined up on the left side and cow $$$2$$$ is lined up on the right side. Cow $$$2$$$ is lined up on the left side and cow $$$1$$$ is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve $$$1$$$ sleeping cow: Cow $$$1$$$ is lined up on the left side. Cow $$$2$$$ is lined up on the left side. Cow $$$1$$$ is lined up on the right side. Cow $$$2$$$ is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve $$$2$$$ sleeping cows: Cow $$$1$$$ and $$$2$$$ are lined up on the left side. Cow $$$1$$$ and $$$2$$$ are lined up on the right side. Cow $$$1$$$ is lined up on the left side and cow $$$2$$$ is lined up on the right side. Cow $$$1$$$ is lined up on the right side and cow $$$2$$$ is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of $$$n$$$ units of grass, each with a sweetness $$$s_i$$$. Farmer John has $$$m$$$ cows, each with a favorite sweetness $$$f_i$$$ and a hunger value $$$h_i$$$. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats $$$h_i$$$ units. The moment a cow eats $$$h_i$$$ units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo $$$10^9+7$$$)? The order in which FJ sends the cows does not matter as long as no cows get upset.
Output two integers  — the maximum number of sleeping cows that can result and the number of ways modulo $$$10^9+7$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$, $$$1 \le m \le 5000$$$)  — the number of units of grass and the number of cows. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le n$$$)  — the sweetness values of the grass. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$f_i$$$ and $$$h_i$$$ ($$$1 \le f_i, h_i \le n$$$)  — the favorite sweetness and hunger value of the $$$i$$$-th cow. No two cows have the same hunger and favorite sweetness simultaneously.
standard output
standard input
PyPy 3
Python
2,500
train_077.jsonl
4accc91231dfe9fe0ff7551f1ee6d62b
256 megabytes
["5 2\n1 1 1 1 1\n1 2\n1 3", "5 2\n1 1 1 1 1\n1 2\n1 4", "3 2\n2 3 2\n3 1\n2 1", "5 1\n1 1 1 1 1\n2 5"]
PASSED
from sys import stdin, stdout import bisect at_dist = [] mx = [] cow = [] sums = [] m = [] res_p = 0 res_r = 1 def modInverse(a, m) : return power(a, m - 2, m) # To compute x^y under modulo m def power(x, y, m) : if (y == 0) : return 1 p = power(x, y // 2, m) % m p = (p * p) % m if(y % 2 == 0) : return p else : return ((x * p) % m) # Function to return gcd of a and b def gcd(a, b) : if (a == 0) : return b return gcd(b % a, a) def update(p, r): global res_p global res_r if p > res_p: res_p = p res_r = r elif p == res_p: res_r += r res_r = int(res_r % 1000000007) def set_way(f): right = bisect.bisect_right(cow[f],at_dist[f]) left = bisect.bisect_right(cow[f], mx[f] - at_dist[f]) mn = min(left, right) mul = right*left - mn plus = left + right if mul > 0: sums[f] = 2 m[f] = mul elif plus > 0: sums[f] = 1 m[f] = plus else: sums[f] = 0 m[f] = 1 def do_up(f): right = at_dist[f] b = bisect.bisect_right(cow[f],at_dist[f]) left = mx[f] - at_dist[f] if right >= left: b-=1 if b > 0: sums[f] = 2 m[f] = b else: sums[f] = 1 m[f] = 1 def main(): global res_p global res_r global mx n,M = list(map(int, stdin.readline().split())) grass = list(map(int, stdin.readline().split())) for i in range(n+1): at_dist.append(0) sums.append(0) m.append(0) cow.append([]) for i,x in enumerate(grass): at_dist[x] += 1 mx = list(at_dist) for _ in range(M): f,h = list(map(int, stdin.readline().split())) cow[f].append(h) for i in range(1,n+1): cow[i].sort() set_way(i) res_p += sums[i] res_r *= m[i] t_p = res_p t_r = res_r for i in range(n): f = grass[i] t_p -= sums[f] t_r = int(t_r* modInverse(m[f], 1000000007) % 1000000007) at_dist[f] -=1 left = mx[f] - at_dist[f] ii = bisect.bisect_left(cow[f], left) if ii < len(cow[f]) and cow[f][ii] == left: do_up(f) temp_p = t_p + sums[f] temp_r = t_r * m[f] update(temp_p, temp_r) set_way(f) t_p += sums[grass[i]] t_r = (t_r * m[grass[i]]) % 1000000007 stdout.write(str(res_p) + " " + str(int(res_r % 1000000007))) main()
1581953700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n0\n0\n1\n999999999\n381621773"]
b69170c8377623beb66db4706a02ffc6
NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are: $$$a=6$$$, $$$b=1$$$; $$$a=5$$$, $$$b=2$$$; $$$a=4$$$, $$$b=3$$$.
There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that: Alice will get $$$a$$$ ($$$a &gt; 0$$$) candies; Betty will get $$$b$$$ ($$$b &gt; 0$$$) candies; each sister will get some integer number of candies; Alice will get a greater amount of candies than Betty (i.e. $$$a &gt; b$$$); all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a&gt;b$$$.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.
standard output
standard input
Python 3
Python
800
train_030.jsonl
366761afa14b08a3d90f95dc723f4c66
256 megabytes
["6\n7\n1\n2\n3\n2000000000\n763243547"]
PASSED
from math import ceil T=int(input()) while T>0: A=int(input()) B=ceil(A-A/2-1) print(B) T-=1
1586788500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3 5\n\n3 3\n\n3 4\n\n5 5"]
c46d1a87c6a6540d573c0391e845e1db
NoteIn the first sample, the train was initially at the station $$$5$$$, after the first application of the gadget it did not move, after the second application it moved to the station $$$3$$$, and after the third application moved again to the station $$$5$$$.
This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with $$$n$$$ stations, indexed consecutively from $$$1$$$ to $$$n$$$. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers $$$l$$$ and $$$r$$$ ($$$l \le r$$$), and then check, whether the train is located on a station with index between $$$l$$$ and $$$r$$$, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most $$$k$$$ stations away. Formally, if the train was at the station $$$x$$$ when the gadget was applied, then at the next application of the gadget the train can appear at any station $$$y$$$ such that $$$\max(1, x - k) \leq y \leq \min(n, x + k)$$$.Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than $$$4500$$$ applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than $$$4500$$$ applications of the gadgets?
null
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^{18}$$$, $$$0 \leq k \leq 10$$$) — the number of stations and the maximum number of stations the train can move between two applications of the gadget.
standard output
standard input
Python 3
Python
2,100
train_003.jsonl
3542385115c63e21e620f9879ba57b65
512 megabytes
["10 2\n\nYes\n\nNo\n\nYes\n\nYes"]
PASSED
# import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try : #raise ModuleNotFoundError import numpy def dprint(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) dprint('debug mode') except ModuleNotFoundError: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId>0: dprint('use input', inId) sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件 if outId>0: dprint('use output', outId) sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件 atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit N, K = getIntList() b1 = 1 b2 = N def spaned(): global b1 global b2 b1-=K b2+=K if b1<1: b1 = 1 if b2>N: b2 = N import random while True: while b2 - b1+1 >K*5: mid = (b2+b1)//2 print(b1,mid) r = input() if r == 'Yes': if b1== mid: sys.exit() b2 = mid elif r == 'No': b1 =mid +1 elif r =='Bad': sys.exit() spaned() t = random.randint(b1,b2) print(t,t) r = input() if r=='Yes': sys.exit() elif r== 'Bad': sys.exit() spaned()
1536165300
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
2 seconds
["4\n9\n5"]
33e9714f22b603f002d02ef42835ff57
NoteFor the first test case, one possibility for Victor's original grid is:$$$1$$$$$$3$$$$$$2$$$$$$4$$$For the second test case, one possibility for Victor's original grid is:$$$3$$$$$$8$$$$$$8$$$$$$5$$$$$$9$$$$$$5$$$$$$5$$$$$$1$$$$$$5$$$$$$5$$$$$$9$$$$$$9$$$$$$8$$$$$$4$$$$$$2$$$$$$9$$$For the third test case, one possibility for Victor's original grid is:$$$4$$$$$$3$$$$$$2$$$$$$1$$$$$$1$$$$$$2$$$$$$3$$$$$$4$$$$$$5$$$$$$6$$$$$$7$$$$$$8$$$$$$8$$$$$$9$$$$$$9$$$$$$1$$$
Note: The XOR-sum of set $$$\{s_1,s_2,\ldots,s_m\}$$$ is defined as $$$s_1 \oplus s_2 \oplus \ldots \oplus s_m$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.After almost winning IOI, Victor bought himself an $$$n\times n$$$ grid containing integers in each cell. $$$n$$$ is an even integer. The integer in the cell in the $$$i$$$-th row and $$$j$$$-th column is $$$a_{i,j}$$$.Sadly, Mihai stole the grid from Victor and told him he would return it with only one condition: Victor has to tell Mihai the XOR-sum of all the integers in the whole grid.Victor doesn't remember all the elements of the grid, but he remembers some information about it: For each cell, Victor remembers the XOR-sum of all its neighboring cells.Two cells are considered neighbors if they share an edge — in other words, for some integers $$$1 \le i, j, k, l \le n$$$, the cell in the $$$i$$$-th row and $$$j$$$-th column is a neighbor of the cell in the $$$k$$$-th row and $$$l$$$-th column if $$$|i - k| = 1$$$ and $$$j = l$$$, or if $$$i = k$$$ and $$$|j - l| = 1$$$.To get his grid back, Victor is asking you for your help. Can you use the information Victor remembers to find the XOR-sum of the whole grid?It can be proven that the answer is unique.
For each test case, output a single integer — the XOR-sum of the whole grid.
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 even integer $$$n$$$ ($$$2 \leq n \leq 1000$$$) — the size of the grid. Then follows $$$n$$$ lines, each containing $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th of these lines represents the XOR-sum of the integers in all the neighbors of the cell in the $$$i$$$-th row and $$$j$$$-th column. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$ and in the original grid $$$0 \leq a_{i, j} \leq 2^{30} - 1$$$. Hack Format To hack a solution, use the following format: The first line should contain a single integer t ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case should contain a single even integer $$$n$$$ ($$$2 \leq n \leq 1000$$$) — the size of the grid. Then $$$n$$$ lines should follow, each containing $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th of these lines is $$$a_{i,j}$$$ in Victor's original grid. The values in the grid should be integers in the range $$$[0, 2^{30}-1]$$$ The sum of $$$n$$$ over all test cases must not exceed $$$1000$$$.
standard output
standard input
PyPy 3-64
Python
2,300
train_093.jsonl
d174af94b5f7029e310c1ba4e3fa85cf
256 megabytes
["3\n2\n1 5\n5 1\n4\n1 14 8 9\n3 1 5 9\n4 13 11 1\n1 15 4 11\n4\n2 4 1 6\n3 7 3 10\n15 9 4 2\n12 7 15 1"]
PASSED
''' E. Grid Xor https://codeforces.com/contest/1629/problem/E ''' import io, os, sys input = sys.stdin.readline output = sys.stdout.write DEBUG = os.environ.get('debug') not in [None, '0'] if DEBUG: from inspect import currentframe, getframeinfo from re import search def debug(*args): if not DEBUG: return frame = currentframe().f_back s = getframeinfo(frame).code_context[0] r = search(r"\((.*)\)", s).group(1) vnames = r.split(', ') var_and_vals = [f'{var}={val}' for var, val in zip(vnames, args)] prefix = f'{currentframe().f_back.f_lineno:02d}: ' print(f'{prefix}{", ".join(var_and_vals)}') INF = float('inf') # ----------------------------------------- # https://codeforces.com/blog/entry/99276?#comment-880317 # each cell should have odd number of chosen neighbors # fix row 1 to all 0 # then choose (r, c) if (r-1, c) has even number of 1 neighbors # but why is last row valid? def solve(N, grid): res = 0 chosen = [[0]*N for _ in range(N)] for r in range(1, N): for c in range(N): cnt = 0 if r > 1: cnt += chosen[r-2][c] if c > 0: cnt += chosen[r-1][c-1] if c < N-1: cnt += chosen[r-1][c+1] if cnt % 2 == 0: chosen[r][c] = 1 res ^= grid[r][c] return res def main(): T = int(input()) for _ in range(T): N = int(input()) grid = [list(map(int, input().split())) for _ in range(N)] out = solve(N, grid) print(out) if __name__ == '__main__': main()
1642862100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
a67ea891cd6084ceeaace8894cf18e60
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i &lt; j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds.
standard output
standard input
Python 2
Python
1,600
train_023.jsonl
01de2d8acf297a6644650db0a0fab976
256 megabytes
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
PASSED
n = input() A = map(int, raw_input().split()) M = [raw_input() for ii in range(n)] seen = [False for ii in range(n)] vi = [] def dfs(id): seen[id] = True vi.append(id) for ii in range(n): if M[id][ii] == '1' and seen[ii] == False: dfs(ii) for ii in range(0,n): if seen[ii] == False: vi = [] dfs(ii) k = [A[x] for x in vi] k.sort() vi.sort() # print vi, k for jj in range(len(vi)): A[vi[jj]] = k[jj] for ii in A: print ii,
1419951600
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["1 2", "2 4", "2 5", "2 7"]
4ebbda2fc1a260e9827205a25addd9c4
NoteIn example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.DefinitionsA substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".Given a string, you have to find two values: the number of good substrings of even length; the number of good substrings of odd length.
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
standard output
standard input
Python 3
Python
2,000
train_002.jsonl
04d8f0a1df0fda43c203f00183d2ff14
256 megabytes
["bb", "baab", "babb", "babaa"]
PASSED
s = input() a = [] for c in s: a.append(ord(c) - ord('a')) cnt = [[0, 0], [0, 0]] ans = [0, 0] for i in range(len(a)): cnt[a[i]][i % 2] += 1 ans[0] += cnt[a[i]][i % 2] ans[1] += cnt[a[i]][1 - i % 2] print(ans[1], ans[0])
1406215800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["1 1 0", "10 10 4 0 0", "276 276 132 36 0 0 0"]
6f58b157c875651127af682f34ca794c
NoteExample $$$1$$$: there are two possible trees: with edges $$$(1-2)$$$, and $$$(1-3)$$$ — here the centroid is $$$1$$$; and with edges $$$(1-2)$$$, and $$$(2-3)$$$ — here the centroid is $$$2$$$. So the answer is $$$1, 1, 0$$$.Example $$$2$$$: there are $$$24$$$ possible trees, for example with edges $$$(1-2)$$$, $$$(2-3)$$$, $$$(3-4)$$$, and $$$(4-5)$$$. Here the centroid is $$$3$$$.
Consider every tree (connected undirected acyclic graph) with $$$n$$$ vertices ($$$n$$$ is odd, vertices numbered from $$$1$$$ to $$$n$$$), and for each $$$2 \le i \le n$$$ the $$$i$$$-th vertex is adjacent to exactly one vertex with a smaller index.For each $$$i$$$ ($$$1 \le i \le n$$$) calculate the number of trees for which the $$$i$$$-th vertex will be the centroid. The answer can be huge, output it modulo $$$998\,244\,353$$$.A vertex is called a centroid if its removal splits the tree into subtrees with at most $$$(n-1)/2$$$ vertices each.
Print $$$n$$$ integers in a single line, the $$$i$$$-th integer is the answer for the $$$i$$$-th vertex (modulo $$$998\,244\,353$$$).
The first line contains an odd integer $$$n$$$ ($$$3 \le n &lt; 2 \cdot 10^5$$$, $$$n$$$ is odd) — the number of the vertices in the tree.
standard output
standard input
PyPy 3-64
Python
3,000
train_097.jsonl
2bd4cb2ed00303e871e5f6c57e91a144
256 megabytes
["3", "5", "7"]
PASSED
def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N = len(A) self.merge_func = merge_func self.lg = [0]*(N + 1) for i in range(2, N+1): self.lg[i] = self.lg[i >> 1] + 1 self.pow_2 = [pow(2,i) for i in range(20)] self.table = [None]*(self.lg[N] + 1) st0 = self.table[0] = [a for a in A] b = 1 for i in range(self.lg[N]): st0 = self.table[i+1] = [self.merge_func(u,v) for u, v in zip(st0, st0[b:])] b <<= 1 def query(self,s,t): b = t-s+1 m = self.lg[b] return self.merge_func(self.table[m][s],self.table[m][t-self.pow_2[m]+1]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x class slope_trick(): def __init__(self): self.L = [10**17] self.R = [10**17] self.min_f = 0 self.x_left = 0 self.x_right = 0 def add_right(self,a): a -= self.x_left l0 = -self.L[0] self.min_f = self.min_f + max(0,l0-a) if l0 <= a: a += self.x_left a -= self.x_right heappush(self.R,a) else: heappush(self.L,-a) a = -heappop(self.L) a += self.x_left a -= self.x_right heappush(self.R,a) #self.min_f = self.min_f + max(0,l0-a) def add_left(self,a): a -= self.x_right r0 = self.R[0] self.min_f = self.min_f + max(0,a-r0) if a <= r0: a += self.x_right a -= self.x_left heappush(self.L,-a) else: heappush(self.R,a) a = heappop(self.R) a += self.x_right a -= self.x_left heappush(self.L,-a) #self.min_f = self.min_f + max(0,a-r0) def add_abs(self,a): self.add_left(a) self.add_right(a) def change_min_slide(self,a,b): self.x_left += a self.x_right += b def get_val(self,x): L = [-l+self.x_left for l in self.L] L.sort() R = [r+self.x_right for r in self.R] R.sort() res = self.min_f if 0 < L[-1]: L = L[::-1] n = len(L) for i in range(n): c0 = L[i] c1 = L[i+1] if c1 <= x <= c0: res += (i+1) * (c0-x) break else: res += (i+1) * (c0-c1) return res elif L[-1] <= x <= R[0]: return res else: n = len(R) for i in range(n): c0 = R[i] c1 = R[i+1] if c0 <= x <= c1: res += (i+1) * (x-c0) break else: res += (i+1) * (c1-c0) return res class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: k >>= 1 self.tree[k] = self.segfunc(self.tree[2*k], self.tree[2*k+1]) def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num right = [] while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: right.append(self.tree[r-1]) l >>= 1 r >>= 1 for e in right[::-1]: res = self.segfunc(res,e) return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) def cmb(n, r, mod): if ( r<0 or r>n ): return 0 return (g1[n] * g2[r] % mod) * g2[n-r] % mod mod = 998244353 N = 2*10**5 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 n = int(input()) ans = [0] * n pre = [(g1[n-i]*g1[i-2] % mod)*cmb((n-1)//2,i-1,mod)%mod for i in range(n+1)] for i in range(1,n+1): pre[i] += pre[i-1] pre[i] %= mod for i in range(1,n+1): """ 部分木にある """ res = (g1[n-1] - (pre[n]-pre[i])) % mod """ 自分の木が小さすぎる """ if i!=1: res -= (g1[n-i] * g1[i-2] % mod) * (((cmb(n-1,i-1,mod)-cmb((n-1)//2,i-1,mod)) % mod) * (i-1) % mod) % mod res %= mod ans[i-1] = res print(*ans)
1650378900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES"]
6ca98e655007bfb86f1039c9f096557e
NoteIn the first test case, we can make the following transformation: Choose $$$k = 2$$$. Choose $$$i_1 = 1$$$, $$$i_2 = 2$$$. Add $$$1$$$ to $$$a_1$$$ and $$$a_2$$$. The resulting array is $$$[0, 2, 0]$$$. Swap the elements on the second and third positions. In the second test case there is no suitable transformation.In the third test case we choose $$$k = 0$$$ and do not change the order of elements.
You are given two arrays of integers $$$a_1, a_2, \ldots, a_n$$$ and $$$b_1, b_2, \ldots, b_n$$$.Let's define a transformation of the array $$$a$$$: Choose any non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$. Choose $$$k$$$ distinct array indices $$$1 \le i_1 &lt; i_2 &lt; \ldots &lt; i_k \le n$$$. Add $$$1$$$ to each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$, all other elements of array $$$a$$$ remain unchanged. Permute the elements of array $$$a$$$ in any order. Is it possible to perform some transformation of the array $$$a$$$ exactly once, so that the resulting array is equal to $$$b$$$?
For each test case, print "YES" (without quotes) if it is possible to perform a transformation of the array $$$a$$$, so that the resulting array is equal to $$$b$$$. Print "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Descriptions of test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \le a_i \le 100$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-100 \le b_i \le 100$$$).
standard output
standard input
PyPy 3
Python
900
train_091.jsonl
1461f1548d849b9936199c079f040753
256 megabytes
["3\n3\n-1 1 0\n0 0 2\n1\n0\n2\n5\n1 2 3 4 5\n1 2 3 4 5"]
PASSED
import sys t = int(sys.stdin.readline()) for _ in range(t): n = int(sys.stdin.readline()) a = list(map(int, sys.stdin.readline().split())) b = list(map(int, sys.stdin.readline().split())) newa = sorted(a) newb = sorted(b) ans = "YES" for i in range(n): if (newa[i] != newb[i]) and (newa[i] + 1 != newb[i]): ans = "NO" print(ans)
1636869900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3", "0\n2"]
d7ffedb180378b3ab70e5f05c79545f5
NoteIn the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying.In the second example, at the beginning, child i is holding toy i for 1 ≤ i ≤ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now: In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play. In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys: Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set. If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever. Children request toys at distinct moments of time. No two children request a toy at the same time. If a child is granted a toy, he never gives it back until he finishes playing with his lovely set. If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting. If two children are waiting for the same toy, then the child who requested it first will take the toy first.Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request.
For each query, print on a single line the number of children who will start crying when child x makes his last request for toy y. Please answer all queries independent of each other.
The first line contains four integers n, m, k, q (1 ≤ n, m, k, q ≤ 105) — the number of children, toys, scenario requests and queries. Each of the next k lines contains two integers a, b (1 ≤ a ≤ n and 1 ≤ b ≤ m) — a scenario request meaning child a requests toy b. The requests are given in the order they are made by children. Each of the next q lines contains two integers x, y (1 ≤ x ≤ n and 1 ≤ y ≤ m) — the request to be added to the scenario meaning child x will request toy y just after getting the toy he is waiting for (if any). It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.
standard output
standard input
PyPy 3
Python
2,700
train_037.jsonl
e3d87d652482d805ba50dd86ac041a93
256 megabytes
["3 3 5 1\n1 1\n2 2\n3 3\n1 2\n2 3\n3 1", "5 4 7 2\n1 1\n2 2\n2 1\n5 1\n3 3\n4 4\n4 1\n5 3\n5 4"]
PASSED
from sys import stdin from sys import stdout n, m, k, q = map(int, stdin.readline().split()) d = [None for i in range(m)] roots = set(range(n)) matrix = [[] for i in range(n)] for i in range(k): x, y = map(int, stdin.readline().split()) if d[y - 1] is None: d[y - 1] = x - 1 else: matrix[d[y - 1]].append(x - 1) roots.discard(x - 1) d[y - 1] = x - 1 location = [None for i in range(n)] comp_of_conn = [] graph = [matrix[i][:] for i in range(n)] for i in roots: stack = [] time = 1 queue = [[i, time]] while queue: j = queue[-1] time += 1 if len(graph[j[0]]) == 0: stack.append(queue.pop() + [time]) else: queue.append([graph[j[0]].pop(), time]) stack.reverse() if len(stack) > 1: for j in range(len(stack)): location[stack[j][0]] = [len(comp_of_conn), j] for j in range(len(stack) - 1, -1, -1): app = 0 for u in matrix[stack[j][0]]: app += stack[location[u][1]][3] stack[j].append(app + 1) comp_of_conn.append(stack) for i in range(q): x, y = map(int, stdin.readline().split()) x -= 1 y = d[y - 1] if y is None: stdout.write('0\n') elif location[x] is not None and location[y] is not None and location[x][0] == location[y][0]: c = location[x][0] ind_x = location[x][1] ind_y = location[y][1] if comp_of_conn[c][ind_x][1] < comp_of_conn[c][ind_y][1] and comp_of_conn[c][ind_x][2] > comp_of_conn[c][ind_y][ 2]: stdout.write(str(comp_of_conn[c][ind_x][3]) + '\n') else: stdout.write('0\n') else: stdout.write('0\n')
1496326500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
4 seconds
["YES\n4\n4 3 1\n2 3 1\n2 5 2\n1 5 2", "NO"]
f236c4110a973d1c9f63cbbcc74b9e0b
NoteConsider the first example. After the first move the locations of stones is $$$[2, 2, 6, 5, 9]$$$. After the second move the locations of stones is $$$[2, 3, 5, 5, 9]$$$. After the third move the locations of stones is $$$[2, 5, 5, 5, 7]$$$. After the last move the locations of stones is $$$[4, 5, 5, 5, 5]$$$.
There are $$$n$$$ stones arranged on an axis. Initially the $$$i$$$-th stone is located at the coordinate $$$s_i$$$. There may be more than one stone in a single place.You can perform zero or more operations of the following type: take two stones with indices $$$i$$$ and $$$j$$$ so that $$$s_i \leq s_j$$$, choose an integer $$$d$$$ ($$$0 \leq 2 \cdot d \leq s_j - s_i$$$), and replace the coordinate $$$s_i$$$ with $$$(s_i + d)$$$ and replace coordinate $$$s_j$$$ with $$$(s_j - d)$$$. In other words, draw stones closer to each other. You want to move the stones so that they are located at positions $$$t_1, t_2, \ldots, t_n$$$. The order of the stones is not important — you just want for the multiset of the stones resulting positions to be the same as the multiset of $$$t_1, t_2, \ldots, t_n$$$.Detect whether it is possible to move the stones this way, and if yes, construct a way to do so. You don't need to minimize the number of moves.
If it is impossible to move the stones this way, print "NO". Otherwise, on the first line print "YES", on the second line print the number of operations $$$m$$$ ($$$0 \le m \le 5 \cdot n$$$) required. You don't have to minimize the number of operations. Then print $$$m$$$ lines, each containing integers $$$i, j, d$$$ ($$$1 \le i, j \le n$$$, $$$s_i \le s_j$$$, $$$0 \leq 2 \cdot d \leq s_j - s_i$$$), defining the operations. One can show that if an answer exists, there is an answer requiring no more than $$$5 \cdot n$$$ operations.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) – the number of stones. The second line contains integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 10^9$$$) — the initial positions of the stones. The second line contains integers $$$t_1, t_2, \ldots, t_n$$$ ($$$1 \le t_i \le 10^9$$$) — the target positions of the stones.
standard output
standard input
Python 3
Python
2,300
train_053.jsonl
f0457f67d945d41dd13fd78a533db099
256 megabytes
["5\n2 2 7 4 9\n5 4 5 5 5", "3\n1 5 10\n3 5 7"]
PASSED
from collections import namedtuple Stone = namedtuple('Stone', ['s', 'i']) def debug(*args, **kwargs): import sys #print(*args, *('{}={}'.format(k, v) for k, v in kwargs.items()), sep='; ', file=sys.stderr) def solve(n, s, t): #debug(s=s, t=t) s = list(map(lambda s_i: Stone(s_i[1], s_i[0]), enumerate(s))) t = t[:] s.sort() t.sort() #debug(s=s, t=t) diff = [s_.s - t_ for s_, t_ in zip(s, t)] j = 0 while j < n and diff[j] <= 0: j += 1 moves = [] for i in range(n): if diff[i] == 0: continue if diff[i] > 0: return None, None while j < n and -diff[i] >= diff[j]: #debug("about to gobble", i=i, j=j, moves=moves, diff=diff) moves.append((s[i].i, s[j].i, diff[j])) diff[i] += diff[j] diff[j] = 0 while j < n and diff[j] <= 0: j += 1 #debug(i=i, j=j, moves=moves, diff=diff) if diff[i] != 0: if j == n: return None, None moves.append((s[i].i, s[j].i, -diff[i])) diff[j] -= -diff[i] diff[i] = 0 #debug("gobbled", i=i, j=j, moves=moves, diff=diff) return len(moves), moves def check(n, s, t, m, moves): s = s[:] t = t[:] for i, j, d in moves: debug(i=i, j=j, d=d, s=s) assert d > 0 and s[j] - s[i] >= 2*d s[i] += d s[j] -= d debug(s=s, t=t) s.sort() t.sort() assert s == t def main(): n = int(input()) s = list(map(int, input().split())) t = list(map(int, input().split())) m, moves = solve(n, s, t) if m is None: print("NO") return #check(n, s, t, m, moves) print("YES") print(m) for i, j, d in moves: print(i + 1, j + 1, d) if __name__ == "__main__": main()
1559399700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0\n3\n1\n3\n2"]
ab6fefc6c15d4647bc601f1f9db21d3f
NoteIn the first test case, it is already given a number divisible by $$$25$$$.In the second test case, we can remove the digits $$$1$$$, $$$3$$$, and $$$4$$$ to get the number $$$75$$$.In the third test case, it's enough to remove the last digit to get the number $$$325$$$.In the fourth test case, we can remove the three last digits to get the number $$$50$$$.In the fifth test case, it's enough to remove the digits $$$4$$$ and $$$7$$$.
It is given a positive integer $$$n$$$. In $$$1$$$ move, one can select any single digit and remove it (i.e. one selects some position in the number and removes the digit located at this position). The operation cannot be performed if only one digit remains. If the resulting number contains leading zeroes, they are automatically removed.E.g. if one removes from the number $$$32925$$$ the $$$3$$$-rd digit, the resulting number will be $$$3225$$$. If one removes from the number $$$20099050$$$ the first digit, the resulting number will be $$$99050$$$ (the $$$2$$$ zeroes going next to the first digit are automatically removed).What is the minimum number of steps to get a number such that it is divisible by $$$25$$$ and positive? It is guaranteed that, for each $$$n$$$ occurring in the input, the answer exists. It is guaranteed that the number $$$n$$$ has no leading zeros.
For each test case output on a separate line an integer $$$k$$$ ($$$k \ge 0$$$) — the minimum number of steps to get a number such that it is divisible by $$$25$$$ and positive.
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$$$ ($$$25 \le n \le 10^{18}$$$). It is guaranteed that, for each $$$n$$$ occurring in the input, the answer exists. It is guaranteed that the number $$$n$$$ has no leading zeros.
standard output
standard input
Python 3
Python
900
train_093.jsonl
5fddd654b95c203f43995f4b1c378d58
256 megabytes
["5\n100\n71345\n3259\n50555\n2050047"]
PASSED
for _ in range(int(input())): s = input() count = 0 for i in range(len(s) - 1): for j in range(i+1, len(s)): if int(s[i]+s[j]) % 25 == 0: count = len(s)-i-2 print(count)
1634135700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2", "1"]
8d2845c33645ac45d4d37f9493b0c380
NoteExplanation to the first and second samples from the statement, respectively:
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.
Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.
The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000,  - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.
standard output
standard input
Python 3
Python
1,400
train_002.jsonl
be3888292b854b243871809a1d2f5396
256 megabytes
["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"]
PASSED
num_coor = input().split() num_storm = int(num_coor[0]) han_coor = [int(num_coor[1]), int(num_coor[2])] l = [] for i in range(num_storm): temp = tuple([int(h) for h in input().split()]) l.append(temp) for f in range(len(l)): temp = l[f] if temp[0] == han_coor[0]: l[f] = "banana" else: slope = ((temp[1] - han_coor[1]) / (temp[0] - han_coor[0])) l[f] = float(slope) num = set(l) print(len(num))
1423931400
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["a", "aab", "aaabb"]
2924053ee058c531254d690f0b12d324
NoteIn the first sample, one can choose the subsequence {3} and form a string "a".In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".
You are given a string s, consisting of lowercase English letters, and the integer m.One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves.Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order.Formally, we choose a subsequence of indices 1 ≤ i1 &lt; i2 &lt; ... &lt; it ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j,  j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ ik ≤ j + m - 1.Then we take any permutation p of the selected indices and form a new string sip1sip2... sipt.Find the lexicographically smallest string, that can be obtained using this procedure.
Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.
The first line of the input contains a single integer m (1 ≤ m ≤ 100 000). The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.
standard output
standard input
PyPy 3
Python
1,900
train_043.jsonl
a521e9d5f408133937bca461e491d22d
256 megabytes
["3\ncbabc", "2\nabcab", "3\nbcabcbaccba"]
PASSED
m = int(input()) s = input() ans = [] mark = [True for _ in range(len(s))] z = 'a' i = 0 while i <= len(s) - m: k = i for j in range(i, i + m): if s[j] <= s[k]: k = j ans.append(s[k]) z = max(z, s[k]) mark[k] = False i = k i += 1 for i in range(len(s)): if s[i] < z and mark[i]: ans.append(s[i]) print(''.join(str(i) for i in sorted(ans)))
1475928900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["5\nMike 1\nGerald 1\nKate 1\nTank 1\nDavid 2", "5\nvalera 0\nvanya 3\nedik 3\npasha 3\nigor 3"]
1e80e51e770cd901156382d2e35cb5bf
NoteIn the first test case consider user David. Users Mike and Tank have one common friend (Gerald) with David. User Kate has no common friends with David. That's why David's suggested friends are users Mike and Tank.
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as m username pairs ai, bi (ai ≠ bi). Each pair ai, bi means that users ai and bi are friends. Friendship is symmetric, that is, if ai is friends with bi, then bi is also friends with ai. User y is a suggested friend for user x, if the following conditions are met: x ≠ y; x and y aren't friends; among all network users who meet the first two conditions, user y has most of all common friends with user x. User z is a common friend of user x and user y (z ≠ x, z ≠ y), if x and z are friends, and y and z are also friends. Your task is to help Polycarpus to implement a mechanism for determining suggested friends.
In the first line print a single integer n — the number of network users. In next n lines print the number of suggested friends for each user. In the i-th line print the name of the user ci and the number of his suggested friends di after a space. You can print information about the users in any order.
The first line contains a single integer m (1 ≤ m ≤ 5000) — the number of pairs of friends in the social network. Next m lines contain pairs of names of the users who are friends with each other. The i-th line contains two space-separated names ai and bi (ai ≠ bi). The users' names are non-empty and consist of at most 20 uppercase and lowercase English letters. It is guaranteed that each pair of friends occurs only once in the input. For example, the input can't contain x, y and y, x at the same time. It is guaranteed that distinct users have distinct names. It is guaranteed that each social network user has at least one friend. The last thing guarantees that each username occurs at least once in the input.
standard output
standard input
Python 2
Python
2,200
train_079.jsonl
7a946d97c0d1774198bcfb2efb386328
256 megabytes
["5\nMike Gerald\nKate Mike\nKate Tank\nGerald Tank\nGerald David", "4\nvalera vanya\nvalera edik\npasha valera\nigor valera"]
PASSED
import sys from collections import defaultdict n,m =0, input() mp={} G = defaultdict(list) def myfind(c): global n,mp if c not in mp: mp[c] = n n += 1 return mp[c] def add(u,v): G[u].append(v) G[v].append(u) for ch in sys.stdin: a,b=ch.split() u,v=myfind(a),myfind(b) add(u,v) print n def bfs(s): mx,ans,ct =0,0,1 vis = [-1] * n cnt = [0] * n chk = [] Q = [s] vis[s] = 0 while len(Q) : u = Q.pop() for v in G[u]: if vis[v] == -1: ct += 1 vis[v] = vis[u] + 1 if vis[v] == 1: Q.append(v) else: chk.append(v) cnt[v] += 1 if len(chk) == 0: return n - ct; for u in chk: if cnt[u] > mx: mx = cnt[u] ans = 1 elif cnt[u]==mx: ans += 1 return ans for c in mp: print c,bfs(mp[c])
1353339000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["aaa\nagaa\nbnbbabb\naapp"]
b86c1533fdfe68fd4dea2bf99cd9e111
null
You are given a string $$$s$$$ of lowercase Latin letters. The following operation can be used: select one character (from 'a' to 'z') that occurs at least once in the string. And replace all such characters in the string with the previous one in alphabetical order on the loop. For example, replace all 'c' with 'b' or replace all 'a' with 'z'. And you are given the integer $$$k$$$ — the maximum number of operations that can be performed. Find the minimum lexicographically possible string that can be obtained by performing no more than $$$k$$$ operations.The string $$$a=a_1a_2 \dots a_n$$$ is lexicographically smaller than the string $$$b = b_1b_2 \dots b_n$$$ if there exists an index $$$k$$$ ($$$1 \le k \le n$$$) such that $$$a_1=b_1$$$, $$$a_2=b_2$$$, ..., $$$a_{k-1}=b_{k-1}$$$, but $$$a_k &lt; b_k$$$.
For each test case, output the lexicographically minimal string that can be obtained from the string $$$s$$$ by performing no more than $$$k$$$ operations.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. This is followed by descriptions of the 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 size of the string $$$s$$$ and the maximum number of operations that can be performed on the string $$$s$$$. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,500
train_092.jsonl
5f605c971553dc9ad4fc45d15edaa9d3
256 megabytes
["4\n\n3 2\n\ncba\n\n4 5\n\nfgde\n\n7 5\n\ngndcafb\n\n4 19\n\nekyv"]
PASSED
d = {chr(96+i):96+i for i in range(1,27)} for _ in range(int(input())): n,k = map(int,input().split()) s = input() l = [0 for i in range(n)] m1,m2,m3 = 'a','a','a' q = "" if k>=25: print('a'*n) continue for i in range(n): x = d[s[i]] if k == 0: if x <= d[m1]: l[i] = 'a' elif x <= d[m2]: l[i] = min(s[i],m3) else: l[i] = s[i] else: if s[i] <= m1: l[i] = 'a' elif x-d[m1]>k: m2 = s[i] m3 = chr(x-k) l[i] = m3 k = 0 else : k -= (x-d[m1]) m1 = s[i] l[i] = 'a' q = ''.join(l) print(q)
1651761300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["00\n01\n10\n11", "10", "01\n11"]
f03f1613292cacc36abbd3a3a25cbf86
NoteIn the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end.
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
standard output
standard input
Python 2
Python
1,900
train_016.jsonl
0d95de503c9538f8dde86f13cb9eef30
256 megabytes
["????", "1010", "1?1"]
PASSED
a=raw_input() O,I,Q=[a.count(i)for i in"01?"] Z=I-O if Q>Z:print"00" if-Q<=Z<2+Q: if"?">a[-1]:print"10"[int(a[-1])]+a[-1] else: if Z<Q:print"01" if~Q<1-Z<Q:print 10 if Z+Q>1:print 11
1323443100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["173\n171\n75\n3298918744"]
ce2b12f1d7c0388c39fee52f5410b94b
NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0&lt;x_1&lt;x_2&lt;\ldots&lt;x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
For each test case, output a single integer  — the minimum cost to conquer all kingdoms.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 &lt; x_2 &lt; \ldots &lt; x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,500
train_110.jsonl
fdd98238a04bce23bb9cd0686c56485b
256 megabytes
["4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030"]
PASSED
import math from sys import stdin, stdout from collections import deque def do_it(a,b,kingdoms,previous,position,states): if len(kingdoms) == 0: return 0 current = kingdoms[0] if position in states: return states[position] gap = current-position prev_gap = current-previous positin_gap = previous-position if(a*(previous-position)<b*(previous-position)*len(kingdoms)): return a*(previous-position) + b*prev_gap + do_it(a,b,kingdoms[1:],current,previous,states) else: return b*gap + do_it(a,b,kingdoms[1:],current,position,states) if __name__ == '__main__': T = int(stdin.readline().strip()) for t in range(0,T): n,a,b = [int(x) for x in stdin.readline().strip().split(" ")] kingdoms = [int(x) for x in stdin.readline().strip().split(" ")] previous = 0 position = 0 res = 0 count = 0 for current in kingdoms: gap = current - position prev_gap = current - previous positin_gap = previous - position if (a * (previous - position) < b * (previous - position) * (len(kingdoms)-count)): res += a * (previous - position) + b * prev_gap position = previous previous = current else: res += b * gap previous = current count += 1 stdout.write(str(res) + "\n")
1650206100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n011\n101\n110", "5\n01111\n10111\n11011\n11101\n11110"]
d3f4c7fedd6148c28d8780142b6594f4
null
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
standard output
standard input
Python 3
Python
1,600
train_006.jsonl
8a725ebcd4bca73dd0d0ae21128a9652
256 megabytes
["1", "10"]
PASSED
n, k = 0, int(input()) p = [['0'] * 100 for i in range(100)] while k: for i in range(n): if i > k: break p[n][i] = p[i][n] = '1' k -= i n += 1 print(n) for i in range(n): print(''.join(p[i][:n]))
1349969400
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO\nYES\nNO"]
5139d222fbbfa70d50e990f5d6c92726
NoteIn the first test case of the example, the array $$$a$$$ has a subsequence $$$[1, 2, 1]$$$ which is a palindrome.In the second test case of the example, the array $$$a$$$ has two subsequences of length $$$3$$$ which are palindromes: $$$[2, 3, 2]$$$ and $$$[2, 2, 2]$$$.In the third test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.In the fourth test case of the example, the array $$$a$$$ has one subsequence of length $$$4$$$ which is a palindrome: $$$[1, 2, 2, 1]$$$ (and has two subsequences of length $$$3$$$ which are palindromes: both are $$$[1, 2, 1]$$$).In the fifth test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.
You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to determine if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome.Recall that an array $$$b$$$ is called a subsequence of the array $$$a$$$ if $$$b$$$ can be obtained by removing some (possibly, zero) elements from $$$a$$$ (not necessarily consecutive) without changing the order of remaining elements. For example, $$$[2]$$$, $$$[1, 2, 1, 3]$$$ and $$$[2, 3]$$$ are subsequences of $$$[1, 2, 1, 3]$$$, but $$$[1, 1, 2]$$$ and $$$[4]$$$ are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $$$a$$$ of length $$$n$$$ is the palindrome if $$$a_i = a_{n - i - 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n$$$. For example, arrays $$$[1234]$$$, $$$[1, 2, 1]$$$, $$$[1, 3, 2, 2, 3, 1]$$$ and $$$[10, 100, 10]$$$ are palindromes, but arrays $$$[1, 2]$$$ and $$$[1, 2, 3, 1]$$$ are not.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer — "YES" (without quotes) if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome and "NO" otherwise.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 5000$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).
standard output
standard input
Python 3
Python
1,100
train_012.jsonl
d7c0d22e92c06ee128f29ff7cf8df17d
256 megabytes
["5\n3\n1 2 1\n5\n1 2 2 3 2\n3\n1 1 2\n4\n1 2 2 1\n10\n1 1 2 2 3 3 4 4 5 5"]
PASSED
for test in range(int(input())): n=int(input()) l=list(map(int,input().split())) l.append(10000000009) c=0 for i in range(n-2): if l[i] in l[i+2:]: print("YES") c=1 break if(c==0): print("NO")
1584018300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["14", "-3"]
b5b13cb304844a8bbd07e247150719f3
NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value  - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) =  - 8, Gena's score is ( - 8) + 3 =  - 5, i.e. the score difference will be  - 3.
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right.
standard output
standard input
Python 3
Python
2,200
train_012.jsonl
8647b6c06752750d4a11959931905a1d
256 megabytes
["3\n2 4 8", "4\n1 -7 -2 3"]
PASSED
n = int(input()) raw = input().split() d = [] prev = 0 for i in range(n): di = int(raw[i]) di += prev d.append(di) prev = di i = n - 2 cur = d[n - 1] while i > 0: cur = max(cur, d[i] - cur) i -= 1 print(cur)
1476611100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1", "2", "-1"]
7d5ecacc037c9b0e6de2e86b20638674
null
Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.
Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.
The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i &lt; i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.
standard output
standard input
Python 3
Python
1,600
train_014.jsonl
dc867f40a1f0438d8891b6f1b53be219
256 megabytes
["5\n1 1 1 1\n1 -1 -1 -1 -1", "5\n1 2 3 1\n1 -1 2 -1 -1", "3\n1 2\n2 -1 1"]
PASSED
n = int(input().strip()) p = [0 for i in range(n)] p[0] = -1 index = 1 for i in input().strip().split(): p[index] = int(i) - 1 index += 1 min_ = [100000000000 for i in range(n)] s = [] for i in input().strip().split(): val = int(i) s.append(val) for i in range(1,n): if s[i] >= 0 and s[p[i]] < 0: min_[p[i]] = min(min_[p[i]],s[i]) for i in range(1,n): if s[i] < 0: got = min_[i] if got == 100000000000: got = s[p[i]] s[i] = got res = s[0] impossible = False for i in range(1,n): if s[i] < s[p[i]]: impossible = True break res += s[i] - s[p[i]] if impossible: print(-1) else: print(res)
1546706100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["ayd", "-1"]
8ba3a7f7cb955478481c74cd4a4eed14
null
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print  - 1.
Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.
The first line contains two integers n and t (1 ≤ n ≤ 105, 0 ≤ t ≤ n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.
standard output
standard input
PyPy 2
Python
1,700
train_005.jsonl
80891314260344aad99f2503b53dba69
256 megabytes
["3 2\nabc\nxyc", "1 0\nc\nb"]
PASSED
def main(): n, t = map(int, raw_input().split()) s1 = raw_input().strip() s2 = raw_input().strip() same_count = 0 for a, b in zip(s1, s2): if a == b: same_count += 1 should_same_count = n - t manuel_same = should_same_count - same_count buf = [] if manuel_same <= 0: for a, b in zip(s1, s2): if a != b: if 'a' not in (a, b): buf.append('a') elif 'b' not in (a, b): buf.append('b') else: buf.append('c') else: if manuel_same < 0: manuel_same += 1 if 'a' == a: buf.append('b') else: buf.append('a') else: buf.append(a) print ''.join(buf) elif manuel_same * 2 <= n - same_count: manuel_same *= 2 for a, b in zip(s1, s2): if a != b: if manuel_same > 0: if manuel_same & 1 == 1: buf.append(b) else: buf.append(a) manuel_same -= 1 else: if 'a' not in (a, b): buf.append('a') elif 'b' not in (a, b): buf.append('b') else: buf.append('c') else: buf.append(a) print ''.join(buf) else: print -1 if __name__ == "__main__": main()
1444149000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n1 2 1", "3\n1 2 0\n1 3 1\n2 3 0", "3\n2 3 0\n1 5 0\n6 8 1"]
a7d3548c4bc356b4bcd40fca7fe839b2
NoteIn the first test the only path is 1 - 2In the second test the only shortest path is 1 - 3 - 4In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).Can you help Walter complete his task and gain the gang's trust?
In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≤ x, y ≤ n, ), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any.
The first line of input contains two integers n, m (2 ≤ n ≤ 105, ), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≤ x, y ≤ n, ) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not.
standard output
standard input
Python 3
Python
2,100
train_023.jsonl
1d4c1bcf74cfa6c5c026cb9f91fa1522
256 megabytes
["2 1\n1 2 0", "4 4\n1 2 1\n1 3 0\n2 3 1\n3 4 1", "8 9\n1 2 0\n8 3 0\n2 3 1\n1 4 1\n8 7 0\n1 5 1\n4 6 1\n5 7 0\n6 8 0"]
PASSED
from sys import * from collections import * s = stdin.read().split() d = list(map(int, s)) n, m = d[:2] g = [[] for i in range(n + 1)] for j in range(m): i = 3 * j + 2 g[d[i]].append((d[i + 1], d[i + 2], j)) g[d[i + 1]].append((d[i], d[i + 2], j)) u, v = [-1] * n + [0], [1e9] * n + [0] x, y = [0] * (n + 1), [0] * (n + 1) q = deque([n]) while q: a = q.popleft() for b, k, i in g[a]: if v[b] == 1e9: q.append(b) if v[b] > v[a] and u[b] < u[a] + k: v[b] = v[a] + 1 u[b] = u[a] + k x[b], y[b] = a, i a, t = 1, [0] * m while a != n: t[y[a]], a = 1, x[a] l = [] for j in range(m): i = 3 * j + 2 if d[i + 2] != t[j]: l.append(' '.join([s[i], s[i + 1], str(t[j])])) print(len(l)) print('\n'.join(l))
1422028800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["18\n4\n6"]
3a3fbb61c7e1ccda69cd6d186da653ae
null
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
Print $$$t$$$ lines, the answers for each test case.
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
standard output
standard input
PyPy 3
Python
null
train_003.jsonl
d56b7c765c2d6e85618ece820e8c1eed
256 megabytes
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
PASSED
t=int(input()) for i in range(t): n,m,r,c=map(int,input().split()) a1=1 a2=n b1=1 b2=m c1=abs(a1-r)+abs(b1-c) c2=abs(a1-r)+abs(b2-c) c3=abs(a2-r)+abs(b1-c) c4=abs(a2-r)+abs(b2-c) print(max(c1,max(c2,max(c3,c4))))
1606633500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1.0 1.0 1.0", "3.0 0.0 0.0"]
0a9cabb857949e818453ffe411f08f95
null
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1.
Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) =  - ∞.
The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists.
standard output
standard input
Python 3
Python
1,800
train_036.jsonl
f3f0e9e844b77679a5bd5a640dbaffd9
256 megabytes
["3\n1 1 1", "3\n2 0 0"]
PASSED
a=int(input()) b=list(map(int,input().split())) if sum(b)==0:print(' '.join([str(a/3)]*3)) else:print(' '.join(map(str,map(lambda x:a*x/sum(b),b))))
1336145400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n3\n5\n11\n17\n23\n29\n59\n89\n0"]
12157ec4a71f0763a898172b38ff1ef2
null
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers $$$d, m$$$, find the number of arrays $$$a$$$, satisfying the following constraints: The length of $$$a$$$ is $$$n$$$, $$$n \ge 1$$$ $$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_n \le d$$$ Define an array $$$b$$$ of length $$$n$$$ as follows: $$$b_1 = a_1$$$, $$$\forall i &gt; 1, b_i = b_{i - 1} \oplus a_i$$$, where $$$\oplus$$$ is the bitwise exclusive-or (xor). After constructing an array $$$b$$$, the constraint $$$b_1 &lt; b_2 &lt; \dots &lt; b_{n - 1} &lt; b_n$$$ should hold. Since the number of possible arrays may be too large, you need to find the answer modulo $$$m$$$.
For each test case, print the number of arrays $$$a$$$, satisfying all given constrains, modulo $$$m$$$.
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) denoting the number of test cases in the input. Each of the next $$$t$$$ lines contains two integers $$$d, m$$$ ($$$1 \leq d, m \leq 10^9$$$). Note that $$$m$$$ is not necessary the prime!
standard output
standard input
Python 3
Python
1,700
train_022.jsonl
9bf265a24bdd6428d87b6fa7690216d5
256 megabytes
["10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1"]
PASSED
t=int(input()) for q in range(t): n,m=map(int,input().split()) st=1 ans=1 while st<=n: ans*=min(st*2-st+1,n-st+2) st*=2 print((ans-1)%m)
1585924500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO\nYES\nYES\nNO"]
ccb5369bc4175ba071969571ceb17227
NoteIn the first test case, the number $$$1$$$ is already on the board.In the second test case, Nezzar could perform the following operations to write down $$$k=0$$$ on the board: Select $$$x=3$$$ and $$$y=2$$$ and write down $$$4$$$ on the board. Select $$$x=4$$$ and $$$y=7$$$ and write down $$$1$$$ on the board. Select $$$x=1$$$ and $$$y=2$$$ and write down $$$0$$$ on the board. In the third test case, it is impossible to have the number $$$k = -1$$$ on the board.
$$$n$$$ distinct integers $$$x_1,x_2,\ldots,x_n$$$ are written on the board. Nezzar can perform the following operation multiple times. Select two integers $$$x,y$$$ (not necessarily distinct) on the board, and write down $$$2x-y$$$. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite number $$$k$$$ on the board after applying above operation multiple times.
For each test case, print "YES" on a single line if it is possible to have $$$k$$$ on the board. Otherwise, print "NO". You can print each letter in any case (upper or lower).
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first line of each test case contains two integers $$$n,k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$-10^{18} \le k \le 10^{18}$$$). The second line of each test case contains $$$n$$$ distinct integers $$$x_1,x_2,\ldots,x_n$$$ ($$$-10^{18} \le x_i \le 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,800
train_088.jsonl
e66a0f3373f97d8b5d33521daeb3c468
512 megabytes
["6\n2 1\n1 2\n3 0\n2 3 7\n2 -1\n31415926 27182818\n2 1000000000000000000\n1 1000000000000000000\n2 -1000000000000000000\n-1000000000000000000 123\n6 80\n-5 -20 13 -14 -2 -11"]
PASSED
import math for t in range(int(input())): n, k = map(int,input().split()) a = list(map(int,input().split())) ans = 0 for i in range(1, n): ans = math.gcd(ans, a[i]-a[i - 1]) if (k-a[0])%ans==0: print ("YES") else: print ("NO")
1611844500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["3", "6", "3"]
d02e8f3499c4eca03e0ae9c23f80dc95
NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left".
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c &lt; ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c &gt; 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).
Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).
The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1).
output.txt
input.txt
Python 3
Python
1,600
train_020.jsonl
a01148c00811822eb4c96527236a3705
256 megabytes
["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"]
PASSED
from collections import deque def read(line): return [int(c) for c in line.split()] def solve(n, lines, r1, c1, r2, c2): queue = deque([(r1, c1, 0)]) visited = {} while queue: r, c, cost = queue.pop() if (r, c) not in visited: visited[(r, c)] = cost else: if cost < visited[(r, c)]: visited[(r, c)] = cost else: continue # left or right to the target column if c2 <= lines[r - 1] + 1: queue.appendleft((r, c2, cost + abs(c - c2))) # right to last column last_pos = lines[r - 1] + 1 if c < last_pos: queue.appendleft((r, last_pos, cost + abs(c - last_pos))) # up if r - 1 >= 1: last_pos_prev = lines[r - 2] + 1 if last_pos_prev >= c: queue.appendleft((r - 1, c, cost + 1)) else: queue.appendleft((r - 1, last_pos_prev, cost + 1)) # down if r + 1 <= n: last_pos_next = lines[r] + 1 if last_pos_next >= c: queue.appendleft((r + 1, c, cost + 1)) else: queue.appendleft((r + 1, last_pos_next, cost + 1)) return visited[(r2, c2)] def main(): with open('input.txt') as f: test = f.readlines() n, = read(test[0]) lines = read(test[1]) r1, c1, r2, c2 = read(test[2]) ans = solve(n, lines, r1, c1, r2, c2) with open('output.txt', 'w') as f: f.write(str(ans)) if __name__ == "__main__": main()
1354960800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2", "0", "3"]
194bc63b192a4e24220b36984901fb3b
NoteIn the first sample case, we can transform $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4$$$ in two steps. Note that the sequence $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4$$$ also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need $$$0$$$ swaps.
Allen is hosting a formal dinner party. $$$2n$$$ people come to the event in $$$n$$$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $$$2n$$$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.
Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of pairs of people. The second line contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$. For each $$$i$$$ with $$$1 \le i \le n$$$, $$$i$$$ appears exactly twice. If $$$a_j = a_k = i$$$, that means that the $$$j$$$-th and $$$k$$$-th people in the line form a couple.
standard output
standard input
Python 3
Python
1,400
train_034.jsonl
a63e5fbdd02d3f10b39d697f9627ddc0
256 megabytes
["4\n1 1 2 3 3 2 4 4", "3\n1 1 2 2 3 3", "3\n3 1 2 3 1 2"]
PASSED
l = int(input()) a = list(map(int,input().split())) count = 0 i = 0 n = 2*l while (i<n-2): if (a[i]==a[i+1]): i += 2 continue j = i+2 while (j<n and a[j]!=a[i]): j += 1 while (j>i+1): count += 1 a[j-1],a[j] = a[j],a[j-1] j -= 1 i += 2 print(count)
1529858100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n2 3", "3\n2 2 2"]
98fd00d3c83d4b3f0511d8afa6fdb27b
null
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
standard output
standard input
Python 2
Python
800
train_004.jsonl
494cefa8733cf0fcae59d51319820907
256 megabytes
["5", "6"]
PASSED
n = int(input()) print n >> 1 while n > 0: if n % 2 > 0: print 3, n -= 3 else: print 2, n -= 2
1482165300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["17\n18\n1\n1\n39\n0\n2"]
84c88932e107e1d1f80b44aec88134e4
NoteIn the first test case, the words can be written as $$$x_1 = 10010_2$$$, $$$x_2 = 01001_2$$$ and $$$x_3 = 10101_2$$$ in binary. Let $$$y = 10001_2$$$. Then, $$$d(x_1, y) = 2$$$ (the difference is in the fourth and the fifth positions), $$$d(x_2, y) = 2$$$ (the difference is in the first and the second positions), $$$d(x_3, y) = 1$$$ (the difference is in the third position). So, the closeness is $$$2 + 2 + 1 = 5$$$. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to $$$18$$$ ($$$10010_2$$$ in binary), so the initial form is also $$$18$$$. It's easy to see that closeness is equal to zero in this case.
Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $$$\ell$$$ letters long. So, the scientists decided to write each word of this language as an integer from $$$0$$$ to $$$2^{\ell} - 1$$$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $$$1001_2$$$ and $$$1100_2$$$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $$$x$$$ and $$$y$$$ as $$$d(x, y)$$$.Let the word have $$$n$$$ forms, the $$$i$$$-th of which is described with an integer $$$x_i$$$. All the $$$x_i$$$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $$$y$$$. Then, closeness of the word $$$y$$$ is equal to the sum of distances to each of the word forms, i. e. the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$.The initial form is the word $$$y$$$ with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the $$$n$$$ given forms.
For each test, print a single integer, the initial form of the word, i. e. such $$$y$$$ ($$$0 \le y \le 2^\ell - 1$$$) that the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$ is minimal possible. Note that $$$y$$$ can differ from all the integers $$$x_i$$$. If there are multiple ways to restore the initial form, print any.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains two integers $$$n$$$ and $$$\ell$$$ ($$$1 \le n \le 100$$$, $$$1 \le \ell \le 30$$$) — the amount of word forms, and the number of letters in one word. The second line contains $$$n$$$ integers $$$x_i$$$ ($$$0 \le x_i \le 2^\ell - 1$$$) — word forms. The integers are not necessarily different.
standard output
standard input
Python 3
Python
800
train_085.jsonl
ce67d53f5517adb49754b03cd2d5de98
256 megabytes
["7\n3 5\n18 9 21\n3 5\n18 18 18\n1 1\n1\n5 30\n1 2 3 4 5\n6 10\n99 35 85 46 78 55\n2 1\n0 1\n8 8\n5 16 42 15 83 65 78 42"]
PASSED
for _ in range(int(input())): n, l = list(map(int, input().split())) arr = list(map(int, input().split())) ans = 0 for i in range(l): cnt = 0 for el in arr: if el & (1 << i): cnt += 1 if cnt > n - cnt: ans += 1 << i print(ans)
1641989100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3\n1 2\n4 2\n2 3"]
d93a0574497b60bb77fb1c1dfe95090f
NoteThis is one possible solution of the example: These are examples of wrong solutions: The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads. Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3.
A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that a road should be constructed between cities ai and bi. If there are several solutions, you may print any of them.
The first line consists of two integers n and m . Then m lines follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n. It is guaranteed that every pair of cities will appear at most once in the input.
standard output
standard input
Python 3
Python
1,300
train_003.jsonl
1ff475f43c832f48a89f372b6022995a
256 megabytes
["4 1\n1 3"]
PASSED
#B. Road Construction n,m = map(int,input().split()) edges = [0]*(n+1) for _ in range(m): x,y = map(int,input().split()) edges[x] = 1 edges[y] = 1 for i in range(1,n+1): if edges[i] == 0: break print(n-1) for j in range(1,n+1): if i!=j: print(i,j)
1374327000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["0 1 2 3 \n1 2 3 \n2 3 4 5 6 7 \n1 1 1 1 \n2 \n0 0 0 0 0 0", "2 2 3 1 \n0 0 0 0 \n2 2 0 \n0 0 1 0 1"]
8feb34d083d9b50c44c469e1254a885b
null
You are given a string $$$s$$$, consisting of lowercase Latin letters.You are asked $$$q$$$ queries about it: given another string $$$t$$$, consisting of lowercase Latin letters, perform the following steps: concatenate $$$s$$$ and $$$t$$$; calculate the prefix function of the resulting string $$$s+t$$$; print the values of the prefix function on positions $$$|s|+1, |s|+2, \dots, |s|+|t|$$$ ($$$|s|$$$ and $$$|t|$$$ denote the lengths of strings $$$s$$$ and $$$t$$$, respectively); revert the string back to $$$s$$$. The prefix function of a string $$$a$$$ is a sequence $$$p_1, p_2, \dots, p_{|a|}$$$, where $$$p_i$$$ is the maximum value of $$$k$$$ such that $$$k &lt; i$$$ and $$$a[1..k]=a[i-k+1..i]$$$ ($$$a[l..r]$$$ denotes a contiguous substring of a string $$$a$$$ from a position $$$l$$$ to a position $$$r$$$, inclusive). In other words, it's the longest proper prefix of the string $$$a[1..i]$$$ that is equal to its suffix of the same length.
For each query, print the values of the prefix function of a string $$$s+t$$$ on positions $$$|s|+1, |s|+2, \dots, |s|+|t|$$$.
The first line contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 10^6$$$), consisting of lowercase Latin letters. The second line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contains a query: a non-empty string $$$t$$$ ($$$1 \le |t| \le 10$$$), consisting of lowercase Latin letters.
standard output
standard input
PyPy 3-64
Python
2,200
train_090.jsonl
d05aebd364a36ff6e40dd8c56422924d
256 megabytes
["aba\n6\ncaba\naba\nbababa\naaaa\nb\nforces", "aacba\n4\naaca\ncbbb\naab\nccaca"]
PASSED
def get_next(j, k, nxt, p): while p[j] != '$': if k == -1 or p[j] == p[k]: j += 1 k += 1 if p[j] == p[k]: nxt[j] = nxt[k] else: nxt[j] = k else: k = nxt[k] return j, k, nxt def solve(): s = input().strip() len_s = len(s) ns = [ch for ch in s] for i in range(11): ns.append('$') # print(ns) j, k, nxt = get_next(0, -1, [-1 for i in range(len(ns))], ns) q = int(input().strip()) for _ in range(q): t = input().strip() ans = [] for i in range(10): ns[i + len_s] = '$' for i in range(len(t)): ns[i + len_s] = t[i] # print(ns) nj, nk, n_nxt = get_next(j, k, nxt, ns) # print(n_nxt) ans.append(n_nxt[len_s + i + 1]) print(' '.join(map(str, ans))) if __name__ == '__main__': # t = int(input().strip()) # for _ in range(t): solve()
1661610900
[ "strings", "trees" ]
[ 0, 0, 0, 0, 0, 0, 1, 1 ]
1 second
["Yes", "No"]
6478d3dda3cbbe146eb03627dd5cc75e
NoteIn the first example, we can perform the following synchronizations ($$$1$$$-indexed): First, synchronize the third stone $$$[7, 2, \mathbf{4}, 12] \rightarrow [7, 2, \mathbf{10}, 12]$$$. Then synchronize the second stone: $$$[7, \mathbf{2}, 10, 12] \rightarrow [7, \mathbf{15}, 10, 12]$$$. In the second example, any operation with the second stone will not change its charge.
Grigory has $$$n$$$ magic stones, conveniently numbered from $$$1$$$ to $$$n$$$. The charge of the $$$i$$$-th stone is equal to $$$c_i$$$.Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index $$$i$$$, where $$$2 \le i \le n - 1$$$), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge $$$c_i$$$ changes to $$$c_i' = c_{i + 1} + c_{i - 1} - c_i$$$.Andrew, Grigory's friend, also has $$$n$$$ stones with charges $$$t_i$$$. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes $$$c_i$$$ into $$$t_i$$$ for all $$$i$$$?
If there exists a (possibly empty) sequence of synchronization operations, which changes all charges to the required ones, print "Yes". Otherwise, print "No".
The first line contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of magic stones. The second line contains integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \le c_i \le 2 \cdot 10^9$$$) — the charges of Grigory's stones. The second line contains integers $$$t_1, t_2, \ldots, t_n$$$ ($$$0 \le t_i \le 2 \cdot 10^9$$$) — the charges of Andrew's stones.
standard output
standard input
Python 3
Python
2,200
train_008.jsonl
58de502b090b83212bbc336bb49dcb03
256 megabytes
["4\n7 2 4 12\n7 15 10 12", "3\n4 4 4\n1 2 3"]
PASSED
n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) x = [] y = [] for i in range(n-1): x.append(a[i+1]-a[i]) for i in range(n-1): y.append(b[i+1]-b[i]) x.sort() y.sort() # print(x,y) if x == y and a[0] == b[0] and a[n-1] == b[n-1]: print("Yes") else: print("No")
1549546500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["0 1 1 1 1 0 1 1"]
2dcc82e6abc733a9c4567742294184dc
null
You are given a tree consisting of $$$n$$$ vertices. Some of the vertices (at least two) are black, all the other vertices are white.You place a chip on one of the vertices of the tree, and then perform the following operations: let the current vertex where the chip is located is $$$x$$$. You choose a black vertex $$$y$$$, and then move the chip along the first edge on the simple path from $$$x$$$ to $$$y$$$. You are not allowed to choose the same black vertex $$$y$$$ in two operations in a row (i. e., for every two consecutive operations, the chosen black vertex should be different).You end your operations when the chip moves to the black vertex (if it is initially placed in a black vertex, you don't perform the operations at all), or when the number of performed operations exceeds $$$100^{500}$$$.For every vertex $$$i$$$, you have to determine if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex, if the chip is initially placed on the vertex $$$i$$$.
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to $$$1$$$ if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex if it is placed on the vertex $$$i$$$, and $$$0$$$ if no such sequence of operations exists.
The first line contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$0 \le c_i \le 1$$$), where $$$c_i = 0$$$ means that the $$$i$$$-th vertex is white, and $$$c_i = 1$$$ means that the $$$i$$$-th vertex is black. At least two values of $$$c_i$$$ are equal to $$$1$$$. Then $$$n-1$$$ lines follow, each of them contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — the endpoints of some edge. These edges form a tree.
standard output
standard input
PyPy 3-64
Python
2,400
train_087.jsonl
70d88734342c645f3bdcb74bad3c5d5b
512 megabytes
["8\n0 1 0 0 0 0 1 0\n8 6\n2 5\n7 8\n6 5\n4 5\n6 1\n7 3"]
PASSED
from sys import stdin inp = stdin.readline n = int(inp()) bow = [int(x) for x in inp().split()] # tree[nr][color, [connected]] tree = {i+1: [c, set()] for i, c in enumerate(bow)} for i in range(n-1): a, b = map(int, inp().split()) tree[a][1].add(b) tree[b][1].add(a) blacks = [] for i in range(n): if bow[i] == 1: blacks.append(i+1) blacksDone = {c: set() for c in blacks} ans = [0 for i in range(n)] for start in blacks: arr = [[start, set(tree[start][1]).difference(blacksDone[start])]] layer = 0 blackNr = len(blacksDone[start]) branch = set() branch2 = set() blackBranch = False blackLayer = -1 ans[start-1] = 1 for c in arr[0][1]: ans[c-1] = 1 while True: # counter if len(arr[layer][1]) > 0: current = arr[layer][1].pop() arr.append([current, set(tree[current][1])]) arr[-1][1].discard(arr[layer][0]) layer += 1 if layer > blackLayer != -1: branch2.add(current) elif layer > 1: branch.add(current) if tree[current][0] == 1 and current != start: if len(blacksDone[current]) >= 1: blackNr = 2 break if not blackBranch: blackNr += 1 blackBranch = True elif blackLayer > -1: blackNr = 2 break blackLayer = layer-1 blacksDone[current].add(arr[layer-1][0]) arr[layer-1][1] = set(tree[arr[layer-1][0]][1]) arr[layer-1][1].discard(arr[layer-2][0]) arr[layer-1][1].discard(current) arr.pop() ans[arr[layer-1][0]-1] = 1 layer -= 1 else: layer -= 1 if layer == 1: if not blackBranch: for c in branch: ans[c-1] = 1 else: blackBranch = False branch = set() elif layer == blackLayer: for c in branch2: ans[c - 1] = 1 branch2 = set() if layer < blackLayer: blackLayer = -1 if layer == -1: break arr.pop() if blackNr > 1: break if blackNr > 1: break if blackNr > 1: ans = [1]*n print(*ans)
1642343700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["1\n2 3\n2\n2 3\n5 8\n-1\n1\n1 5"]
1d72b5ab8b6af0b7a02246ecd5e87953
NoteIn the first example, the cuteness of $$$\texttt{0011}$$$ is the same as the cuteness of $$$\texttt{01}$$$.In the second example, the cuteness of $$$\texttt{11000011}$$$ is $$$\frac{1}{2}$$$ and there is no subsegment of size $$$6$$$ with the same cuteness. So we must use $$$2$$$ disjoint subsegments $$$\texttt{10}$$$ and $$$\texttt{0011}$$$.In the third example, there are $$$8$$$ ways to split the string such that $$$\sum\limits_{i=1}^k (r_i - l_i + 1) = 3$$$ but none of them has the same cuteness as $$$\texttt{0101}$$$.In the last example, we don't have to split the string.
The cuteness of a binary string is the number of $$$\texttt{1}$$$s divided by the length of the string. For example, the cuteness of $$$\texttt{01101}$$$ is $$$\frac{3}{5}$$$.Juju has a binary string $$$s$$$ of length $$$n$$$. She wants to choose some non-intersecting subsegments of $$$s$$$ such that their concatenation has length $$$m$$$ and it has the same cuteness as the string $$$s$$$. More specifically, she wants to find two arrays $$$l$$$ and $$$r$$$ of equal length $$$k$$$ such that $$$1 \leq l_1 \leq r_1 &lt; l_2 \leq r_2 &lt; \ldots &lt; l_k \leq r_k \leq n$$$, and also: $$$\sum\limits_{i=1}^k (r_i - l_i + 1) = m$$$; The cuteness of $$$s[l_1,r_1]+s[l_2,r_2]+\ldots+s[l_k,r_k]$$$ is equal to the cuteness of $$$s$$$, where $$$s[x, y]$$$ denotes the subsegment $$$s_x s_{x+1} \ldots s_y$$$, and $$$+$$$ denotes string concatenation. Juju does not like splitting the string into many parts, so she also wants to minimize the value of $$$k$$$. Find the minimum value of $$$k$$$ such that there exist $$$l$$$ and $$$r$$$ that satisfy the constraints above or determine that it is impossible to find such $$$l$$$ and $$$r$$$ for any $$$k$$$.
For each test case, if there is no valid pair of $$$l$$$ and $$$r$$$, print $$$-1$$$. Otherwise, print $$$k + 1$$$ lines. In the first line, print a number $$$k$$$ ($$$1 \leq k \leq m$$$) — the minimum number of subsegments required. Then print $$$k$$$ lines, the $$$i$$$-th should contain $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$) — the range of the $$$i$$$-th subsegment. Note that you should output the subsegments such that the inequality $$$l_1 \leq r_1 &lt; l_2 \leq r_2 &lt; \ldots &lt; l_k \leq r_k$$$ is true.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq m \leq n \leq 2 \cdot 10^5$$$). The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. 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
2,700
train_095.jsonl
70d8a5de9e0a484d906fb2ee97ee25a1
256 megabytes
["4\n\n4 2\n\n0011\n\n8 6\n\n11000011\n\n4 3\n\n0101\n\n5 5\n\n11111"]
PASSED
import sys from calendar import c import math t = int(input()) for _ in range(0, t): n,m = [int(i) for i in input().split()] s = input() p = [0 for i in range(n+1)] for i in range(0, n): p[i + 1] = p[i] + (s[i] == '1') k = p[n] c = k * m if c % n != 0: print("-1") continue c /= n sol =- 1 for i in range(0, n-m+1): if p[i + m] - p[i] == c: sol = i break if sol != -1: print(1) print('{} {}'.format(sol + 1,sol + m)) continue for i in range(0, m+1): if p[i + (n-m)] - p[i] == k-c: sol = i if sol != -1: print(2) print('{} {}'.format(1,sol)) print('{} {}'.format(sol+1+n-m,n))
1648391700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2.5 seconds
["1 3 2", "-1"]
725a65c7eb72ad54af224895b20a163d
null
A tournament is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes u and v (u ≠ v) exists either an edge going from u to v, or an edge from v to u.You are given a tournament consisting of n vertexes. Your task is to find there a cycle of length three.
Print three distinct vertexes of the graph a1, a2, a3 (1 ≤ ai ≤ n), such that Aa1, a2 = Aa2, a3 = Aa3, a1 = 1, or "-1", if a cycle whose length equals three does not exist. If there are several solutions, print any of them.
The first line contains an integer n (1 ≤ n ≤ 5000). Next n lines contain the adjacency matrix A of the graph (without spaces). Ai, j = 1 if the graph has an edge going from vertex i to vertex j, otherwise Ai, j = 0. Ai, j stands for the j-th character in the i-th line. It is guaranteed that the given graph is a tournament, that is, Ai, i = 0, Ai, j ≠ Aj, i (1 ≤ i, j ≤ n, i ≠ j).
standard output
standard input
Python 2
Python
2,000
train_074.jsonl
171c3cacecb9e4a715b016df43426671
256 megabytes
["5\n00100\n10000\n01001\n11101\n11000", "5\n01111\n00000\n01000\n01100\n01110"]
PASSED
from sys import stdin, stdout input = stdin.readline import gc gc.disable() def f(): p, q, n = [0], [0], int(input()) input() for i in range(1, n): t = input()[: i] if '0' in t: if '1' in t: for l, j in enumerate(p): if t[j] == '1': for r, j in enumerate(q): if t[j] == '0': if l + r == i: break return str(p[l] + 1) + ' ' + str(q[r] + 1) + ' ' + str(i + 1) break p.insert(l, i) q.insert(i - l, i) else: p.append(i) q = [i] + q else: p = [i] + p q.append(i) return -1 print(f())
1316790000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["4\n2\n1\n0\n2\n0\n0\n0\n17"]
9966bfdc9677a9dd558684a00977cd58
NoteIn the first test case, for each pair of adjacent cosplayers, you can invite two female cosplayers to stand in between them. Then, $$$000 \rightarrow 0110110$$$.In the third test case, you can invite one female cosplayer to stand next to the second cosplayer. Then, $$$010 \rightarrow 0110$$$.
Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot!For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $$$2$$$ cosplayers, the number of males does not exceed the number of females (obviously).Currently, the line has $$$n$$$ cosplayers which can be described by a binary string $$$s$$$. The $$$i$$$-th cosplayer is male if $$$s_i = 0$$$ and female if $$$s_i = 1$$$. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.Marin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?
For each test case, print the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains a positive integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of cosplayers in the initial line. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ — describing the cosplayers already in line. Each character of the string is either 0 describing a male, or 1 describing a female. Note that there is no limit on the sum of $$$n$$$.
standard output
standard input
PyPy 3-64
Python
800
train_095.jsonl
fe14ec67ea19ee56dc216d3461fa5680
256 megabytes
["9\n\n3\n\n000\n\n3\n\n001\n\n3\n\n010\n\n3\n\n011\n\n3\n\n100\n\n3\n\n101\n\n3\n\n110\n\n3\n\n111\n\n19\n\n1010110000100000101"]
PASSED
#https://codeforces.com/blog/entry/71884 import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def incr(): s = input() return(list(s[:len(s)])) def invr(): return(map(int,input().split())) t = inp() for _ in range(t): N = inp() s = insr() ans = 0 op, cl = 0,0 for k in range(len(s)): if s[k] == "0": if k == len(s) - 1: continue #elif k == len(s) - 2: else: if s[k+1] == "1": if k+2 >= len(s) or s[k+2] == "1": continue else: ans += 1 else: ans += 2 print(ans)
1648391700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["-\n+\n+\n-\n-\n+\n-\n+\n+\n+"]
1f5f5ccbdfcbe5cb2d692475f0726bfd
null
Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump k squares diagonally down and to the right. The player who can’t move the piece loses. The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size.
Output t lines that can determine the outcomes of the game on every board. Write «+» if the first player is a winner, and «-» otherwise.
The first input line contains two integers t and k (1 ≤ t ≤ 20, 1 ≤ k ≤ 109). Each of the following t lines contains two numbers n, m — the board’s length and width (1 ≤ n, m ≤ 109).
output.txt
input.txt
Python 2
Python
2,300
train_078.jsonl
da1f71e4fdae8b1e653fe48dffd52a0d
64 megabytes
["10 2\n1 1\n1 2\n2 1\n2 2\n1 3\n2 3\n3 1\n3 2\n3 3\n4 3"]
PASSED
#!/usr/bin/python c = ['-', '+'] infile = open("input.txt") outfile = open("output.txt", 'w') t, k = map(lambda x: int(x), infile.readline().split()) for i in range(t): n, m = map(lambda x: int(x)-1, infile.readline().split()) if n > m: n, m = m, n if k >= 2: r = n % (2*k + 2) if r == k or r == 2*k+1: outfile.write('+\n') elif r <= k-1: outfile.write(c[(m+n)%2]+'\n') else: outfile.write(c[(m+n+1)%2]+'\n') else: if n % 2 == 1: outfile.write('+\n') else: outfile.write(c[(m+n)%2]+'\n')
1287482400
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
3 seconds
["1\n1\n0\n0\n7\n995\n2\n1\n1\n1\n2"]
716965622c7c5fbc78217998d4bfe9ab
null
A positive number $$$x$$$ of length $$$n$$$ in base $$$p$$$ ($$$2 \le p \le 10^9$$$) is written on the blackboard. The number $$$x$$$ is given as a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i &lt; p$$$) — the digits of $$$x$$$ in order from left to right (most significant to least significant).Dmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.In one operation, he can: take any number $$$x$$$ written on the board, increase it by $$$1$$$, and write the new value $$$x + 1$$$ on the board. For example, $$$p=5$$$ and $$$x=234_5$$$. Initially, the board contains the digits $$$2$$$, $$$3$$$ and $$$4$$$; Dmitry increases the number $$$234_5$$$ by $$$1$$$ and writes down the number $$$240_5$$$. On the board there are digits $$$0, 2, 3, 4$$$; Dmitry increases the number $$$240_5$$$ by $$$1$$$ and writes down the number $$$241_5$$$. Now the board contains all the digits from $$$0$$$ to $$$4$$$. Your task is to determine the minimum number of operations required to make all the digits from $$$0$$$ to $$$p-1$$$ appear on the board at least once.
For each test case print a single integer — the minimum number of operations required for Dmitry to get all the digits on the board from $$$0$$$ to $$$p-1$$$. It can be shown that this always requires a finite number of operations.
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^3$$$) — the number of test cases. The descriptions of the input test cases follow. The first line of description of each test case contains two integers $$$n$$$ ($$$1 \le n \le 100$$$) and $$$p$$$ ($$$2 \le p \le 10^9$$$) — the length of the number and the base of the number system. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i &lt; p$$$) — digits of $$$x$$$ in number system with base $$$p$$$ It is guaranteed that the number $$$x$$$ does not contain leading zeros (that is, $$$a_1&gt;0$$$).
standard output
standard input
PyPy 3-64
Python
1,800
train_086.jsonl
c03ea8f8047ec4d6666a90472f09b0e7
256 megabytes
["11\n\n2 3\n\n1 2\n\n4 2\n\n1 1 1 1\n\n6 6\n\n1 2 3 4 5 0\n\n5 2\n\n1 0 1 0 1\n\n3 10\n\n1 2 3\n\n5 1000\n\n4 1 3 2 5\n\n3 5\n\n2 3 4\n\n4 4\n\n3 2 3 0\n\n1 3\n\n2\n\n5 5\n\n1 2 2 2 4\n\n3 4\n\n1 0 1"]
PASSED
from calendar import c import sys readline = sys.stdin.readline t = int(readline()) def good(oadd, arr, p): add = oadd range_ = (-1,-1) max_ = p min_ = -1 digits = set(arr) for i in range(len(arr)): if add == 0: break val = (add%p + arr[i]) add = add//p+val//p newval = val%p digits.add(newval) if val >= p: max_ = min(max_, arr[i]) min_ = max(min_, newval) else: range_ = (arr[i],newval) if add: digits.add(add) i = min_+1 while i < max_: if i == range_[0]: i = range_[1]+1 elif i in digits: i += 1 else: break return i >= max_ for _ in range(t): n, p = map(int, readline().split()) arr = readline().split() arr.reverse() for i in range(len(arr)): arr[i]=int(arr[i]) l = 0 r = p-1 while l < r: mid = (l+r)//2 g = good(mid, arr, p) if g: r = mid else: l = mid+1 print(l)
1668782100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["8\n998"]
80c75a4c163c6b63a614075e094ad489
NoteIn the second test case (with $$$n = 3$$$), if uncle Bogdan had $$$x = 998$$$ then $$$k = 100110011000$$$. Denis (by wiping last $$$n = 3$$$ digits) will obtain $$$r = 100110011$$$.It can be proved that the $$$100110011$$$ is the maximum possible $$$r$$$ Denis can obtain and $$$998$$$ is the minimum $$$x$$$ to obtain it.
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.In the beginning, uncle Bogdan wrote on a board a positive integer $$$x$$$ consisting of $$$n$$$ digits. After that, he wiped out $$$x$$$ and wrote integer $$$k$$$ instead, which was the concatenation of binary representations of digits $$$x$$$ consists of (without leading zeroes). For example, let $$$x = 729$$$, then $$$k = 111101001$$$ (since $$$7 = 111$$$, $$$2 = 10$$$, $$$9 = 1001$$$).After some time, uncle Bogdan understood that he doesn't know what to do with $$$k$$$ and asked Denis to help. Denis decided to wipe last $$$n$$$ digits of $$$k$$$ and named the new number as $$$r$$$.As a result, Denis proposed to find such integer $$$x$$$ of length $$$n$$$ that $$$r$$$ (as number) is maximum possible. If there are multiple valid $$$x$$$ then Denis is interested in the minimum one.All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?Note: in this task, we compare integers ($$$x$$$ or $$$k$$$) as numbers (despite what representations they are written in), so $$$729 &lt; 1999$$$ or $$$111 &lt; 1000$$$.
For each test case, print the minimum integer $$$x$$$ of length $$$n$$$ such that obtained by Denis number $$$r$$$ is maximum possible.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per test case. The one and only line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the integer $$$x$$$ you need to find. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
1,000
train_005.jsonl
55e84ca9d1187dd71ba802557aacadf0
256 megabytes
["2\n1\n3"]
PASSED
t=int(input()) for i in range(t): x=int(input()) ans=8 u=0 an="" n=0 if x<=4: for i in range(u+1,x): ans+=(9)*(10**i) print(ans) else: a="" q=(x-1)//4 a+='9'*(x-q-1) a+='8'*(q+1) print(int(a))
1596119700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3", "-1"]
7225266f663699ff7e16b726cadfe9ee
NoteIn the first sample, heights sequences are following:Xaniar: Abol:
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar. So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become and height of Abol will become where x1, y1, x2 and y2 are some integer numbers and denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.
Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.
The first line of input contains integer m (2 ≤ m ≤ 106). The second line of input contains integers h1 and a1 (0 ≤ h1, a1 &lt; m). The third line of input contains integers x1 and y1 (0 ≤ x1, y1 &lt; m). The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 &lt; m). The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 &lt; m). It is guaranteed that h1 ≠ a1 and h2 ≠ a2.
standard output
standard input
PyPy 3
Python
2,200
train_059.jsonl
9cf794de657bd5b450b9789e621a2030
256 megabytes
["5\n4 2\n1 1\n0 1\n2 3", "1023\n1 2\n1 0\n1 2\n1 1"]
PASSED
import fractions def read_data(): m = int(input()) h1, a1 = map(int, input().split()) x1, y1 = map(int, input().split()) h2, a2 = map(int, input().split()) x2, y2 = map(int, input().split()) return m, h1, a1, x1, y1, h2, a2, x2, y2 def solve(m, h1, a1, x1, y1, h2, a2, x2, y2): t = 0 h1s = [-1] * m h2s = [-1] * m h1s[h1] = 0 h2s[h2] = 0 t1 = -1 t2 = -1 while h1 != a1 or h2 != a2: t += 1 h1 = (x1 * h1 + y1) % m h2 = (x2 * h2 + y2) % m if h1s[h1] >= 0 and t1 == -1: t1 = h1s[h1] s1 = t - t1 if t2 >= 0: break else: h1s[h1] = t if h2s[h2] >= 0 and t2 == -1: t2 = h2s[h2] s2 = t - t2 if t1 >= 0: break else: h2s[h2] = t if h1 == a1 and h2 == a2: return t return retrieve(a1, a2, t1, s1, t2, s2, h1s, h2s) def retrieve(a1, a2, t1, s1, t2, s2, h1s, h2s): u1 = h1s[a1] u2 = h2s[a2] if u1 == -1 or u2 == -1: return -1 if u1 < t1: if guess(h2s, u1, t2, s2, a2): return u1 else: return -1 if u2 < t2: if guess(h1s, u2, t1, s1, a1): return u2 else: return -1 return find_time(u1, s1, u2, s2) def guess(hs, u, t, s, a): if u <= t: return hs[a] == u tt = t + (u - t) % s return hs[a] == tt def find_time(u1, s1, u2, s2): g = fractions.gcd(s1, s2) if abs(u1 - u2) % g: return -1 k1, k2 = extended_euclid(s1, s2, u2-u1, g) b = s2 // g return (k1 % b) * s1 + u1 def egcd(a, b): x, lastx = 0, 1 y, lasty = 1, 0 while b: q = a // b a, b = b, a % b x, lastx = lastx - q * x, x y, lasty = lasty - q * y, y return lastx, lasty def extended_euclid(a, b, c, g): x, y = egcd(a, b) return (c // g) * x, (x // g) * y param = read_data() print(solve(*param))
1432658100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "3", "4"]
d99b8f78eee74d9933c54af625dafd26
NoteIn the second sample, the get a decomposition of number 2, you need any one number out of three to equal 2, and the rest to equal 1.In the third sample, the possible ways of decomposing into ordered multipliers are [7,5], [5,7], [1,35], [35,1].A decomposition of positive integer m into n ordered multipliers is a cortege of positive integers b = {b1, b2, ... bn} such that . Two decompositions b and c are considered different, if there exists index i such that bi ≠ ci.
You are given an integer m as a product of integers a1, a2, ... an . Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers.Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo 1000000007 (109 + 7).
In a single line print a single number k — the number of distinct decompositions of number m into n ordered multipliers modulo 1000000007 (109 + 7).
The first line contains positive integer n (1 ≤ n ≤ 500). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
standard input
Python 3
Python
null
train_020.jsonl
1ea93b049917839dad13cadba9036a53
256 megabytes
["1\n15", "3\n1 1 2", "2\n5 7"]
PASSED
Mod = 1000000007 MAX = 33000 n = int( input() ) A = list( map( int, input().split() ) ) B = [0] * MAX bePrime = [0] * MAX; primNum = [] C = [] fac=[1] for j in range(1, MAX): fac.append( fac[-1] * j % Mod ) def calc( M, N ): return fac[M] * pow( fac[N] * fac[M-N] % Mod, Mod-2,Mod ) % Mod for j in range(2, MAX): if bePrime[j] == 0: primNum.append( j ) i = j while i < MAX: bePrime[i] = 1 i = i + j for x in A: tmp = x for j in primNum: while tmp % j == 0: tmp /= j B[j] += 1 if tmp > 1: C.append( tmp ) ans = 1 for j in range(2,MAX): if B[j] > 0: ans = ans * calc( n + B[j] -1 , n - 1 ) % Mod l = len( C ) for j in range(0, l ): num= 0; for k in range(0, l ): if C[k] == C[j]: num = num + 1 if k > j: num = 0 break if num > 0: ans = ans * calc( n + num -1, n - 1 ) % Mod print( str( ans % Mod ) ) # Made By Mostafa_Khaled
1393428600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1.5 seconds
["0 3 2 2", "0", "1073741823 0"]
891a7bd69187975f61b8c6ef6b6acac3
NoteIn the first sample, these are all the arrays satisfying the statements: $$$[0, 3, 2, 2]$$$, $$$[2, 1, 0, 0]$$$, $$$[2, 1, 0, 2]$$$, $$$[2, 1, 2, 0]$$$, $$$[2, 1, 2, 2]$$$, $$$[2, 3, 0, 0]$$$, $$$[2, 3, 0, 2]$$$, $$$[2, 3, 2, 0]$$$, $$$[2, 3, 2, 2]$$$.
The Narrator has an integer array $$$a$$$ of length $$$n$$$, but he will only tell you the size $$$n$$$ and $$$q$$$ statements, each of them being three integers $$$i, j, x$$$, which means that $$$a_i \mid a_j = x$$$, where $$$|$$$ denotes the bitwise OR operation.Find the lexicographically smallest array $$$a$$$ that satisfies all the statements.An array $$$a$$$ is lexicographically smaller than an array $$$b$$$ of the same length if and only if the following holds: in the first position where $$$a$$$ and $$$b$$$ differ, the array $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.
On a single line print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i &lt; 2^{30}$$$) — array $$$a$$$.
In the first line you are given with two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). In the next $$$q$$$ lines you are given with three integers $$$i$$$, $$$j$$$, and $$$x$$$ ($$$1 \le i, j \le n$$$, $$$0 \le x &lt; 2^{30}$$$) — the statements. It is guaranteed that all $$$q$$$ statements hold for at least one array.
standard output
standard input
PyPy 3-64
Python
1,900
train_082.jsonl
19d850f43229ef9c5b587111f73d4efd
256 megabytes
["4 3\n1 2 3\n1 3 2\n4 1 2", "1 0", "2 1\n1 1 1073741823"]
PASSED
# if you win, you live. you cannot win unless you fighst. from sys import stdin,setrecursionlimit import os import sys from io import BytesIO, IOBase _str = str str = lambda x=b"": x if type(x) is bytes else _str(x).encode() BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") import heapq rd=lambda: map(lambda s: int(s), input().strip().split()) rdone=lambda: map(lambda s: int(s)-1, input().strip().split()) ri=lambda: int(input()) rs=lambda :input().strip() from collections import defaultdict as unsafedict,deque,Counter as unsafecounter from bisect import bisect_left as bl, bisect_right as br from random import randint from math import gcd, floor,log2,factorial,radians,sin,cos random = randint(1, 10 ** 9) mod=998244353 def ceil(a,b): return (a+b-1)//b class mydict: def __init__(self,func): self.random = randint(0,1<<32) self.default=func self.dict={} def __getitem__(self,key): mykey=self.random^key if mykey not in self.dict: self.dict[mykey]=self.default() return self.dict[mykey] def get(self,key,default): mykey=self.random^key if mykey not in self.dict: return default return self.dict[mykey] def __setitem__(self,key,item): mykey=self.random^key self.dict[mykey]=item def getkeys(self): return [self.random^i for i in self.dict] def __str__(self): return f'{[(self.random^i,self.dict[i]) for i in self.dict]}' ''' 6576394 4462850 268435455 4460800 ''' n,m=rd() can1=[[True]*30 for i in range(n+1)] can0=[[True]*30 for i in range(n+1)] store=[[] for i in range(n+1)] st=[[0]*30 for i in range(n+1)] for _ in range(m): i,j,x=rd() if j<i: i,j=j,i if i==j: for bit in range(30): if x&(1<<bit): can0[i][bit]=False else: can1[i][bit]=False continue store[i].append((j,x)) for bit in range(30): if x&(1<<bit) : st[i][bit]=1 st[j][bit]=1 else: can1[i][bit]=False can1[j][bit]=False for i in range(1,n+1): for bit in range(30): if can0[i][bit]==False: continue fl=False need=False for id,val in store[i]: if val&(1<<bit): need=True if val&(1<<bit) and can1[id][bit]==False: fl=True break if fl and need: can0[i][bit]=False elif need: for id,val in store[i]: if val&(1<<bit) : can0[id][bit]=False ans=[] for i in range(1,n+1): pp=0 for bit in range(30): if can0[i][bit]==False: pp|=(1<<bit) ans.append(pp) print(*ans)
1661006100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["6", "1"]
818e5f23028faf732047fc177eeb3851
null
Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.
Print the only integer t — the minimal time required for all ants to be in the root of the tree.
The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree.
standard output
standard input
PyPy 2
Python
2,200
train_050.jsonl
8273dd43e2a35a64f198ac4b45ebff26
256 megabytes
["12\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n3 9\n8 10\n8 11\n8 12", "2\n2 1"]
PASSED
#!/usr/bin/env python3 from __future__ import division, print_function def bfs(node, adj, visited): L = [] visited[node] = True L.append( (node, 1) ) d = [] while L: node, depth = L.pop() is_leaf = True for i in adj[node]: if not visited[i]: is_leaf = False visited[i] = True L.append( (i, depth+1) ) if is_leaf: d.append(depth) d.sort() res = d[0] for i, v in enumerate(d): if i==0: continue res = max(res+1, v) return res def solver(ifs): n = int(ifs.readline()) adj = [ [] for i in range(n) ] for i in range(n-1): x, y = list(map(int, ifs.readline().split())) x, y = x-1, y-1 adj[x].append(y) adj[y].append(x) res = 0 visited = [False, ] * n visited[0] = True for node in adj[0]: if not visited[node]: res = max(res, bfs(node, adj, visited)) print(res) def main(): import sys if sys.version_info.major == 3: from io import StringIO as StreamIO else: from io import BytesIO as StreamIO with StreamIO(sys.stdin.read()) as ifs, StreamIO() as ofs: _stdout = sys.stdout sys.stdout = ofs solver(ifs) sys.stdout = _stdout sys.stdout.write(ofs.getvalue()) return 0 if __name__ == '__main__': main()
1455116400
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["2", "0", "30"]
c1f50da1fbe797e7c9b982583a3b02d5
NoteIn the first example, you have to swap the third and the fourth elements, so the string becomes "aazaa". Then you have to swap the second and the third elements, so the string becomes "azaaa". So, it is possible to reverse the string in two swaps.Since the string in the second example is a palindrome, you don't have to do anything to reverse it.
You are given a string $$$s$$$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.
Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the length of $$$s$$$. The second line contains $$$s$$$ — a string consisting of $$$n$$$ lowercase Latin letters.
standard output
standard input
Python 3
Python
1,900
train_010.jsonl
9fa43384471926cf6aef2ad874648da0
256 megabytes
["5\naaaza", "6\ncbaabc", "9\nicpcsguru"]
PASSED
import sys input = sys.stdin.readline n = int(input()) S = input().strip() LIST = [[] for i in range(26)] for i in range(n): LIST[ord(S[i])-97].append(i) # for i in LIST: # print(i) LEN = n+1 BIT = [0]*(LEN+1) # print(BIT) def update(v, w): while v <= LEN: BIT[v] += w v += (v & (-v)) def getvalue(v): ANS = 0 while v != 0: ANS += BIT[v] v -= (v & (-v)) return ANS ANS = 0 moji = [0]*26 for i in range(n-1, -1, -1): s = ord(S[i])-97 x = LIST[s][moji[s]] ANS += x-getvalue(x+1) moji[s] += 1 # print(x-getvalue(x+1)) # print("*") # print(BIT) update(x+1, 1) # print(moji) # print("/") # print(BIT) # print("#") print(ANS)
1602407100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1\n8\n16\n13\n4", "16\n9\n7\n20"]
3c48123f326fb79ce2e4e17e1e0765f8
NoteAnswers to the queries from examples are on the board in the picture from the problem statement.
You are given a chessboard of size $$$n \times n$$$. It is filled with numbers from $$$1$$$ to $$$n^2$$$ in the following way: the first $$$\lceil \frac{n^2}{2} \rceil$$$ numbers from $$$1$$$ to $$$\lceil \frac{n^2}{2} \rceil$$$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $$$n^2 - \lceil \frac{n^2}{2} \rceil$$$ numbers from $$$\lceil \frac{n^2}{2} \rceil + 1$$$ to $$$n^2$$$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $$$\lceil\frac{x}{y}\rceil$$$ means division $$$x$$$ by $$$y$$$ rounded up.For example, the left board on the following picture is the chessboard which is given for $$$n=4$$$ and the right board is the chessboard which is given for $$$n=5$$$. You are given $$$q$$$ queries. The $$$i$$$-th query is described as a pair $$$x_i, y_i$$$. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$.
For each query from $$$1$$$ to $$$q$$$ print the answer to this query. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Queries are numbered from $$$1$$$ to $$$q$$$ in order of the input.
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le q \le 10^5$$$) — the size of the board and the number of queries. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th line contains two integers $$$x_i, y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — description of the $$$i$$$-th query.
standard output
standard input
Python 3
Python
1,200
train_024.jsonl
61aa0ee40bcf3289b9686fde1af2d128
256 megabytes
["4 5\n1 1\n4 4\n4 3\n3 2\n2 4", "5 4\n2 1\n4 2\n3 3\n3 4"]
PASSED
from math import ceil n, q = map(int, input().split()) a = [] def getNumber(x, y): global n if n % 2 == 0: if (x + y) % 2 == 0: start = 0 else: start = n ** 2 // 2 pos = (x - 1) * n // 2 + (y + 1) // 2 else: t = (x - 1) * n + y + 1 if t % 2 == 0: start = 0 else: start = (n ** 2 + 1) // 2 pos = t // 2 return start + pos for i in range(q): xi, yi = map(int, input().split()) a.append(str(getNumber(xi, yi))) print('\n'.join(a))
1534602900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 1 4 6\n\n2 1 5 6\n\n2 2 1 4\n\n0 1 3 4 2 6 5"]
6c0ed9fe0a104fc9380c199003a22e90
NoteThe image below shows the hidden polygon in the example: The interaction in the example goes as below: Contestant reads $$$n = 6$$$. Contestant asks a query with $$$t = 1$$$, $$$i = 1$$$, $$$j = 4$$$, $$$k = 6$$$. Jury answers $$$15$$$. The area of the triangle $$$A_1A_4A_6$$$ is $$$7.5$$$. Note that the answer is two times the area of the triangle. Contestant asks a query with $$$t = 2$$$, $$$i = 1$$$, $$$j = 5$$$, $$$k = 6$$$. Jury answers $$$-1$$$. The cross product of $$$\overrightarrow{A_1A_5} = (2, 2)$$$ and $$$\overrightarrow{A_1A_6} = (4, 1)$$$ is $$$-2$$$. The sign of $$$-2$$$ is $$$-1$$$. Contestant asks a query with $$$t = 2$$$, $$$i = 2$$$, $$$j = 1$$$, $$$k = 4$$$. Jury answers $$$1$$$. The cross product of $$$\overrightarrow{A_2A_1} = (-5, 2)$$$ and $$$\overrightarrow{A_2A_4} = (-2, -1)$$$ is $$$1$$$. The sign of $$$1$$$ is $$$1$$$. Contestant says that the permutation is $$$(1, 3, 4, 2, 6, 5)$$$.
This is an interactive problem.Khanh has $$$n$$$ points on the Cartesian plane, denoted by $$$a_1, a_2, \ldots, a_n$$$. All points' coordinates are integers between $$$-10^9$$$ and $$$10^9$$$, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ such that the polygon $$$a_{p_1} a_{p_2} \ldots a_{p_n}$$$ is convex and vertices are listed in counter-clockwise order.Khanh gives you the number $$$n$$$, but hides the coordinates of his points. Your task is to guess the above permutation by asking multiple queries. In each query, you give Khanh $$$4$$$ integers $$$t$$$, $$$i$$$, $$$j$$$, $$$k$$$; where either $$$t = 1$$$ or $$$t = 2$$$; and $$$i$$$, $$$j$$$, $$$k$$$ are three distinct indices from $$$1$$$ to $$$n$$$, inclusive. In response, Khanh tells you: if $$$t = 1$$$, the area of the triangle $$$a_ia_ja_k$$$ multiplied by $$$2$$$. if $$$t = 2$$$, the sign of the cross product of two vectors $$$\overrightarrow{a_ia_j}$$$ and $$$\overrightarrow{a_ia_k}$$$. Recall that the cross product of vector $$$\overrightarrow{a} = (x_a, y_a)$$$ and vector $$$\overrightarrow{b} = (x_b, y_b)$$$ is the integer $$$x_a \cdot y_b - x_b \cdot y_a$$$. The sign of a number is $$$1$$$ it it is positive, and $$$-1$$$ otherwise. It can be proven that the cross product obtained in the above queries can not be $$$0$$$.You can ask at most $$$3 \cdot n$$$ queries.Please note that Khanh fixes the coordinates of his points and does not change it while answering your queries. You do not need to guess the coordinates. In your permutation $$$a_{p_1}a_{p_2}\ldots a_{p_n}$$$, $$$p_1$$$ should be equal to $$$1$$$ and the indices of vertices should be listed in counter-clockwise order.
null
null
standard output
standard input
PyPy 2
Python
2,300
train_030.jsonl
6cbee4e374df3177acee6dc4aaa413bc
256 megabytes
["6\n\n15\n\n-1\n\n1"]
PASSED
import sys range = xrange input = raw_input def query1(a,b,c): print 1, a+1, b+1, c+1 return int(input()) def query2(a,b,c): print 2, a+1, b+1, c+1 return int(input()) def ans(order): print 0,' '.join(str(x + 1) for x in order) sys.exit() n = int(input()) a = 0 b = 1 for i in range(2,n): if query2(a,b,i) < 0: b = i A = [-1]*n for i in range(1,n): if i != b: A[i] = query1(a,b,i) order = sorted(range(n), key = A.__getitem__) j = order[-1] left = [] right = [a,b] for i in order: if i != a and i != b and i != j: (left if query2(a,j,i) >= 0 else right).append(i) right.append(j) right += reversed(left) ans(right)
1574174100
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1.500000000000000", "2.000000000000000"]
adaae163882b064bf7257e82e8832ffb
NoteIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.
Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads.
standard output
standard input
Python 3
Python
1,500
train_010.jsonl
23430fc1c25c113258721964a6ec2e9b
256 megabytes
["4\n1 2\n1 3\n2 4", "5\n1 2\n1 3\n3 4\n2 5"]
PASSED
class Node: def __init__(self, index): self.neighbours = [] self.index = index self.prob = 1.0 self.vis = False self.length = 0 def addNode(self, city): self.neighbours.append(city) if self.index == 1: self.prob = 1.0 / len(self.neighbours) else: l = len(self.neighbours) self.prob = 1.0 if l < 2 else (1.0 / (l - 1)) n = int(input()) if n == 1: print(0) exit() cities = {} for i in range(n-1): a, b = map( lambda k: int(k), input().split()) #print ("test ", a, " to ", b) if a not in cities: cities[a] = Node(a) cities[a].addNode(b) if b not in cities: cities[b] = Node(b) cities[b].addNode(a) if len(cities) == 2: print(1) exit() # for i in range(1, n + 1, 1): # print ("city.index ", cities[i].index, ' roads ', cities[i].neighbours, ' prob ', cities[i].prob) # deadends = [] # deadendsProb = [] # def Parse(city, prob, length, oldCity): # #print ('parse ', city.index) # newprob = 1.0 if oldCity == 0 else cities[oldCity].prob # #print ('nnewProb ', newprob) # prob *= newprob # #print (city.index, ' len ', len(city.neighbours)) # if len(city.neighbours) == 1 and oldCity != 0: # deadends.append(length) # deadendsProb.append(prob) # else: # #print (city.neighbours) # length += 1 # for c in city.neighbours: # if c != oldCity: # Parse(cities[c], prob, length, city.index ) # Parse(cities[1], 1.0, 0, 0) # #for i in range(len(deadends)): # # print('len ', deadends[i], ' prob ', deadendsProb[i]) # ans = sum(map(lambda l, p: l * p, deadends, deadendsProb)) # #print('ans', ans) # print(ans) def inorder(city): s = [] s.append(city) #print ('index ', city.index) #print ('neighbours ', city.neighbours) while s: city = s.pop() city.vis = True if city.neighbours: if city.index == 1 or len(city.neighbours) > 1: for c in city.neighbours: if not cities[c].vis: cities[c].length = city.length + 1 cities[c].prob *= city.prob s.append(cities[c]) else: yield (city.index, city.prob, city.length) test = sum([city[1] * city[2] for city in inorder(cities[1])]) print(test) # this is a tree
1502548500
[ "probabilities", "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 1, 0, 1 ]
2 seconds
["fix", "Just a legend"]
fd94aea7ca077ee2806653d22d006fb1
null
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
standard output
standard input
PyPy 3
Python
1,700
train_000.jsonl
369f90ccad156909f0a8cd31f86e4e5a
256 megabytes
["fixprefixsuffix", "abcdabc"]
PASSED
import sys input=sys.stdin.readline import collections as cc s=input().strip() n=len(s) temp=cc.Counter(s) pre=[0]*(n) i=1 j=0 lst=-1 while i<n: if(s[i]==s[j]): j+=1 pre[i]=j i+=1 else: if j: j=pre[j-1] else: pre[i]=0 i+=1 pre[0]=0 #print(pre) temp=pre[-1] if pre[-1]!=0 and pre.count(temp)>=2: print(''.join(s[:temp])) elif pre[-1]!=0 and pre[pre[-1]-1]>0: print(''.join(s[:pre[pre[-1]-1]])) else: print('Just a legend')
1320858000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["molice", "cdcbcdcfcdc"]
67a70d58415dc381afaa74de1fee7215
NoteIn the second sample the name of the corporation consecutively changes as follows:
The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.
Print the new name of the corporation.
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.
standard output
standard input
Python 3
Python
1,200
train_000.jsonl
ba02b91aebce084f69fa4733b4496ca0
256 megabytes
["6 1\npolice\np m", "11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b"]
PASSED
import string t = string.ascii_lowercase t2 = list(t) #print(t2) n , m = map(int,input().split()) s = input() for i in range(m): x , y = input().split() index_x = t2.index(x) index_y = t2.index(y) t2[index_x] , t2[index_y] = t2[index_y] , t2[index_x] #print(t2) for i in s : index = ord(i) - ord('a') print(t2[index] , end = '')
1445763600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1\n2\n3\n3\n3\n3\n3", "1\n1\n1\n1\n1\n1\n4\n4", "1\n1\n1\n1\n1", "0\n1\n1\n1\n2\n2\n2\n3\n3\n3\n3\n4\n4\n4\n4\n4\n4\n4\n5"]
10e6b62d5b1abf8e1ba964a38dc6a9e8
NoteIn the first example: For $$$i = 1$$$, we can just apply one operation on $$$A_1$$$, the final states will be $$$1010110$$$; For $$$i = 2$$$, we can apply operations on $$$A_1$$$ and $$$A_3$$$, the final states will be $$$1100110$$$; For $$$i \ge 3$$$, we can apply operations on $$$A_1$$$, $$$A_2$$$ and $$$A_3$$$, the final states will be $$$1111111$$$. In the second example: For $$$i \le 6$$$, we can just apply one operation on $$$A_2$$$, the final states will be $$$11111101$$$; For $$$i \ge 7$$$, we can apply operations on $$$A_1, A_3, A_4, A_6$$$, the final states will be $$$11111111$$$.
There are $$$n$$$ lamps on a line, numbered from $$$1$$$ to $$$n$$$. Each one has an initial state off ($$$0$$$) or on ($$$1$$$).You're given $$$k$$$ subsets $$$A_1, \ldots, A_k$$$ of $$$\{1, 2, \dots, n\}$$$, such that the intersection of any three subsets is empty. In other words, for all $$$1 \le i_1 &lt; i_2 &lt; i_3 \le k$$$, $$$A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$$$.In one operation, you can choose one of these $$$k$$$ subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let $$$m_i$$$ be the minimum number of operations you have to do in order to make the $$$i$$$ first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between $$$i+1$$$ and $$$n$$$), they can be either off or on.You have to compute $$$m_i$$$ for all $$$1 \le i \le n$$$.
You must output $$$n$$$ lines. The $$$i$$$-th line should contain a single integer $$$m_i$$$  — the minimum number of operations required to make the lamps $$$1$$$ to $$$i$$$ be simultaneously on.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 3 \cdot 10^5$$$). The second line contains a binary string of length $$$n$$$, representing the initial state of each lamp (the lamp $$$i$$$ is off if $$$s_i = 0$$$, on if $$$s_i = 1$$$). The description of each one of the $$$k$$$ subsets follows, in the following format: The first line of the description contains a single integer $$$c$$$ ($$$1 \le c \le n$$$)  — the number of elements in the subset. The second line of the description contains $$$c$$$ distinct integers $$$x_1, \ldots, x_c$$$ ($$$1 \le x_i \le n$$$)  — the elements of the subset. It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations.
standard output
standard input
PyPy 2
Python
2,400
train_023.jsonl
5651c446583302149fd707727055a007
256 megabytes
["7 3\n0011100\n3\n1 4 6\n3\n3 4 7\n2\n2 3", "8 6\n00110011\n3\n1 3 8\n5\n1 2 5 6 7\n2\n6 8\n2\n3 5\n2\n4 7\n1\n2", "5 3\n00011\n3\n1 2 3\n1\n4\n3\n3 4 5", "19 5\n1001001001100000110\n2\n2 3\n2\n5 6\n2\n8 9\n5\n12 13 14 15 16\n1\n19"]
PASSED
import sys range = xrange input = raw_input n, k = [int(x) for x in input().split()] A = [+(c == '0') for c in input()] inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 B = [] for _ in range(k): m = inp[ii]; ii += 1 B.append([a - 1 for a in inp[ii: ii + m]]); ii += m buckets = [[] for _ in range(n)] for j in range(k): for a in B[j]: buckets[a].append(j) ##################### parent = list(range(2 * k)) size = [1] * (2 * k) state = [0] * (2 * k) true = [1] * k + [0] * k cost = 0 def find(a): acopy = a while a != parent[a]: a = parent[a] while acopy != a: parent[acopy], acopy = a, parent[acopy] return a def calcer(a): a = find(a) b = find((a + k) % (2 * k)) if state[a] == 0: return min(true[a], true[b]) elif state[a] == 1: return true[b] else: return true[a] def union(a, b): a, b = find(a), find(b) if a != b: if size[a] < size[b]: a, b = b, a parent[b] = a size[a] += size[b] state[a] |= state[b] true[a] += true[b] def on(a): global cost a = find(a) if state[a] == 0: b = find((a + k) % (2 * k)) cost -= calcer(a) state[a] = 1 state[b] = 2 cost += calcer(a) def same(a, b): global cost a = find(a) b = find(b) if a != b: cost -= calcer(a) cost -= calcer(b) union(a, b) union((a + k) % (2 * k), (b + k) % (2 * k)) cost += calcer(a) ###### out = [] for i in range(n): bucket = buckets[i] if not bucket: pass elif len(bucket) == 1: j = bucket[0] if not A[i]: on(j) else: on(j + k) else: j1, j2 = bucket if not A[i]: same(j1, j2) else: same(j1, j2 + k) out.append(cost) print '\n'.join(str(x) for x in out)
1580652300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["DA\nNET\nNET"]
046900001c7326fc8d890a22fa7267c9
NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move.
Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible: delete $$$s_1$$$ and $$$s_2$$$: $$$\textbf{10}11001 \rightarrow 11001$$$; delete $$$s_2$$$ and $$$s_3$$$: $$$1\textbf{01}1001 \rightarrow 11001$$$; delete $$$s_4$$$ and $$$s_5$$$: $$$101\textbf{10}01 \rightarrow 10101$$$; delete $$$s_6$$$ and $$$s_7$$$: $$$10110\textbf{01} \rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.
For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.
First line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), consisting of only characters 0 and 1.
standard output
standard input
PyPy 3
Python
900
train_001.jsonl
776c2e91e043e68aff6d1fe786090703
256 megabytes
["3\n01\n1111\n0011"]
PASSED
for _ in range(int(input())): s = input() s=list(s) if min(s.count('0'),s.count('1'))%2==0: print("NET") else: print("DA")
1593095700
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
3 seconds
["1", "2", "0", "7"]
b50df0e6d91d538cd7db8dfdc7cd5266
NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$.
You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.
Print a single integer — the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 10^9$$$) — the description of the $$$i$$$-th segment.
standard output
standard input
Python 3
Python
1,600
train_017.jsonl
76939e7684a7d63db408cf8b5ed7cc24
256 megabytes
["4\n1 3\n2 6\n0 4\n3 3", "5\n2 6\n1 3\n0 4\n1 20\n0 4", "3\n4 5\n1 2\n9 20", "2\n3 10\n1 5"]
PASSED
n=int(input()) l,r,s=[],[],[] for i in range(n): a,b=map(int,input().split()) l.append(a) r.append(b) s.append((a,b)) l=sorted(l)[::-1] r=sorted(r) if (l[0],r[0]) in s: print(max(r[1]-l[1],0)) else: print(max(r[0]-l[1],r[1]-l[0],0))
1535122200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["First\n2\n\n3"]
351c6fb0a9d1bbb29387c5b7ce8c7f28
NoteIn the sample input, the piles initially have $$$5$$$, $$$2$$$, and $$$6$$$ stones. Harris decides to go first and provides the number $$$2$$$ to Anton. Anton adds $$$2$$$ stones to the third pile, which results in $$$5$$$, $$$2$$$, and $$$8$$$.In the next turn, Harris chooses $$$3$$$. Note that Anton cannot add the stones to the third pile since he chose the third pile in the previous turn. Anton realizes that he has no valid moves left and reluctantly recognizes Harris as the king.
This is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing $$$a$$$, $$$b$$$, and $$$c$$$ stones, where $$$a$$$, $$$b$$$, and $$$c$$$ are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer $$$y$$$ and provides it to the second player. The second player adds $$$y$$$ stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if $$$1000$$$ turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!
null
The first line of input contains three distinct positive integers $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$)  — the initial number of stones in piles $$$1$$$, $$$2$$$, and $$$3$$$ respectively.
standard output
standard input
PyPy 3
Python
2,600
train_014.jsonl
822d93a7d953ac332a05a6715b77adb1
256 megabytes
["5 2 6\n\n\n3\n\n0"]
PASSED
l = list(map(int, input().split())) def play(x): global s res = int(input(str(x)+'\n')) if res == 0: exit(0) l[res-1] += x s = sorted(l) BIG = 10**11 print("First") play(BIG) play(s[2]*2-s[1]-s[0]) play(s[1]-s[0])
1593873900
[ "math", "games" ]
[ 1, 0, 0, 1, 0, 0, 0, 0 ]
0.5 seconds
["24"]
d41aebacfd5d16046db7c5d339478115
null
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.
Output one integer — the amount of ways to place the pennants on n tables.
The only line of the input contains one integer n (1 ≤ n ≤ 500) — the number of tables in the IT company.
standard output
standard input
PyPy 2
Python
1,600
train_020.jsonl
22c9c58d3b882f311742bd306135cd9b
64 megabytes
["2"]
PASSED
W = int(raw_input()) def ncr(n, r): res = 1 for i in xrange(r + 1, n + 1): res *= i for i in xrange(1, n - r + 1): res /= i return res print ncr(W + 5 - 1, W - 1) * ncr(W + 3 - 1, W - 1)
1455807600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1", "2"]
19ba94b8d223cc153d387287ce50ee1a
NoteIn the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because .There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because . Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because .
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that , where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments. Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
standard output
standard input
PyPy 2
Python
2,100
train_037.jsonl
c3ff6ae8c18b9fe0ad5a212085705336
256 megabytes
["1 1\n1", "4 2\n6 3 8 1"]
PASSED
from sys import stdin import math # stdin = open('in') n, k = map(int, stdin.readline().split()) a = [int(x) for x in stdin.readline().split()] nxt = [-1]*n pref = [] f, s = -1, 0 for i in range(n): s += a[i] pref.append(s) nxt[n-1-i] = f if a[n-1-i] != 1: f = n-1-i ans = 0 for i in range(n): pos, cur = i, 0 prod = 1 while 1: if prod > 1e18: break prod *= a[pos] cur += a[pos] if prod == k*cur: ans += 1 nt = nxt[pos] if nt == -1: ones = n-1-pos if k*cur < prod and k*(cur+ones) >= prod and prod%k == 0: ans += 1 break ones = nt - pos - 1 if k*cur < prod and k*(cur+ones) >= prod and prod%k == 0: ans += 1 cur += ones pos = nt print(ans)
1529339700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["021", "001122", "211200", "120120"]
cb852bf0b62d72b3088969ede314f176
null
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
standard output
standard input
Python 3
Python
1,500
train_018.jsonl
22230f3a8327ac73dffa4cbdf718b9d8
256 megabytes
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
PASSED
n = int(input()) s = list(input()) d = {i:0 for i in '012'} for i in s: d[i] += 1 eq = n // 3 i = 0 while d['0'] < eq: if s[i] != '0': if d[s[i]] > eq: d[s[i]] -= 1 d['0'] += 1 s[i] = '0' i += 1 i = n - 1 while d['2'] < eq: if s[i] != '2': if d[s[i]] > eq: d[s[i]] -= 1 d['2'] += 1 s[i] = '2' i -= 1 i = n - 1 while d['1'] < eq and i >= 0: if s[i] == '0': if d[s[i]] > eq: d[s[i]] -= 1 d['1'] += 1 s[i] = '1' i -= 1 i = 0 while d['1'] < eq and i < n: if s[i] == '2': if d[s[i]] > eq: d[s[i]] -= 1 d['1'] += 1 s[i] = '1' i += 1 print(*s, sep = '')
1547044500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n9\n6\n35\n112"]
eaab346f1dd620c8634a7991fa581bff
NoteIn the first test case, there is the only substring ")". Its cost is $$$1$$$ because we can insert '(' to the beginning of this substring and get a string "()", that is a balanced string.In the second test case, the cost of each substring of length one is $$$1$$$. The cost of a substring ")(" is $$$1$$$ because we can cyclically shift it to right and get a string "()". The cost of strings ")()" and "()(" is $$$1$$$ because its enough to insert one bracket to each of them. The cost of substring ")()(" is $$$1$$$ because we can cyclically shift it to right and get a string "()()". So there are $$$4 + 2 + 2 + 1 = 9$$$ substring of cost $$$1$$$ and $$$1$$$ substring of cost $$$0$$$. So the sum of the costs is $$$9$$$.In the third test case, "(", the cost is $$$1$$$; "()", the cost is $$$0$$$; "())", the cost is $$$1$$$; ")", the cost is $$$1$$$; "))", the cost is $$$2$$$; ")", the cost is $$$1$$$. So the sum of the costs is $$$6$$$.
Daemon Targaryen decided to stop looking like a Metin2 character. He turned himself into the most beautiful thing, a bracket sequence.For a bracket sequence, we can do two kind of operations: Select one of its substrings$$$^\dagger$$$ and cyclic shift it to the right. For example, after a cyclic shift to the right, "(())" will become ")(()"; Insert any bracket, opening '(' or closing ')', wherever you want in the sequence. We define the cost of a bracket sequence as the minimum number of such operations to make it balanced$$$^\ddagger$$$.Given a bracket sequence $$$s$$$ of length $$$n$$$, find the sum of costs across all its $$$\frac{n(n+1)}{2}$$$ non-empty substrings. Note that for each substring we calculate the cost independently.$$$^\dagger$$$ A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.$$$^\ddagger$$$ A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters $$$+$$$ and $$$1$$$. For example, sequences "(())()", "()", and "(()(()))" are balanced, while ")(", "(()", and "(()))(" are not.
For each test case, print a single integer — the sum of costs of all substrings of $$$s$$$.
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — 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 2 \cdot 10^5$$$) — the length of the bracket sequence. The second line of each test case contains a string $$$s$$$, consisting only of characters '(' and ')', of length $$$n$$$ — the bracket sequence. It is guaranteed that sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,400
train_101.jsonl
4abecb950b6e32430d8f119b093f8a8a
256 megabytes
["5\n\n1\n\n)\n\n4\n\n)()(\n\n3\n\n())\n\n5\n\n(((((\n\n10\n\n)(())))())"]
PASSED
import os,sys from random import randint, shuffle from io import BytesIO, IOBase from collections import defaultdict,deque,Counter from bisect import bisect_left,bisect_right from heapq import heappush,heappop from functools import lru_cache from itertools import accumulate, permutations import math # Fast IO Region 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") # for _ in range(int(input())): # n = int(input()) # a = list(map(int, input().split())) # for _ in range(int(input())): # n = int(input()) # a = list(map(int, input().split())) # if a[0] == min(a): # print('YES') # else: # print('NO') # for _ in range(int(input())): # n = int(input()) # s = input() # cnt = 0 # for i in range(n): # if s[i] == '0': # cnt += 1 # if cnt == 0 or cnt == n: # ans = n * n # else: # ans = cnt * (n - cnt) # a = s.split('0') # mx = 0 # for i in a: # mx = max(mx, len(i)) # b = s.split('1') # for i in b: # mx = max(mx, len(i)) # print(max(mx * mx, ans)) # N = int(pow(10 ** 9, 0.5)) + 5 # def get_prime_linear(n): # global cnt # for i in range(2, n + 1): # if not st[i]: # primes[cnt] = i # cnt += 1 # for j in range(n): # if primes[j] > n / i: break # st[primes[j] * i] = True # if i % primes[j] == 0: break # primes, cnt, st = [0] * (N + 5), 0, [False] * (N + 5) # get_prime_linear(N) # prime1e3 = primes[:cnt] # @lru_cache(None) # def get_factor(n): # res = [] # for i in prime1e3: # if i * i > n: # break # while n % i == 0: # n //= i # res.append(i) # if n > 1: # res.append(n) # return sorted(set(res)) # mod = 998244353 # for _ in range(int(input())): # n, m = list(map(int, input().split())) # a = list(map(int, input().split())) # ans = 1 # for i in range(1, n): # if a[i - 1] % a[i]: # ans = 0 # break # k = a[i - 1] // a[i] # mx = m // a[i] # f = get_factor(k) # res = 0 # N = len(f) # for i in range(1 << N): # cnt = 0 # cur = 1 # for j in range(N): # if i >> j & 1: # cnt += 1 # cur *= f[j] # if cnt % 2 == 0: res += mx // cur # else: res -= mx // cur # ans = ans * res % mod # print(ans) for _ in range(int(input())): n = int(input()) s = input() a = [0] cur = 0 for i in range(n): if s[i] == '(': cur += 1 else: cur -= 1 a.append(cur) n = len(a) stack = [] l = [-1] * (n) for i in range(n): while stack and stack[-1][0] >= a[i]: stack.pop() l[i] = stack[-1][1] if stack else -1 stack.append([a[i], i]) stack = [] r = [n] * (n) for i in range(n)[::-1]: while stack and stack[-1][0] > a[i]: stack.pop() r[i] = stack[-1][1] if stack else n stack.append([a[i], i]) ans = 0 for i in range(n): ans -= a[i] * (i - l[i]) * (r[i] - i) a.sort() for i in range(n): ans += (i + 1) * a[i] print(ans)
1667745300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n11\n14\n29\n80\n100\n100\n100\n118\n190\n196\n3000000094\n3000060094\n3000060400\n3000060952\n3000061270\n3000061366\n3000061366"]
d15cffca07768f8ce6fab7e13a6e7976
NoteIn the first test case, the array $$$a = [2]$$$ after the first query.In the third test case, the array $$$a$$$ is modified as follows: $$$[1, 3, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[10, 12, 10, 12, 18, 56]$$$ $$$\rightarrow$$$ $$$[22, 24, 22, 24, 30, 68]$$$ $$$\rightarrow$$$ $$$[23, 25, 23, 25, 31, 69]$$$.
You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.
The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
800
train_094.jsonl
fab543a1be575a368d7f292c5d70f849
256 megabytes
["4\n\n1 1\n\n1\n\n1 1\n\n3 3\n\n1 2 4\n\n0 2\n\n1 3\n\n0 5\n\n6 7\n\n1 3 2 4 10 48\n\n1 6\n\n0 5\n\n0 4\n\n0 5\n\n1 3\n\n0 12\n\n0 1\n\n6 7\n\n1000000000 1000000000 1000000000 11 15 17\n\n0 17\n\n1 10000\n\n1 51\n\n0 92\n\n0 53\n\n1 16\n\n0 1"]
PASSED
t = int(input()) for _ in range(t): n, q = [int(i) for i in input().split()] a = [int(j) for j in input().split()] n0 = 0 n1 = 0 suma = sum(a) for j in range(n): if a[j] % 2 == 0: n0 += 1 else: n1 += 1 for _ in range(q): operation, number = [int(i) for i in input().split()] if operation == 0: suma += (n0 * number) print(suma) if operation == 1: suma += (n1 * number) print(suma) if number % 2 != 0: if operation == 1: n0 += n1 n1 = 0 elif operation == 0: n1 += n0 n0 = 0
1665930900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2", "0", "1"]
02b0ffb0045fc0a2c8613c8ef58ed2c8
NoteIn the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns.
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.
Output the single integer — the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.
The first line contains one integer n (1 ≤ n ≤ 50) — the length of the hidden word. The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed. The third line contains an integer m (1 ≤ m ≤ 1000) — the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves — n-letter strings of lowercase Latin letters. All words are distinct. It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed.
standard output
standard input
PyPy 2
Python
1,500
train_016.jsonl
5f9d9239677c5cd147e3ba64c786d8e5
256 megabytes
["4\na**d\n2\nabcd\nacbd", "5\nlo*er\n2\nlover\nloser", "3\na*a\n2\naaa\naba"]
PASSED
n = int(raw_input()) s = str(raw_input()) m = int(raw_input()) cur = set(s) st = None for i in range(m): t = str(raw_input()) #check first if t is possible ch = ''.join(i if i in s else '*' for i in t) if ch == s: if st is None: st = set(t) else: st.intersection_update(set(t)) if st is None: st = set() st.difference_update(cur) print len(st)
1508573100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["baaaab", "daarkkcyan", "darkcyan"]
9463dd8f054eeaeeeeaec020932301c3
NoteThe images below present the tree for the examples. The number in each node is the node number, while the subscripted letter is its label. To the right is the string representation of the tree, with each letter having the same color as the corresponding node.Here is the tree for the first example. Here we duplicated the labels of nodes $$$1$$$ and $$$3$$$. We should not duplicate the label of node $$$2$$$ because it would give us the string "bbaaab", which is lexicographically greater than "baaaab". In the second example, we can duplicate the labels of nodes $$$1$$$ and $$$2$$$. Note that only duplicating the label of the root will produce a worse result than the initial string. In the third example, we should not duplicate any character at all. Even though we would want to duplicate the label of the node $$$3$$$, by duplicating it we must also duplicate the label of the node $$$2$$$, which produces a worse result. There is no way to produce string "darkkcyan" from a tree with the initial string representation "darkcyan" :(.
A binary tree of $$$n$$$ nodes is given. Nodes of the tree are numbered from $$$1$$$ to $$$n$$$ and the root is the node $$$1$$$. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote $$$l_u$$$ and $$$r_u$$$ as the left and the right child of the node $$$u$$$ respectively, $$$l_u = 0$$$ if $$$u$$$ does not have the left child, and $$$r_u = 0$$$ if the node $$$u$$$ does not have the right child.Each node has a string label, initially is a single character $$$c_u$$$. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let $$$f(u)$$$ be the string representation of the tree rooted at the node $$$u$$$. $$$f(u)$$$ is defined as follows: $$$$$$ f(u) = \begin{cases} \texttt{&lt;empty string&gt;}, &amp; \text{if }u = 0; \\ f(l_u) + c_u + f(r_u) &amp; \text{otherwise}, \end{cases} $$$$$$ where $$$+$$$ denotes the string concatenation operation.This way, the string representation of the tree is $$$f(1)$$$.For each node, we can duplicate its label at most once, that is, assign $$$c_u$$$ with $$$c_u + c_u$$$, but only if $$$u$$$ is the root of the tree, or if its parent also has its label duplicated.You are given the tree and an integer $$$k$$$. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most $$$k$$$ nodes?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
Print a single line, containing the lexicographically smallest string representation of the tree if at most $$$k$$$ nodes have their labels duplicated.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The second line contains a string $$$c$$$ of $$$n$$$ lower-case English letters, where $$$c_i$$$ is the initial label of the node $$$i$$$ for $$$1 \le i \le n$$$. Note that the given string $$$c$$$ is not the initial string representation of the tree. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i, r_i \le n$$$). If the node $$$i$$$ does not have the left child, $$$l_i = 0$$$, and if the node $$$i$$$ does not have the right child, $$$r_i = 0$$$. It is guaranteed that the given input forms a binary tree, rooted at $$$1$$$.
standard output
standard input
PyPy 3-64
Python
2,500
train_106.jsonl
be872f2351a7ebb25a1501c96898387d
256 megabytes
["4 3\nabab\n2 3\n0 0\n0 4\n0 0", "8 2\nkadracyn\n2 5\n3 4\n0 0\n0 0\n6 8\n0 7\n0 0\n0 0", "8 3\nkdaracyn\n2 5\n0 3\n0 4\n0 0\n6 8\n0 7\n0 0\n0 0"]
PASSED
import sys I=lambda:[*map(int, sys.stdin.readline().split())] left = [] right = [] n, k = I() parents = [-1] * n s = input() for i in range(n): l, r = I() l -= 1 r -= 1 left.append(l) right.append(r) if l >= 0: parents[l] = i if r >= 0: parents[r] = i covered = [0] * n covered.append(1) order = [] curr = 0 while len(order) < n: if covered[left[curr]]: if covered[curr]: if covered[right[curr]]: curr = parents[curr] else: curr = right[curr] else: covered[curr] = 1 order.append(curr) else: curr = left[curr] after = 'a' want = [0] * n curr = s[order[-1]] for i in range(n - 2, -1, -1): new = s[order[i]] if new != curr: after = curr curr = new if curr < after: want[order[i]] = 1 dist = [float('inf')] * n for v in order: if want[v]: dist[v] = 0 elif left[v] >= 0: dist[v] = dist[left[v]] + 1 dupe = [0] * n checked = [0] * n curr = 0 lef = k while lef > 0 and curr != -1: if dupe[curr]: if left[curr] >= 0 and dupe[left[curr]] == 0 and checked[left[curr]] == 0: curr = left[curr] elif right[curr] >= 0 and dupe[right[curr]] == 0 and checked[right[curr]] == 0: curr = right[curr] else: curr = parents[curr] else: if dist[curr] < lef: lef -= dist[curr] + 1 dupe[curr] = 1 for i in range(dist[curr]): curr = left[curr] dupe[curr] = 1 else: checked[curr] = 1 curr = parents[curr] out = [] for guy in order: if dupe[guy]: out.append(2 * s[guy]) else: out.append(s[guy]) print(''.join(out))
1640698500
[ "strings", "trees" ]
[ 0, 0, 0, 0, 0, 0, 1, 1 ]
2 seconds
["4"]
38bee9c2b21d2e91fdda931c8cacf204
NoteIn the sample the longest chain the Donkey can build consists of four stars. Note that the Donkey can't choose the stars that lie on the rays he imagines.
In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis — up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles α1 and α2 to the OX axis. Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles α1 and α2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star. As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.Your task is to find the maximum number of stars m that the Donkey's chain can contain.Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain.
In a single line print number m — the answer to the problem.
The first line contains an integer n (1 ≤ n ≤ 105) — the number of stars. The second line contains simple fractions representing relationships "a/b c/d", such that and (0 ≤ a, b, c, d ≤ 105; ; ; ). The given numbers a, b, c, d are integers. Next n lines contain pairs of integers xi, yi (1 ≤ xi, yi ≤ 105)— the stars' coordinates. It is guaranteed that all stars have distinct coordinates.
standard output
standard input
Python 3
Python
2,700
train_024.jsonl
f7de2c566f0a15379fec35e1945f4fe1
256 megabytes
["15\n1/3 2/1\n3 1\n6 2\n4 2\n2 5\n4 5\n6 6\n3 4\n1 6\n2 1\n7 4\n9 3\n5 3\n1 3\n15 5\n12 4"]
PASSED
import bisect def INPUT(): global n, a, b, c, d n = int(input()) a, b, c, d = [int(j) for i in input().split() for j in i.split("/")] global y_alpha y_alpha = [] for _ in range(n): x, y = [int(x) for x in input().split()] y_alpha.append((b * y - a * x, c * x - d * y)) if __name__ == '__main__': INPUT() y_alpha = sorted([(x, y) for x, y in y_alpha if x > 0 and y > 0], key = lambda x: (x[0], -x[1])) dp = [] for x, y in y_alpha: i = bisect.bisect_left(dp, y) if i == len(dp): dp.append(y) else: dp[i] = y; print(len(dp));
1353857400
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"]
29bc7a22baa3dc6bb508b00048e50114
NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people.
William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet.
Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions.
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_110.jsonl
57aab1d4fc2365bdfd01e1e55fe8eb24
256 megabytes
["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"]
PASSED
from collections import defaultdict n = (10 ** 3)+10 parent = [i for i in range(n)] size = [1 for i in range(n)] def find(root): a = root while parent[a] != a: a = parent[a] # path comprehension while root != a: nextnode = parent[root] parent[root] = a root = nextnode return a def union(a, b): a = find(a) b = find(b) if a != b: if size[a] < size[b]: a, b = b, a parent[b] = a size[a] += size[b] return False else: return True c=0 l,d=map(int,input().split()) for j in range(d): a,b=map(int,input().split()) cans = union(a,b) if cans: c+=1 ans=0 allp=set() grps=[] for k in range(1,l+1): pr= find(k) if pr not in allp: allp.add(pr) grps.append(size[pr]) grps.sort(reverse=True) # print(grps) # print(parent[:l+1]) # print(c) for k in range(min(c+1,len(grps))): ans+=grps[k] print(ans-1)
1638110100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3 seconds
["3\n1 1 1 5\n1 5 8 5\n8 5 8 6"]
f0bd06345a2aeeb5faedc824fb5f42b9
NoteThe points and the segments from the example are shown below.
You are given three points on a plane. You should choose some segments on the plane that are parallel to coordinate axes, so that all three points become connected. The total length of the chosen segments should be the minimal possible.Two points $$$a$$$ and $$$b$$$ are considered connected if there is a sequence of points $$$p_0 = a, p_1, \ldots, p_k = b$$$ such that points $$$p_i$$$ and $$$p_{i+1}$$$ lie on the same segment.
On the first line output $$$n$$$ — the number of segments, at most 100. The next $$$n$$$ lines should contain descriptions of segments. Output four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ on a line — the coordinates of the endpoints of the corresponding segment ($$$-10^9 \le x_1, y_1, x_2, y_2 \le 10^9$$$). Each segment should be either horizontal or vertical. It is guaranteed that the solution with the given constraints exists.
The input consists of three lines describing three points. Each line contains two integers $$$x$$$ and $$$y$$$ separated by a space — the coordinates of the point ($$$-10^9 \le x, y \le 10^9$$$). The points are pairwise distinct.
standard output
standard input
Python 3
Python
1,800
train_091.jsonl
84d346b43dc19930e6c92c4fb69b4e38
512 megabytes
["1 1\n3 5\n8 6"]
PASSED
# -- coding: utf-8 -- ''' Author: your name Date: 2022-01-03 20:13:21 LastEditTime: 2022-05-28 17:47:53 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: /code_everyWeek/week6.py ''' class Point(): def __init__(self, x, y): self.x = x self.y = y def connect_the_points(point_list): sorted_point_y = sorted(point_list, key=lambda x:x.y) sorted_point_x = sorted(point_list, key=lambda x:x.x) res = [] if sorted_point_x[0].x != sorted_point_x[2].x: res.append([sorted_point_x[0].x, sorted_point_y[1].y, sorted_point_x[2].x, sorted_point_y[1].y]) if sorted_point_y[0].y != sorted_point_y[1].y: res.append([sorted_point_y[0].x, sorted_point_y[0].y, sorted_point_y[0].x, sorted_point_y[1].y]) if sorted_point_y[2].y != sorted_point_y[1].y: res.append([sorted_point_y[2].x, sorted_point_y[2].y, sorted_point_y[2].x, sorted_point_y[1].y]) return res if __name__ == "__main__": point_list = [] for i in range(3): terms = input().split(" ") point = Point(int(terms[0]), int(terms[1])) point_list.append(point) res = connect_the_points(point_list) print(len(res)) for x in res: print(" ".join(list(map(str, x))))
1649837100
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["0 2 1", "0 0 1 1", "0"]
a2085c2d21b2dbe4cc27a15fa4a1ec4f
NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.
Print exactly $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.
standard output
standard input
PyPy 3
Python
900
train_000.jsonl
3794a6ddf45465943e15bd3e76dc57e9
256 megabytes
["3 5\n3 7 9", "4 20\n10 9 19 2", "1 100\n99"]
PASSED
inp = input() n, m = inp.split() n = int(n) m = int(m) inp = input() a = inp.split() remainder = 0 for aith in a: names = int(aith) if names == 0: print(0, end=" ") else: pages = int((names + remainder) / m) remainder = (names + remainder) % m print(pages, end=" ")
1533307500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["possible", "impossible"]
f217337f015224231e64a992329242e8
NoteIn the first sample, a possible choice for the values of the $$$a_i$$$ is $$$3, 4, 3, 5, 2$$$. On the first day, Dora buys the integers $$$3, 4$$$ and $$$3$$$, whose LCM is $$$12$$$, while Swiper buys integers $$$5$$$ and $$$2$$$, whose LCM is $$$10$$$. On the second day, Dora buys $$$3, 5$$$ and $$$2$$$, whose LCM is $$$30$$$, and Swiper buys integers $$$3$$$ and $$$4$$$, whose LCM is $$$12$$$.
Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?There are $$$n$$$ stores numbered from $$$1$$$ to $$$n$$$ in Nlogonia. The $$$i$$$-th of these stores offers a positive integer $$$a_i$$$.Each day among the last $$$m$$$ days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.Dora considers Swiper to be her rival, and she considers that she beat Swiper on day $$$i$$$ if and only if the least common multiple of the numbers she bought on day $$$i$$$ is strictly greater than the least common multiple of the numbers that Swiper bought on day $$$i$$$.The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.However, Dora forgot the values of $$$a_i$$$. Help Dora find out if there are positive integer values of $$$a_i$$$ such that she beat Swiper on every day. You don't need to find what are the possible values of $$$a_i$$$ though.Note that it is possible for some values of $$$a_i$$$ to coincide in a solution.
Output must consist of a single line containing "possible" if there exist positive integers $$$a_i$$$ such that for each day the least common multiple of the integers bought by Dora is strictly greater than the least common multiple of the integers bought by Swiper on that day. Otherwise, print "impossible". Note that you don't have to restore the integers themselves.
The first line contains integers $$$m$$$ and $$$n$$$ ($$$1\leq m \leq 50$$$, $$$1\leq n \leq 10^4$$$) — the number of days and the number of stores. After this $$$m$$$ lines follow, the $$$i$$$-th line starts with an integer $$$s_i$$$ ($$$1\leq s_i \leq n-1$$$), the number of integers Dora bought on day $$$i$$$, followed by $$$s_i$$$ distinct integers, the indices of the stores where Dora bought an integer on the $$$i$$$-th day. The indices are between $$$1$$$ and $$$n$$$.
standard output
standard input
PyPy 3
Python
2,100
train_008.jsonl
f4241da82851c9d5c18d446465251ee7
256 megabytes
["2 5\n3 1 2 3\n3 3 4 5", "10 10\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10"]
PASSED
# https://codeforces.com/problemset/problem/1166/E def push(d, x): if x not in d: d[x]=0 d[x]+=1 def check(a, i, j): for x in a[i]: d[x]+=1 for x in a[j]: d[x]+=1 for val in d: if val==2: refresh() return True refresh() return False def refresh(): for i in range(len(d)): d[i]=0 m, n = map(int, input().split()) d = [0] * 10010 arr=[] for _ in range(m): arr.append(list(map(int, input().split()))[1:]) flg=True for i in range(m): for j in range(i+1, m): if check(arr, i, j)==False: flg=False break if flg==True: print('possible') else: print('impossible')
1558105500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["2 2\n4 6\n12 12\n-1 -1\n-1 -1\n373248 730\n-1 -1\n15120 53760\n-1 -1\n536870912 536870912"]
27be78f2739b681b25c331c60fc2b22b
null
This is an hard version of the problem. The only difference between an easy and a hard version is the constraints on $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$.You are given $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ with $$$a &lt; c$$$ and $$$b &lt; d$$$. Find any pair of numbers $$$x$$$ and $$$y$$$ that satisfies the following conditions: $$$a &lt; x \leq c$$$, $$$b &lt; y \leq d$$$, $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$.Note that required $$$x$$$ and $$$y$$$ may not exist.
For each test case print a pair of numbers $$$a &lt; x \leq c$$$ and $$$b &lt; y \leq d$$$ such that $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$. If there are multiple answers, print any of them. If there is no such pair of numbers, then print -1 -1.
The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10$$$), the number of test cases. The descriptions of the test cases follow. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1 \leq a &lt; c \leq 10^9$$$, $$$1 \leq b &lt; d \leq 10^9$$$).
standard output
standard input
PyPy 3-64
Python
1,900
train_094.jsonl
d41410cfe389f53b145fceb776a55cf8
256 megabytes
["10\n\n1 1 2 2\n\n3 4 5 7\n\n8 9 15 18\n\n12 21 14 24\n\n36 60 48 66\n\n1024 729 373248 730\n\n1024 729 373247 730\n\n5040 40320 40319 1000000000\n\n999999999 999999999 1000000000 1000000000\n\n268435456 268435456 1000000000 1000000000"]
PASSED
ceil = lambda a, b: (((a) + ((b) - 1)) // (b)) def make_divisors(n): divisors = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n // i) # divisors.sort() return divisors q = int(input()) for _ in range(q): a, b, c, d = map(int, input().split()) ab = a * b res = [-1, -1] DivAs = make_divisors(a) DivBs = make_divisors(b) for DivA in DivAs: for DivB in DivBs: e = DivA * DivB f = ab // e x = ceil(a + 1, e) * e if not (a < x <= c): continue y = ceil(b + 1, f) * f if not (b < y <= d): continue res = [x, y] print(*res)
1665930900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["3", "2"]
a628b6606c977059dca6d8dd05de99d4
NoteIn the first sample periodic numbers are 3, 7 and 10.In the second sample periodic numbers are 31 and 36.
A non-empty string s is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string s from 1 to the string's length and let's denote the i-th character in string s as si.Binary string s with length n is periodical, if there is an integer 1 ≤ k &lt; n such that: k is a divisor of number n for all 1 ≤ i ≤ n - k, the following condition fulfills: si = si + k For example, binary strings "101010" and "11" are periodical and "10" and "10010" are not.A positive integer x is periodical, if its binary representation (without leading zeroes) is a periodic string.Your task is to calculate, how many periodic numbers are in the interval from l to r (both ends are included).
Print a single integer, showing how many periodic numbers are in the interval from l to r (both ends are included).
The single input line contains two integers l and r (1 ≤ l ≤ r ≤ 1018). The numbers are separated by a space. 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 2
Python
2,100
train_013.jsonl
dd289908a5bdadfddea25262106c87ad
256 megabytes
["1 10", "25 38"]
PASSED
import math def tree_search(l, u, x, a, b): if u == l: if check_upper(u, a, b, x): return u else: return u-1 if u - l <= 1: if check_upper(u, a, b, x): return u elif check_upper(l, a, b, x): return l else: return l-1 m = (l+u)/2 if check_upper(m, a, b, x): return tree_search(m, u, x, a, b) else: return tree_search(l, m, x, a, b) dict_periodical = {} def periodical(n): if n == 1: return 0 if n in dict_periodical: return dict_periodical[n] total = 0 for d in divisor(n): total = total + pow(2, d-1) - periodical(d) dict_periodical[n] = total return total def check_upper(p, a, b, upper): mask = pow(2, a) - 1 for i in range(b-1, -1,-1): converted = (upper >> i*a) & mask if converted > p: return True elif converted < p: return False else: continue return True #dict_periodical_upper_div = {} def periodical_upper_div(a, upper, k): # if a in dict_periodical_upper_div: # return dict_periodical_upper_div[a] sum = 0 b = k/a # for c in range(pow(2,a-1), pow(2,a)): # if check_upper(c, a, b, upper): # sum += 1 # else: # break l = pow(2,a-1) u = pow(2,a) sum = tree_search(l, u-1, upper, a, b) - l + 1 for d in divisor(a): sum -= periodical_upper_div(d, upper, k) # dict_periodical_upper_div[a] = sum return sum def periodical_upper(upper, k): sum = 0 for a in divisor(k): sum += periodical_upper_div(a, upper, k) # dict_periodical_upper_div.clear() return sum dict_sigma = {} def sigma(n, l): if (n, l) in dict_sigma: return dict_sigma[(n, l)] k = pow(2,n) result = (1 - pow(k, l))/(1-k) dict_sigma[(n, l)] = result return result dict_divisor = {} def divisor(n): if n in dict_divisor: return dict_divisor[n] results = [] for i in range(1, n/2+1): if n%i == 0: results.append(i) dict_sigma[n] = results return results def periodical_upper_total(m): if m == 0: return 0 k = int(math.floor(math.log(m, 2)))+1 num = 0 for i in range(1, k): num += periodical(i) num += periodical_upper(m, k) return num def count_periodical(n, m): return periodical_upper_total(m) - periodical_upper_total(n-1) [l, r] = raw_input().split() print count_periodical(long(l), long(r)) #print count_periodical(1, 1000000000000000000) #print count_periodical(1, 10000000000000000000) #print periodical_upper_total(25) #print periodical_upper_total(38) #100100 #print count_periodical(7, 9) #883 947 #(891, 5, 2)1101111011 #(924, 5, 2)1110011100
1344267000
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["4", "860616440"]
c602545676f6388a5c5107a5d83fc2c6
NoteAn example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
You are given an integer m.Let M = 2m - 1.You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.A set of integers S is called "good" if the following hold. If , then . If , then All elements of S are less than or equal to M. Here, and refer to the bitwise XOR and bitwise AND operators, respectively.Count the number of good sets S, modulo 109 + 7.
Print a single integer, the number of good sets modulo 109 + 7.
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)). The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
standard output
standard input
Python 3
Python
2,500
train_068.jsonl
723c91ddc44a78810fbb2eb203f64390
256 megabytes
["5 3\n11010\n00101\n11000", "30 2\n010101010101010010101010101010\n110110110110110011011011011011"]
PASSED
MOD = 10**9 + 7 m, N = map(int, input().split()) binom = [[1] + [0 for i in range(m)] for j in range(m + 1)] for n in range(1, m + 1): for k in range(1, n + 1): binom[n][k] = (binom[n - 1][k] + binom[n - 1][k - 1]) % MOD bell = [0 for n in range(m + 1)] bell[0] = bell[1] = 1 for n in range(1, m): for k in range(n + 1): bell[n + 1] += bell[k] * binom[n][k] bell[n + 1] %= MOD #print(bell) bags = [0 for i in range(m)] for it in range(N): for i, z in enumerate(input()): if z == '1': bags[i] |= (1 << it) difs = set(bags) sol = 1 for mask in difs: sol = sol * bell[bags.count(mask)] % MOD print(sol)
1514562000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]