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
4 seconds
["1"]
bd519efcfaf5b43bb737337004a1c2c0
null
You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
Print the only integer c — the number of parallelograms with the vertices at the given points.
The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points. Each of the next n lines contains two integers (xi, yi) (0 ≤ xi, yi ≤ 109) — the coordinates of the i-th point.
standard output
standard input
PyPy 3
Python
1,900
train_042.jsonl
82c99a94439adb77a2c7994a093e41c1
256 megabytes
["4\n0 1\n1 0\n1 1\n2 0"]
PASSED
n = int(input()) points = [0] * n D = {} for i in range(n): points[i] = tuple(int(x) for x in input().split()) for i in range(n): for j in range(i+1, n): x1, y1 = points[i] x2, y2 = points[j] u, v = x2 - x1, y2 - y1 if u < 0 or u == 0 and v < 0: u, v = -u, -v if (u, v) in D: D[(u, v)] += 1 else: D[(u, v)] = 1 S = sum(D[i] * (D[i] - 1) // 2 for i in D) print(S // 2)
1460127600
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["1 -1\n-1 5 1 -1 -1\n-10 2 2 -3 5 -1 -1"]
c4541021337252c7e2c4afd2de8cd766
NoteIn the first test case, $$$5 \cdot 1 + 5 \cdot (-1)=5-5=0$$$. You could also print $$$3$$$ $$$-3$$$, for example, since $$$5 \cdot 3 + 5 \cdot (-3)=15-15=0$$$In the second test case, $$$5 \cdot (-1) + (-2) \cdot 5 + 10 \cdot 1 + (-9) \cdot (-1) + 4 \cdot (-1)=-5-10+10+9-4=0$$$.
Vupsen and Pupsen were gifted an integer array. Since Vupsen doesn't like the number $$$0$$$, he threw away all numbers equal to $$$0$$$ from the array. As a result, he got an array $$$a$$$ of length $$$n$$$.Pupsen, on the contrary, likes the number $$$0$$$ and he got upset when he saw the array without zeroes. To cheer Pupsen up, Vupsen decided to come up with another array $$$b$$$ of length $$$n$$$ such that $$$\sum_{i=1}^{n}a_i \cdot b_i=0$$$. Since Vupsen doesn't like number $$$0$$$, the array $$$b$$$ must not contain numbers equal to $$$0$$$. Also, the numbers in that array must not be huge, so the sum of their absolute values cannot exceed $$$10^9$$$. Please help Vupsen to find any such array $$$b$$$!
For each test case print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — elements of the array $$$b$$$ ($$$|b_1|+|b_2|+\ldots +|b_n| \le 10^9$$$, $$$b_i \neq 0$$$, $$$\sum_{i=1}^{n}a_i \cdot b_i=0$$$). It can be shown that the answer always exists.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^4 \le a_i \le 10^4$$$, $$$a_i \neq 0$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,600
train_106.jsonl
14ae81da2993ef3457470fe65b705f94
256 megabytes
["3\n2\n5 5\n5\n5 -2 10 -9 4\n7\n1 2 3 4 5 6 7"]
PASSED
def solve(n, aa): head, tail = [], [] if n % 2 == 1: a, b, c = aa[n-3], aa[n-2], aa[n-1] if b + c != 0: tail = [b+c, -a, -a] else: tail = [b-c, -a, a] n -= 3 idx = 0 while idx < n: factor = gcd(aa[idx], aa[idx+1]) head.append(aa[idx+1] // factor) head.append(-aa[idx] // factor) idx += 2 return head + tail def gcd(x, y): x, y = abs(x), abs(y) while y: x, y = y, x % y return x for _ in range(int(input())): n = int(input()) aa = list(map(int, input().split())) bb = solve(n, aa) print(' '.join(map(str, bb)))
1635069900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
6 seconds
["5\n2\n1\n4\n0\n4"]
c7f0fefd9616e4ba2d309a7c5c8a8a0a
NoteThe tree in the first example is shown in the following picture: Answers to the queries are obtained as follows: $$$v=1,k=0$$$: you can delete vertices $$$7$$$ and $$$3$$$, so the vertex $$$1$$$ has $$$5$$$ children (vertices $$$2$$$, $$$4$$$, $$$5$$$, $$$6$$$, and $$$8$$$), and the score is $$$5 - 2 \cdot 0 = 5$$$; $$$v=1,k=2$$$: you can delete the vertex $$$7$$$, so the vertex $$$1$$$ has $$$4$$$ children (vertices $$$3$$$, $$$4$$$, $$$5$$$, and $$$6$$$), and the score is $$$4 - 1 \cdot 2 = 2$$$. $$$v=1,k=3$$$: you shouldn't delete any vertices, so the vertex $$$1$$$ has only one child (vertex $$$7$$$), and the score is $$$1 - 0 \cdot 3 = 1$$$; $$$v=7,k=1$$$: you can delete the vertex $$$3$$$, so the vertex $$$7$$$ has $$$5$$$ children (vertices $$$2$$$, $$$4$$$, $$$5$$$, $$$6$$$, and $$$8$$$), and the score is $$$5 - 1 \cdot 1 = 4$$$; $$$v=5,k=0$$$: no matter what you do, the vertex $$$5$$$ will have no children, so the score is $$$0$$$; $$$v=7,k=200000$$$: you shouldn't delete any vertices, so the vertex $$$7$$$ has $$$4$$$ children (vertices $$$3$$$, $$$4$$$, $$$5$$$, and $$$6$$$), and the score is $$$4 - 0 \cdot 200000 = 4$$$.
You are given a tree consisting of $$$n$$$ vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex $$$1$$$.You have to process $$$q$$$ queries. In each query, you are given a vertex of the tree $$$v$$$ and an integer $$$k$$$.To process a query, you may delete any vertices from the tree in any order, except for the root and the vertex $$$v$$$. When a vertex is deleted, its children become the children of its parent. You have to process a query in such a way that maximizes the value of $$$c(v) - m \cdot k$$$ (where $$$c(v)$$$ is the resulting number of children of the vertex $$$v$$$, and $$$m$$$ is the number of vertices you have deleted). Print the maximum possible value you can obtain.The queries are independent: the changes you make to the tree while processing a query don't affect the tree in other queries.
For each query, print one integer — the maximum value of $$$c(v) - m \cdot k$$$ you can achieve.
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. Then $$$n-1$$$ lines follow, the $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$) — the endpoints of the $$$i$$$-th edge. These edges form a tree. The next line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, the $$$j$$$-th of them contains two integers $$$v_j$$$ and $$$k_j$$$ ($$$1 \le v_j \le n$$$; $$$0 \le k_j \le 2 \cdot 10^5$$$) — the parameters of the $$$j$$$-th query.
standard output
standard input
PyPy 3-64
Python
2,800
train_108.jsonl
d344a982851d811dfb4757119fd51e33
512 megabytes
["8\n6 7\n3 2\n8 3\n5 7\n7 4\n7 1\n7 3\n6\n1 0\n1 2\n1 3\n7 1\n5 0\n7 200000"]
PASSED
import sys, collections n = int(sys.stdin.readline()) e = [[] for i in range(n+1)] for i in range(n-1): a, b = [int(i) for i in sys.stdin.readline().split()] e[a].append(b) e[b].append(a) o = [len(e[i])-1 for i in range(0, n+1)] o[1]+=1 r = [[] for i in range(n+1)] st = collections.deque([1]) d = [0]*(n+1) p = [0]*(n+1) while st: x = st.popleft() for i in e[x]: if i != p[x]: st.append(i); d[i] = d[x]+1; p[i] = x d = [(d[i], i) for i in range(1,n+1)] d.sort(key=lambda x:x[0], reverse=True) for _, v in d: r[v] = [o[v]]*max(max(len(r[i]) for i in e[v]), o[v]-1) for i in e[v]: if i == p: continue for idx, x in enumerate(r[i]): r[v][idx]+=max(x-idx-1, 0) for q in range(int(sys.stdin.readline())): v, k = [int(i) for i in sys.stdin.readline().split()] if k >= len(r[v]): print(o[v]) else: print(r[v][k])
1635518100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["10", "1", "4", "0"]
a5d3c9ea1c9affb0359d81dae4ecd7c8
NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
In the only line print the integer S — the minimum number of burles which are had to spend.
The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom. The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.
standard output
standard input
Python 2
Python
800
train_020.jsonl
41e90df120ed623c64bb38d6e4f09d59
256 megabytes
["5\n0 1 2 3 4", "5\n1 1 0 1 1", "3\n1 3 1", "1\n12"]
PASSED
x=int(raw_input()) y=map(int,raw_input().split()) max=y[0] sum=0 for i in range(len(y)): if y[i]>max: max=y[i] for i in range(len(y)): if y[i]!=max: sum=sum+(max-y[i]) print(sum)
1484838300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6\n0"]
66eb860613bf3def9c1b3f8bb3a6763a
Note In test case $$$1$$$, all possible subsegments of sequence $$$[1, 2, 1, 1]$$$ having size more than $$$1$$$ are: $$$[1, 2]$$$ having $$$0$$$ valid unordered pairs; $$$[2, 1]$$$ having $$$0$$$ valid unordered pairs; $$$[1, 1]$$$ having $$$1$$$ valid unordered pair; $$$[1, 2, 1]$$$ having $$$1$$$ valid unordered pairs; $$$[2, 1, 1]$$$ having $$$1$$$ valid unordered pair; $$$[1, 2, 1, 1]$$$ having $$$3$$$ valid unordered pairs. Answer is $$$6$$$. In test case $$$2$$$, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is $$$0$$$.
The weight of a sequence is defined as the number of unordered pairs of indexes $$$(i,j)$$$ (here $$$i \lt j$$$) with same value ($$$a_{i} = a_{j}$$$). For example, the weight of sequence $$$a = [1, 1, 2, 2, 1]$$$ is $$$4$$$. The set of unordered pairs of indexes with same value are $$$(1, 2)$$$, $$$(1, 5)$$$, $$$(2, 5)$$$, and $$$(3, 4)$$$.You are given a sequence $$$a$$$ of $$$n$$$ integers. Print the sum of the weight of all subsegments of $$$a$$$. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer — the sum of the weight of all subsegments of $$$a$$$.
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 a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_085.jsonl
661caaec62312454f127c801003445fc
256 megabytes
["2\n4\n1 2 1 1\n4\n1 2 3 4"]
PASSED
import sys input = sys.stdin.readline def solve(): t = int(input()) for i in range(t): n = int(input()) s = [int(x) for x in input().split()] res, temp = 0, 0 idx_sum = {} for j in range(n): if s[j] in idx_sum: temp += idx_sum[s[j]] else: idx_sum[s[j]] = 0 idx_sum[s[j]] += j + 1 res += temp sys.stdout.write(str(res) + "\n") if __name__ == '__main__': solve()
1621521300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0\n1\n2"]
58dfab2a45314bbf93c20604e047e7b7
NoteIn the first test case, there is only one vertex, so you don't need any queries.In the second test case, you can ask a single query about the node $$$1$$$. Then, if $$$x = 1$$$, you will get $$$0$$$, otherwise you will get $$$1$$$.
The only difference between this problem and D1 is the bound on the size of the tree.You are given an unrooted tree with $$$n$$$ vertices. There is some hidden vertex $$$x$$$ in that tree that you are trying to find.To do this, you may ask $$$k$$$ queries $$$v_1, v_2, \ldots, v_k$$$ where the $$$v_i$$$ are vertices in the tree. After you are finished asking all of the queries, you are given $$$k$$$ numbers $$$d_1, d_2, \ldots, d_k$$$, where $$$d_i$$$ is the number of edges on the shortest path between $$$v_i$$$ and $$$x$$$. Note that you know which distance corresponds to which query.What is the minimum $$$k$$$ such that there exists some queries $$$v_1, v_2, \ldots, v_k$$$ that let you always uniquely identify $$$x$$$ (no matter what $$$x$$$ is).Note that you don't actually need to output these queries.
For each test case print a single nonnegative integer, the minimum number of queries you need, on its own line.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$)  — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$), meaning there is an edges between vertices $$$x$$$ and $$$y$$$ in the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,300
train_089.jsonl
0785a932dfd5fe17a37d293ec3fe7321
256 megabytes
["3\n\n1\n\n2\n\n1 2\n\n10\n\n2 4\n\n2 1\n\n5 7\n\n3 10\n\n8 6\n\n6 1\n\n1 3\n\n4 7\n\n9 6"]
PASSED
from collections import deque;I=input def f(x,pre): q=deque([(x,pre)]);dp=[0]*(n+1);R=[] while q: u,p=q.popleft() R.append((u)) for v in g[u]: if v!=p:g[v].remove(u);q.append((v,u)) for u in R[::-1]: z=c=0 for v in g[u]: z+=dp[v] if dp[v]==0:c+=1 dp[u]=z+max(0,c-1) return dp[x] for _ in [0]*int(I()): n=int(I());g=[[] for _ in range(n+1)] for _ in range(n-1): u,v=map(int,I().split());g[u].append(v);g[v].append(u) if n==1:z=0 else: for u in range(1,n+1): if len(g[u])>=3:z=f(u,0);break else:z=1 print(z)
1655562900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
5 seconds
["1", "0", "4", "1"]
463d4e6badd3aa110cc87ae7049214b4
null
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.In Shapur's opinion the weakness of an army is equal to the number of triplets i, j, k such that i &lt; j &lt; k and ai &gt; aj &gt; ak where ax is the power of man standing at position x. The Roman army has one special trait — powers of all the people in it are distinct.Help Shapur find out how weak the Romans are.
A single integer number, the weakness of the Roman army. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
The first line of input contains a single number n (3 ≤ n ≤ 106) — the number of men in Roman army. Next line contains n different positive integers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 109) — powers of men in the Roman army.
standard output
standard input
PyPy 2
Python
1,900
train_009.jsonl
5eb189e0a0f8c3d0458ca836514d5fc5
256 megabytes
["3\n3 2 1", "3\n2 3 1", "4\n10 8 3 1", "4\n1 5 4 3"]
PASSED
def fast2(): import os, sys, atexit from cStringIO import StringIO as BytesIO # range = xrange sys.stdout = BytesIO() atexit.register(lambda: os.write(1, sys.stdout.getvalue())) return BytesIO(os.read(0, os.fstat(0).st_size)).readline class order_tree: def __init__(self, n): self.tree, self.n = [[0, 0] for _ in range(n << 1)], n # get interval[l,r) def query(self, r, col): res = 0 l = self.n r += self.n while l < r: if l & 1: res += self.tree[l][col] l += 1 if r & 1: r -= 1 res += self.tree[r][col] l >>= 1 r >>= 1 return res def update(self, ix, val, col): ix += self.n # set new value self.tree[ix][col] += val # move up while ix > 1: self.tree[ix >> 1][col] = self.tree[ix][col] + self.tree[ix ^ 1][col] ix >>= 1 input = fast2() n, a = int(input()), [int(x) for x in input().split()] tree, ans = order_tree(n), 0 mem = {i: j for j, i in enumerate(sorted(a))} for i in range(n - 1, -1, -1): cur = mem[a[i]] ans += tree.query(cur, 1) tree.update(cur, 1, 0) tree.update(cur, tree.query(cur, 0), 1) print(ans)
1298390400
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
3 seconds
["12", "39"]
18b5557b282ebf7288de50ab8cb51c60
NoteIn the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan if i1 &lt; i2 &lt; i3 &lt; ... &lt; ik and gcd(ai1, ai2, ..., aik) &gt; 1 . He calls the strength of that clan k·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans.Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7).Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.
Print one integer — the strength of John Snow's army modulo 1000000007 (109 + 7).
The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his soldiers.
standard output
standard input
Python 3
Python
2,200
train_012.jsonl
8d3584bf33569a7ff9aeafcfbca49a4e
256 megabytes
["3\n3 3 1", "4\n2 3 4 6"]
PASSED
(input()) a=list(map(int,input().split())) n,p=1000001,1000000007 cnt=[0]*n curr=1 for i in a: cnt[i]+=1 ans=[0]*n tot=0 for i in range(n-1,1,-1): k=sum(cnt[i::i]) if k>0: ans[i]=(k*pow(2,k-1,p)-sum(ans[i::i]))%p tot=(tot+i*ans[i])%p print(tot)
1502548500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["0.300000000000", "1.000000000000"]
23604db874ed5b7c007ea4a837bf9c88
NoteIn the first sample we need either win no tour or win the third one. If we win nothing we wouldn't perform well. So, we must to win the third tour. Other conditions will be satisfied in this case. Probability of wining the third tour is 0.3.In the second sample we win the only tour with probability 1.0, and go back home with bag for it.
One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've brought with you have space for no more than k huge prizes.Besides the fact that you want to take all the prizes home, you also want to perform well. You will consider your performance good if you win at least l tours.In fact, years of organizing contests proved to the organizers that transporting huge prizes is an issue for the participants. Alas, no one has ever invented a spell that would shrink the prizes... So, here's the solution: for some tours the winner gets a bag instead of a huge prize. Each bag is characterized by number ai — the number of huge prizes that will fit into it.You already know the subject of all tours, so you can estimate the probability pi of winning the i-th tour. You cannot skip the tour under any circumstances.Find the probability that you will perform well on the contest and will be able to take all won prizes home (that is, that you will be able to fit all the huge prizes that you won into the bags that you either won or brought from home).
Print a single real number — the answer to the problem. The answer will be accepted if the absolute or relative error does not exceed 10 - 6.
The first line contains three integers n, l, k (1 ≤ n ≤ 200, 0 ≤ l, k ≤ 200) — the number of tours, the minimum number of tours to win, and the number of prizes that you can fit in the bags brought from home, correspondingly. The second line contains n space-separated integers, pi (0 ≤ pi ≤ 100) — the probability to win the i-th tour, in percents. The third line contains n space-separated integers, ai (1 ≤ ai ≤ 200) — the capacity of the bag that will be awarded to you for winning the i-th tour, or else -1, if the prize for the i-th tour is a huge prize and not a bag.
standard output
standard input
Python 3
Python
1,800
train_017.jsonl
f2ea202cdad0372ba7254ab303f9e2cc
256 megabytes
["3 1 0\n10 20 30\n-1 -1 2", "1 1 1\n100\n123"]
PASSED
from collections import * f = lambda: list(map(int, input().split())) n, l, a = f() p, s = f(), f() m = s.count(-1) x = {(0, min(a, m)): 1} d = [1] for p, s in zip(p, s): p /= 100 if s > 0: y = defaultdict(int) for (k, a), q in x.items(): y[(k, a)] += q - q * p y[(min(l, k + 1), min(m, a + s))] += q * p x = y else: d = [(a - b) * p + b for a, b in zip([0] + d, d + [0])] y = [[0] * (m + 2) for i in range(n - m + 2)] for k, a in x: if k + a >= l: y[k][a] = x[(k, a)] for k in range(n - m, -1, -1): for a in range(m, -1, -1): y[k][a - 1] += y[k][a] y[k][a] += y[k + 1][a] print(sum(y[max(0, l - k)][k] * p for k, p in enumerate(d) if l - k <= n - m))
1332860400
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["499122179", "0", "499122177"]
2df2d5368f467e0427b1f6f57192e2ee
NoteIn the first example two resulting valid permutations are possible: $$$[3, 1, 2]$$$ — $$$2$$$ inversions; $$$[3, 2, 1]$$$ — $$$3$$$ inversions. The expected value is $$$\frac{2 \cdot 1 + 3 \cdot 1}{2} = 2.5$$$.In the second example no $$$-1$$$ are present, thus the only valid permutation is possible — the given one. It has $$$0$$$ inversions.In the third example there are two resulting valid permutations — one with $$$0$$$ inversions and one with $$$1$$$ inversion.
A permutation of size $$$n$$$ is an array of size $$$n$$$ such that each integer from $$$1$$$ to $$$n$$$ occurs exactly once in this array. An inversion in a permutation $$$p$$$ is a pair of indices $$$(i, j)$$$ such that $$$i &gt; j$$$ and $$$a_i &lt; a_j$$$. For example, a permutation $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(2, 1)$$$, $$$(3, 1)$$$, $$$(4, 1)$$$, $$$(4, 3)$$$.You are given a permutation $$$p$$$ of size $$$n$$$. However, the numbers on some positions are replaced by $$$-1$$$. Let the valid permutation be such a replacement of $$$-1$$$ in this sequence back to numbers from $$$1$$$ to $$$n$$$ in such a way that the resulting sequence is a permutation of size $$$n$$$.The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.Calculate the expected total number of inversions in the resulting valid permutation.It can be shown that it is in the form of $$$\frac{P}{Q}$$$ where $$$P$$$ and $$$Q$$$ are non-negative integers and $$$Q \ne 0$$$. Report the value of $$$P \cdot Q^{-1} \pmod {998244353}$$$.
Print a single integer — the expected total number of inversions in the resulting valid permutation. It can be shown that it is in the form of $$$\frac{P}{Q}$$$ where $$$P$$$ and $$$Q$$$ are non-negative integers and $$$Q \ne 0$$$. Report the value of $$$P \cdot Q^{-1} \pmod {998244353}$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the sequence. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$-1 \le p_i \le n$$$, $$$p_i \ne 0$$$) — the initial sequence. It is guaranteed that all elements not equal to $$$-1$$$ are pairwise distinct.
standard output
standard input
Python 3
Python
2,300
train_049.jsonl
a7651e4321d0aa91c3ac029385913b22
256 megabytes
["3\n3 -1 -1", "2\n1 2", "2\n-1 -1"]
PASSED
def merge(a,b): inda=0 indb=0 lena=len(a) lenb=len(b) d=[a[-1]+b[-1]+1000] a+=d b+=d c=[] inversions=0 for i in range(lena+lenb): if a[inda]<b[indb]: c.append(a[inda]) inda+=1 else: c.append(b[indb]) indb+=1 inversions+=lena-inda return((c,inversions)) def mergesort(a): if len(a)<=1: return((a,0)) split=len(a)//2 b=a[:split] c=a[split:] d=mergesort(b) e=mergesort(c) f=merge(d[0],e[0]) return((f[0],f[1]+d[1]+e[1])) n=int(input()) a=list(map(int,input().split())) b=[] for guy in a: if guy!=-1: b.append(guy) invs=mergesort(b)[1] negs=len(a)-len(b) pairs=(negs*(negs-1))//2 used=[0]*n for guy in a: if guy!=-1: used[guy-1]+=1 unused=[0] for i in range(n-1): unused.append(unused[-1]+1-used[i]) negsseen=0 mix=0 for i in range(n): if a[i]==-1: negsseen+=1 else: mix+=unused[a[i]-1]*(negs-negsseen)+negsseen*(negs-unused[a[i]-1]) num=invs*2*negs+pairs*negs+mix*2 denom=2*negs if negs==0: print(invs%998244353) else: for i in range(denom): if (998244353*i+1)%denom==0: inv=(998244353*i+1)//denom break print((num*inv)%998244353)
1546007700
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
1 second
["6\n1 5 3 6 2 4", "2\n1 3"]
a52ceb8a894809b570cbb74dc5ef76e1
null
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other. In the second line print k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |ai - ai + 1| ≠ 1 for all i from 1 to k - 1. If there are several possible answers, output any of them.
A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.
standard output
standard input
Python 2
Python
1,100
train_016.jsonl
5a7fb39e1ee0851c213f8b8206fa1b1c
256 megabytes
["6", "3"]
PASSED
n = input() if n == 1: print 1 print 1 elif n == 2: print 1 print 1 elif n == 3: print 2 print 1, 3 elif n == 4: print 4 print 2, 4, 1, 3 else: print n B = [] for i in range(1, n + 1, 2): B.append(i) for i in range(2, n + 1, 2): B.append(i) for i in xrange(n): print B[i],
1428854400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["NO", "YES", "NO", "YES"]
b1ef19d7027dc82d76859d64a6f43439
null
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.
If Vasya can write the given anonymous letter, print YES, otherwise print NO
The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.
standard output
standard input
Python 3
Python
1,100
train_005.jsonl
e12f9ee8fd0abf259bb9bd8432f45b5d
256 megabytes
["Instead of dogging Your footsteps it disappears but you dont notice anything\nwhere is your dog", "Instead of dogging Your footsteps it disappears but you dont notice anything\nYour dog is upstears", "Instead of dogging your footsteps it disappears but you dont notice anything\nYour dog is upstears", "abcdefg hijk\nk j i h g f e d c b a"]
PASSED
import collections l=list(input()) p=list(input()) #print(p) #print(l) cl=collections.Counter(l) pl=collections.Counter(p) #print(cl) #print(pl) plk=list(pl.keys()) #print(plk) if ' ' in plk: plk.remove(' ') else: pass n=len(plk) i=0 er=0 #print(cl['s']) while i<n: h=plk[i] t=cl[h] q=pl[h] #print(t) #print(q) if t>=q: er+=1 else: pass i+=1 #print(n) #print(er) if er==n: print('YES') else: print('NO')
1291046400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1\n24\n300\n...5679392764\n111"]
b235128854812b3911f60e5007e451d7
null
A Russian space traveller Alisa Selezneva, like any other schoolgirl of the late 21 century, is interested in science. She has recently visited the MIT (Moscow Institute of Time), where its chairman and the co-inventor of the time machine academician Petrov told her about the construction of a time machine.During the demonstration of the time machine performance Alisa noticed that the machine does not have high speed and the girl got interested in the reason for such disadvantage. As it turns out on closer examination, one of the problems that should be solved for the time machine isn't solved by an optimal algorithm. If you find a way to solve this problem optimally, the time machine will run faster and use less energy.A task that none of the staff can solve optimally is as follows. There exists a matrix a, which is filled by the following rule:The cells are consecutive positive integers, starting with one. Besides, ai, j &lt; at, k (i, j, t, k ≥ 1), if: max(i, j) &lt; max(t, k); max(i, j) = max(t, k) and j &lt; k; max(i, j) = max(t, k), j = k and i &gt; t. So, after the first 36 numbers are inserted, matrix a will look as follows: To solve the problem, you should learn to find rather quickly for the given values of x1, y1, x2 and y2 (x1 ≤ x2, y1 ≤ y2) the meaning of expression:As the meaning of this expression can be large enough, it is sufficient to know only the last 10 digits of the sought value.So, no one in MTI can solve the given task. Alice was brave enough to use the time machine and travel the past to help you.Your task is to write a program that uses the given values x1, y1, x2 and y2 finds the last 10 digits of the given expression.
For each query print the meaning of the expression if it contains at most 10 characters. Otherwise, print three characters "." (without the quotes), and then ten last digits of the time expression. Print the answer to each query on a single line. Follow the format, given in the sample as closely as possible.
The first input line contains a single integer t (1 ≤ t ≤ 105) — the number of test sets for which you should solve the problem. Each of the next t lines contains the description of a test — four positive integers x1, y1, x2 and y2 (1 ≤ x1 ≤ x2 ≤ 109, 1 ≤ y1 ≤ y2 ≤ 109), separated by spaces.
standard output
standard input
Python 2
Python
2,600
train_012.jsonl
078fd775f24ee84a923552d4fc50e7ce
256 megabytes
["5\n1 1 1 1\n2 2 3 3\n2 3 5 6\n100 87 288 2002\n4 2 5 4"]
PASSED
def cal(x0, y0, x1, y1): mini = min(x1, y1) maxi = max(x0, y0) res = 0 res += (x1 * (x1 + 1) * (x1 * 2 + 1) * (y1 - (y0 - 1)) - mini * (mini + 1) * (mini * 2 + 1) * y1 + (maxi - 1) * maxi * (maxi * 2 - 1) * (y0 - 1) + (y1 - 1) * y1 * (y1 * 2 - 1) * (x1 - (x0 - 1)) - (mini - 1) * mini * (mini * 2 - 1) * x1 + (maxi - 2) * (maxi - 1) * (maxi * 2 - 3) * (x0 - 1)) / 3 res += (((y0 - 2) * (y0 - 1) * (x1 - maxi + 1) - (y1 - 1) * y1 * (x1 - mini)) + ((y1 - mini) * x1 * (x1 + 1) - (y1 - maxi + 1) * (x0 - 1) * x0)) mini = mini * mini maxi = (maxi - 1) * (maxi - 1) res += (mini * (mini + 1) - maxi * (maxi + 1)) return res / 2 if __name__ == "__main__": T = int(raw_input()) for step in xrange(T): """ if step == 33333 and T == 100000: break """ x0, y0, x1, y1 = map(int, raw_input().split(' ')) ans = -1 if max(x0, y0) <= min(x1, y1): ans = cal(x0, y0, x1, y1) else: MAX = max(x1, y1) if x1 != MAX: maxi = max(x0, y0) ans = 0 ans += (MAX * (MAX + 1) * (MAX * 2 + 1) * ( - (y0 - 1)) + (maxi - 1) * maxi * (maxi * 2 - 1) * (y0 - 1) + (MAX - 1) * MAX * (MAX * 2 - 1) * (- (x0 - 1)) + (maxi - 2) * (maxi - 1) * (maxi * 2 - 3) * (x0 - 1)) / 3 ans += ((y0 - 2) * (y0 - 1) * (MAX - maxi + 1)) - (MAX - maxi + 1) * (x0 - 1) * x0 mini = MAX * MAX maxi = (maxi - 1) * (maxi - 1) ans += (mini * (mini + 1) - maxi * (maxi + 1)) # ans = cal(x0, y0, MAX, MAX) maxi = max((x1 + 1), y0) ans -= (MAX * (MAX + 1) * (MAX * 2 + 1) * ( - (y0 - 1)) + (maxi - 1) * maxi * (maxi * 2 - 1) * (y0 - 1) + (MAX - 1) * MAX * (MAX * 2 - 1) * (- ((x1 + 1) - 1)) + (maxi - 2) * (maxi - 1) * (maxi * 2 - 3) * ((x1 + 1) - 1)) / 3 ans -= ((y0 - 2) * (y0 - 1) * (MAX - maxi + 1)) - (MAX - maxi + 1) * ((x1 + 1) - 1) * (x1 + 1) mini = MAX * MAX maxi = (maxi - 1) * (maxi - 1) ans -= (mini * (mini + 1) - maxi * (maxi + 1)) ans /= 2 # ans -= cal(x1 + 1, y0, MAX, MAX) else: maxi = max(x0, y0) ans = 0 ans += (MAX * (MAX + 1) * (MAX * 2 + 1) * ( - (y0 - 1)) + (maxi - 1) * maxi * (maxi * 2 - 1) * (y0 - 1) + (MAX - 1) * MAX * (MAX * 2 - 1) * (- (x0 - 1)) + (maxi - 2) * (maxi - 1) * (maxi * 2 - 3) * (x0 - 1)) / 3 ans += ((y0 - 2) * (y0 - 1) * (MAX - maxi + 1)) - (MAX - maxi + 1) * (x0 - 1) * x0 mini = MAX * MAX maxi = (maxi - 1) * (maxi - 1) ans += (mini * (mini + 1) - maxi * (maxi + 1)) # ans = cal(x0, y0, MAX, MAX) maxi = max(x0, (y1 + 1)) ans -= (MAX * (MAX + 1) * (MAX * 2 + 1) * ( - ((y1 + 1) - 1)) + (maxi - 1) * maxi * (maxi * 2 - 1) * ((y1 + 1) - 1) + (MAX - 1) * MAX * (MAX * 2 - 1) * (- (x0 - 1)) + (maxi - 2) * (maxi - 1) * (maxi * 2 - 3) * (x0 - 1)) / 3 ans -= (((y1 + 1) - 2) * ((y1 + 1) - 1) * (MAX - maxi + 1)) - (MAX - maxi + 1) * (x0 - 1) * x0 mini = MAX * MAX maxi = (maxi - 1) * (maxi - 1) ans -= (mini * (mini + 1) - maxi * (maxi + 1)) ans /= 2 # ans -= cal(x0, y1 + 1, MAX, MAX) mod = 10000000000 if mod <= ans: print "..." + str(ans)[-10:] else: print ans
1353857400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n5 8\n2\n1 11\n1\n9\n0\n1\n1\n2\n1 2\n1\n2\n2\n1 3\n1\n2\n2\n2 3\n1\n3\n1\n3\n2\n3 4\n1\n4"]
d0de903a70f8a18589eba60b1f2dd98e
NoteIn the first test case for the first query you can remove the rods numbered $$$5$$$ and $$$8$$$, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero.In the second test case: For the first query, we can remove the rods numbered $$$1$$$ and $$$11$$$, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. For the second query we can remove the rod numbered $$$9$$$, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. For the third query we can not remove the rods at all.
This is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine.The main element of this machine are $$$n$$$ rods arranged along one straight line and numbered from $$$1$$$ to $$$n$$$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $$$1$$$ or $$$-1$$$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.More formally, the rods can be represented as an array of $$$n$$$ numbers characterizing the charge: either $$$1$$$ or $$$-1$$$. Then the condition must hold: $$$a_1 - a_2 + a_3 - a_4 + \ldots = 0$$$, or $$$\sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0$$$.Sparky charged all $$$n$$$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $$$q$$$ questions. In the $$$i$$$th question Sparky asks: if the machine consisted only of rods with numbers $$$l_i$$$ to $$$r_i$$$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Also Sparky wants to know the numbers of these rods. Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.Help your friends and answer all of Sparky's questions!
For each test case, print the answer in the following format: In the first line print a single integer $$$k$$$ — the minimal number of rods that can be removed. In the second line print $$$k$$$ numbers separated by a space — the numbers of rods to be removed. If there is more than one correct answer, you can print any.
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$) — the number of rods and the number of questions. The second line of each test case contains a non-empty string $$$s$$$ of length $$$n$$$, where the charge of the $$$i$$$-th rod is $$$1$$$ if $$$s_i$$$ is the "+" symbol, or $$$-1$$$ if $$$s_i$$$ is the "-" symbol. Each next line from the next $$$q$$$ lines contains two positive integers $$$l_i$$$ ans $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — numbers, describing Sparky's questions. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$. It is guaranteed that the sum of the answers (minimal number of rods that can be removed) over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
2,200
train_086.jsonl
a043d9e1d4632a0ab43333d2a5b7b5a9
512 megabytes
["3\n14 1\n+--++---++-++-\n1 14\n14 3\n+--++---+++---\n1 14\n6 12\n3 10\n4 10\n+-+-\n1 1\n1 2\n1 3\n1 4\n2 2\n2 3\n2 4\n3 3\n3 4\n4 4"]
PASSED
import sys from bisect import bisect_left ipt=sys.stdin.readline T=int(ipt()) for _ in range(T): n, q=map(int, ipt().split()) s=sys.stdin.readline().strip() a=[0 for i in range(n)] for i in range(n): if s[i]=='+': a[i]=-1 if i&1 else 1 else: a[i]=1 if i&1 else -1 b=[0 for i in range(n+1)] c=[] for i in range(1, n+1): b[i]=b[i-1]+a[i-1] for i in range(n): c.append(1000000*(b[i]+b[i+1])+i+1) c.sort() for i in range(q): l, r=map(int, ipt().split()) t=b[r]-b[l-1] if t==0: print(0) elif (l-r)&1: print(2) ll=(b[r-1]+b[l-1])*1000000+l t=bisect_left(c, ll) print(c[t]%1000000, r) else: print(1) ll=(b[r]+b[l-1])*1000000+l t=bisect_left(c, ll) print(c[t]%1000000)
1629988500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2", "3"]
e9f4582601a4296a53b77678589d09ef
NoteIn the first sample, one of the optimal p is [4, 3, 2, 1].
DZY loves planting, and he enjoys solving tree problems.DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every z.For every integer sequence p1, p2, ..., pn (1 ≤ pi ≤ n), DZY defines f(p) as . DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most xj times.Please, find the maximum possible f(p) under the described restrictions.
Print a single integer representing the answer.
The first line contains an integer n (1 ≤ n ≤ 3000). Each of the next n - 1 lines contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; 1 ≤ ci ≤ 10000), denoting an edge between ai and bi with length ci. It is guaranteed that these edges form a tree. Each of the next n lines describes an element of sequence x. The j-th line contains an integer xj (1 ≤ xj ≤ n).
standard output
standard input
Python 3
Python
2,700
train_038.jsonl
6ad40aae202ef155985c57e52078c11c
256 megabytes
["4\n1 2 1\n2 3 2\n3 4 3\n1\n1\n1\n1", "4\n1 2 1\n2 3 2\n3 4 3\n4\n4\n4\n4"]
PASSED
n = int(input()) edges = [[int(x) for x in input().split()] for i in range(n-1)] edges = sorted(edges) use_count = [0]+[int(input()) for i in range(n)] lo,hi = 0,10000 def getpar(par,u): if par[par[u]] == par[u]: return par[u] par[u] = getpar(par,par[u]) return par[u] def unite(par,sz,use,u,v): u = getpar(par,u) v = getpar(par,v) par[u] = v sz[v] += sz[u] use[v] += use[u] def solve(fp): par = [i for i in range(n+1)] sz = [1 for i in range(n+1)] use = [use_count[i] for i in range(n+1)] for edge in edges: if edge[2] < fp: unite(par,sz,use,edge[0],edge[1]) total_use = sum(use_count) for i in range(n+1): p = getpar(par,i) if(p == i): if(total_use - use[p] < sz[p]): return False return True while lo < hi: mid = (lo+hi+1)//2 if solve(mid): lo = mid else: hi = mid-1 print(lo)
1404651900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
4 seconds
["0\n1\n2\n4"]
5defa8c72eaa0b71d120752de71d0df2
NoteIn the first test case, we can apply the operation on each of the $$$4$$$s with $$$(p,q) = (2,2)$$$ and make the multiset $$$\{2,2,2,2,2,2,2\}$$$ with balance $$$\max(\{2,2,2,2,2,2,2\}) - \min(\{2,2,2,2,2,2,2\}) = 0$$$. It is obvious we cannot make this balance less than $$$0$$$.In the second test case, we can apply an operation on $$$12$$$ with $$$(p,q) = (3,4)$$$. After this our multiset will be $$$\{3,4,2,3\}$$$. We can make one more operation on $$$4$$$ with $$$(p,q) = (2,2)$$$, making the multiset $$$\{3,2,2,2,3\}$$$ with balance equal to $$$1$$$.In the third test case, we can apply an operation on $$$35$$$ with $$$(p,q) = (5,7)$$$. The final multiset is $$$\{6,5,7\}$$$ and has a balance equal to $$$7-5 = 2$$$.In the forth test case, we cannot apply any operation, so the balance is $$$5 - 1 = 4$$$.
Ibti was thinking about a good title for this problem that would fit the round theme (numerus ternarium). He immediately thought about the third derivative, but that was pretty lame so he decided to include the best band in the world — Three Days Grace.You are given a multiset $$$A$$$ with initial size $$$n$$$, whose elements are integers between $$$1$$$ and $$$m$$$. In one operation, do the following: select a value $$$x$$$ from the multiset $$$A$$$, then select two integers $$$p$$$ and $$$q$$$ such that $$$p, q &gt; 1$$$ and $$$p \cdot q = x$$$. Insert $$$p$$$ and $$$q$$$ to $$$A$$$, delete $$$x$$$ from $$$A$$$. Note that the size of the multiset $$$A$$$ increases by $$$1$$$ after each operation. We define the balance of the multiset $$$A$$$ as $$$\max(a_i) - \min(a_i)$$$. Find the minimum possible balance after performing any number (possible zero) of operations.
For each test case, print a single integer — the minimum possible balance.
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The second line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^6$$$, $$$1 \le m \le 5 \cdot 10^6$$$) — the initial size of the multiset, and the maximum value of an element. The third line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the elements in the initial multiset. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^6$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$5 \cdot 10^6$$$.
standard output
standard input
PyPy 3-64
Python
2,600
train_088.jsonl
c86b5418a41f764f89181ed96d035fba
256 megabytes
["4\n\n5 10\n\n2 4 2 4 2\n\n3 50\n\n12 2 3\n\n2 40\n\n6 35\n\n2 5\n\n1 5"]
PASSED
from sys import stdin input=lambda :stdin.readline()[:-1] def solve(): n,m=map(int,input().split()) a=list(set(map(int,input().split()))) n=len(a) exist=[0]*(m+1) for i in a: exist[i]=1 dp=list(range(m+1)) cnt=0 ans=10**9 mx_cnt=[0]*(m+1) mx=m for i in range(m,0,-1): if exist[i]: cnt+=1 mx_cnt[i]+=1 for j in range(i*i,m+1,i): y=dp[j//i] if y<dp[j]: if exist[j]: mx_cnt[dp[j]]-=1 mx_cnt[y]+=1 dp[j]=y if cnt==n: while mx_cnt[mx]==0: mx-=1 ans=min(ans,mx-i) print(ans) for _ in range(int(input())): solve()
1656945300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["2\n2\n2\n2\n1\n0"]
d34ffd75ef82111d1077db4b033d5195
null
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $$$n$$$ bosses in this tower, numbered from $$$1$$$ to $$$n$$$. The type of the $$$i$$$-th boss is $$$a_i$$$. If the $$$i$$$-th boss is easy then its type is $$$a_i = 0$$$, otherwise this boss is hard and its type is $$$a_i = 1$$$.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.For example: suppose $$$n = 8$$$, $$$a = [1, 0, 1, 1, 0, 1, 1, 1]$$$. Then the best course of action is the following: your friend kills two first bosses, using one skip point for the first boss; you kill the third and the fourth bosses; your friend kills the fifth boss; you kill the sixth and the seventh bosses; your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer $$$t$$$ independent test cases.
For each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.
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$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of bosses. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th boss. 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
1,500
train_006.jsonl
4230fc33b02c02feb394d87e9c7a851d
256 megabytes
["6\n8\n1 0 1 1 0 1 1 1\n5\n1 1 1 1 0\n7\n1 1 1 1 0 0 1\n6\n1 1 1 1 1 1\n1\n1\n1\n0"]
PASSED
for _ in range(int(input())): n=int(input()) arr=[int(el) for el in input().split()] him=[0]*(n+1) us=[0]*(n+1) for i in range(n-1,-1,-1): him[i]=us[i+1]+arr[i] if (i+2)<=n: him[i]=min(him[i],us[i+2]+arr[i]+arr[i+1]) us[i]=him[i+1] if (i+2)<=n: us[i]=min(us[i],him[i+2]) print(him[0])
1600094100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2\nabba", "0\nababab", "1\nba"]
8ad06ac90b258a8233e2a1cf51f68078
NoteIn the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'. In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.
Nikolay got a string $$$s$$$ of even length $$$n$$$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $$$1$$$ to $$$n$$$.He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.The prefix of string $$$s$$$ of length $$$l$$$ ($$$1 \le l \le n$$$) is a string $$$s[1..l]$$$.For example, for the string $$$s=$$$"abba" there are two prefixes of the even length. The first is $$$s[1\dots2]=$$$"ab" and the second $$$s[1\dots4]=$$$"abba". Both of them have the same number of 'a' and 'b'.Your task is to calculate the minimum number of operations Nikolay has to perform with the string $$$s$$$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.
In the first line print the minimum number of operations Nikolay has to perform with the string $$$s$$$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'. In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.
The first line of the input contains one even integer $$$n$$$ $$$(2 \le n \le 2\cdot10^{5})$$$ — the length of string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$, which consists only of lowercase Latin letters 'a' and 'b'.
standard output
standard input
PyPy 3
Python
800
train_005.jsonl
b438a19e66ae7d78c39b64d8aa713c87
256 megabytes
["4\nbbbb", "6\nababab", "2\naa"]
PASSED
n,a,b=int(input()),0,0 s=input() tot = 0 l=list(s) for i in range(len(s)): if s[i] == 'a':a+=1 else:b+=1 # print(s[i],a,b) if i&1: tot+=1 if a>b: a-=1 b+=1 # print(l) l[i]='b' # print(l,a,b,i) elif b>a: a+=1 b-=1 l[i]='a' # print(l) else:tot-=1 print(tot) print(''.join(l))
1569049500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["5", "10", "2"]
5099a9ae62e82441c496ac37d92e99e3
NoteConsider the first sample. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3. During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens: If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece. Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.
The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.
standard output
standard input
Python 2
Python
1,400
train_023.jsonl
735b45a7a26e046080985accc5b12f5e
256 megabytes
["5 6 3\n5 4 3 2 1", "5 6 3\n5 5 5 5 5", "5 6 3\n1 2 1 1 1"]
PASSED
n,h,k=map(int,raw_input().split()) l=map(int,raw_input().split()) ans=chk=0 for i in l: if chk+i<k: chk+=i elif chk+i<=h: chk+=i ans+=chk/k chk%=k else: ans+=chk/k chk%=k if chk+i>h: ans+=1 chk=i else: chk+=i ans+=chk/k if chk%k: ans+=1 print ans
1464798900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4\n888188", "0\n533", "3\n0000002223"]
cb082cbe9b34a45da851b6764bbc30c3
NoteIn the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188".The lexicographical comparison of strings is performed by the &lt; operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≤ i ≤ n), that xi &lt; yi, and for any j (1 ≤ j &lt; i) xj = yj. The strings compared in this problem will always have the length n.
A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.
On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one.
The first line contains two space-separated integers n and k (2 ≤ n ≤ 104, 2 ≤ k ≤ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits.
standard output
standard input
PyPy 3
Python
1,900
train_017.jsonl
3152cb7947285181debb688adc1aa8cd
256 megabytes
["6 5\n898196", "3 2\n533", "10 6\n0001112223"]
PASSED
n,k = map(int,input().split()) s = list(map(int, input())) e = list(enumerate(s)) min_cost = 9*n a=[9]*n for j in range(10): r = s[:] cost = 0 for x, y in sorted(e, key=lambda t : (abs(t[1] - j), -t[1], t[0]*(-1)**(j > t[1]) ))[:k]: r[x]=j cost += abs(y-j) if cost < min_cost : min_cost = cost a = r if min_cost == cost: a = min(a,r) print(min_cost) print (''.join(map(str,a)))
1317999600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["3", "0", "1"]
bf115b24d85a0581e709c012793b248b
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
standard output
standard input
PyPy 2
Python
1,600
train_014.jsonl
bde2909ab5ae8852bb330295d5846e42
256 megabytes
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
PASSED
from collections import Counter, defaultdict, deque import bisect from sys import stdin, stdout from itertools import repeat import math # sys.stdin = open('input') def inp(): return map(int, raw_input().split()) def inst(): return raw_input().strip() def main(): n, m = inp() da = inp() if n>2100: print 0 return ans = 1 for i in range(n): for j in range(i+1, n): # print da[i],da[j] ans *= abs(da[i]-da[j]) ans %= m print ans main()
1583246100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nNO\nYES"]
447c17cba953d6e2da50c242ac431ab4
NoteIn the test case of the example, $$$m=3, s=13, b=[3,1,4]$$$. You can append to $$$b$$$ the numbers $$$6,2,5$$$, the sum of which is $$$6+2+5=13$$$. Note that the final array will become $$$[3,1,4,6,2,5]$$$, which is a permutation.In the second test case of the example, $$$m=1, s=1, b=[1]$$$. You cannot append one or more numbers to $$$[1]$$$ such that their sum equals $$$1$$$ and the result is a permutation.In the third test case of the example, $$$m=3, s=3, b=[1,4,2]$$$. You can append the number $$$3$$$ to $$$b$$$. Note that the resulting array will be $$$[1,4,2,3]$$$, which is a permutation.
A sequence of $$$n$$$ numbers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences [$$$3, 1, 4, 2$$$], [$$$1$$$] and [$$$2,1$$$] are permutations, but [$$$1,2,1$$$], [$$$0,1$$$] and [$$$1,3,4$$$] — are not.Polycarp lost his favorite permutation and found only some of its elements — the numbers $$$b_1, b_2, \dots b_m$$$. He is sure that the sum of the lost elements equals $$$s$$$.Determine whether one or more numbers can be appended to the given sequence $$$b_1, b_2, \dots b_m$$$ such that the sum of the added numbers equals $$$s$$$, and the resulting new array is a permutation?
Print $$$t$$$ lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array $$$b$$$, that their sum equals $$$s$$$ and the result will be a permutation. Output NO otherwise. You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer).
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases. Then the descriptions of the test cases follow. The first line of each test set contains two integers $$$m$$$ and $$$s$$$ ($$$1 \le m \le 50$$$, $$$1 \le s \le 1000$$$)—-the number of found elements and the sum of forgotten numbers. The second line of each test set contains $$$m$$$ different integers $$$b_1, b_2 \dots b_m$$$ ($$$1 \le b_i \le 50$$$) — the elements Polycarp managed to find.
standard output
standard input
Python 3
Python
800
train_086.jsonl
fc7993bdf580184073f9227a0415db02
256 megabytes
["5\n\n3 13\n\n3 1 4\n\n1 1\n\n1\n\n3 3\n\n1 4 2\n\n2 1\n\n4 3\n\n5 6\n\n1 2 3 4 5"]
PASSED
t=int(input()) for i in range(t): u=input().split() v=input().split() u=[int(i) for i in u] v=[int(t) for t in v] sum=u[1] mi=1 ma=max(v) cursum=0 missing=[] ii=None for i in range(mi,ma): if cursum==sum: if len(v)==ma: ii=True break if i not in v: missing.append(i) v.append(i) cursum+=i if ii: print('YES') else: iu=True while cursum!=sum and len(set(v))==len(v): if cursum>sum: iu=False print('NO') break missing.append(ma+1) v.append(ma+1) ma=missing[-1] cursum+=ma if iu: print('YES')
1668782100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["6", "6", "3"]
9693f60fc65065d00a1899df999405fe
NoteLet $$$s[l; r]$$$ be the substring of $$$s$$$ from the position $$$l$$$ to the position $$$r$$$ inclusive.Then in the first example you can remove the following substrings: $$$s[1; 2]$$$; $$$s[1; 3]$$$; $$$s[1; 4]$$$; $$$s[2; 2]$$$; $$$s[2; 3]$$$; $$$s[2; 4]$$$. In the second example you can remove the following substrings: $$$s[1; 4]$$$; $$$s[1; 5]$$$; $$$s[1; 6]$$$; $$$s[1; 7]$$$; $$$s[2; 7]$$$; $$$s[3; 7]$$$. In the third example you can remove the following substrings: $$$s[1; 1]$$$; $$$s[1; 2]$$$; $$$s[2; 2]$$$.
You are given a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in $$$s$$$.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo $$$998244353$$$.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Print one integer — the number of ways modulo $$$998244353$$$ to remove exactly one substring from $$$s$$$ in such way that all remaining characters are equal.
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in $$$s$$$.
standard output
standard input
Python 3
Python
1,300
train_009.jsonl
b5c2c26388616ec2aaed2b2a56281f36
256 megabytes
["4\nabaa", "7\naacdeee", "2\naz"]
PASSED
n=int(input()) s=input() sf=s[0] sl=s[-1] f=0 l=0 ans = 0 if(s.count(sf)!=n): for i in range(n): if(s[i]==sf): ans+=1 f+=1 else: ans+=1 break for i in range(n)[::-1]: if(s[i]==sl): ans+=1 l+=1 else: ans+=1 break ans-=1 if(sf==sl): ans+=f*l else: ans = n*(n+1) ans //=2 ans+=1 print(ans%998244353)
1546007700
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
2 seconds
["NO", "YES", "NO"]
faf79a485fe06f3081befde45471a569
NoteIn the second example input, the initial statuses of the doors are [1, 0, 1] (0 means locked, 1 — unlocked).After toggling switch 3, we get [0, 0, 0] that means all doors are locked.Then, after toggling switch 1, we get [1, 1, 1] that means all doors are unlocked.It can be seen that for the first and for the third example inputs it is not possible to make all doors unlocked.
Moriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are m switches. Each switch control doors of some rooms, but each door is controlled by exactly two switches.You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch 1, which was connected to room 1, 2 and 3 which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked.You need to tell Sherlock, if there exists a way to unlock all doors at the same time.
Output "YES" without quotes, if it is possible to open all doors at the same time, otherwise output "NO" without quotes.
First line of input contains two integers n and m (2 ≤ n ≤ 105, 2 ≤ m ≤ 105) — the number of rooms and the number of switches. Next line contains n space-separated integers r1, r2, ..., rn (0 ≤ ri ≤ 1) which tell the status of room doors. The i-th room is locked if ri = 0, otherwise it is unlocked. The i-th of next m lines contains an integer xi (0 ≤ xi ≤ n) followed by xi distinct integers separated by space, denoting the number of rooms controlled by the i-th switch followed by the room numbers that this switch controls. It is guaranteed that the room numbers are in the range from 1 to n. It is guaranteed that each door is controlled by exactly two switches.
standard output
standard input
PyPy 3
Python
2,000
train_008.jsonl
bb8667f262d39ca5ad354cb351f83ef3
256 megabytes
["3 3\n1 0 1\n2 1 3\n2 1 2\n2 2 3", "3 3\n1 0 1\n3 1 2 3\n1 2\n2 1 3", "3 3\n1 0 1\n3 1 2 3\n2 1 2\n1 3"]
PASSED
import sys from math import inf time = 0 cc = 0 l = {} d = {} f = {} conn_comp = {} on_stack = {} stack = [] color = [] def tarjan(graph): global l global d global f global pi global stack global on_stack l = {key : inf for key in graph} d = {key : -1 for key in graph} f = {key : -1 for key in graph} conn_comp = {key : -1 for key in graph} on_stack = {key : False for key in graph} for i in graph.keys(): if d[i] == -1: strongconnect(graph, i) def strongconnect(graph, v): global time global cc stack.append(v) on_stack[v] = True time += 1 d[v] = time for i in graph[v]: if d[i] == -1: strongconnect(graph, i) l[v] = min(l[v], l[i]) if on_stack[i]: l[v] = min(l[v], d[i]) if l[v] == d[v]: cc += 1 w = stack.pop() while w != v: conn_comp[w] = cc on_stack[w] = False w = stack.pop() conn_comp[v] = cc on_stack[v] = False def read(): n,m = map(int, sys.stdin.readline().split()) status = list(map(int, sys.stdin.readline().split())) doors_switch = [[] for i in range(n)] for i in range(m): temp = list(map(int, sys.stdin.readline().split())) for j in range (1,len(temp)): door = temp[j] doors_switch[door-1].append(i) return m, status, doors_switch def build_graph_scc(): m, status, doors_switch = read() graph = {i : set() for i in range(2*m)} for i in range (len(doors_switch)): switch_1, switch_2 = tuple(doors_switch[i]) if status[i]: graph[2*switch_1].add(2*switch_2) graph[2*switch_2].add(2*switch_1) graph[2*switch_1 + 1].add(2*switch_2 + 1) graph[2*switch_2 + 1].add(2*switch_1 + 1) else: graph[2*switch_1].add(2*switch_2 + 1) graph[2*switch_2].add(2*switch_1 + 1) graph[2*switch_1 + 1].add(2*switch_2) graph[2*switch_2 + 1].add(2*switch_1) return graph def build_graph_bfs(): m, status, doors_switch = read() g = [[] for i in range(m)] global color color = [-1] * m for i in range(len(status)): switch_1, switch_2 = tuple(doors_switch[i]) g[switch_1].append((switch_2, 1 - status[i])) g[switch_2].append((switch_1, 1 - status[i])) return g def bfs_bipartite(graph, v): color[v] = 0 q = [v] j = 0 while j < len(q): v = q[j] for w,st in graph[v]: if color[w] == -1: color[w] = color[v]^st q.append(w) else: if color[w] != color[v]^st: return False j+=1 return True def main(): # graph = build_graph_scc() # tarjan(graph) # for i in range(0, len(conn_comp), 2): # if conn_comp[i] == conn_comp[i+1]: # print("NO") # return # print("YES") graph = build_graph_bfs() for i in range(len(graph)): if color[i] == -1 and not bfs_bipartite(graph, i): print("NO") return print("YES") main()
1487861100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["4", "2"]
2fc19c3c9604e746a17a63758060c5d7
NoteIn the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
A tree is a connected graph that doesn't contain any cycles.The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
standard output
standard input
Python 3
Python
1,800
train_024.jsonl
d743fe195ea0d3d96e5a6a9db0797781
512 megabytes
["5 2\n1 2\n2 3\n3 4\n2 5", "5 3\n1 2\n2 3\n3 4\n4 5"]
PASSED
n, k = map(int, input().split()) t, q = [[] for i in range(n + 1)], [1] for j in range(n - 1): a, b = map(int, input().split()) t[a].append(b) t[b].append(a) for x in q: for y in t[x]: t[y].remove(x) q.extend(t[x]) q.reverse() a, s = {}, 0 for x in q: a[x] = [1] u = len(a[x]) for y in t[x]: v = len(a[y]) for d in range(max(0, k - u), v): s += a[y][d] * a[x][k - d - 1] if v >= u: for d in range(u - 1): a[x][d + 1] += a[y][d] a[x] += a[y][u - 1: ] u = v + 1 else: for d in range(0, v): a[x][d + 1] += a[y][d] if u > k: a[x].pop() print(s)
1331478300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["1", "6", "4", "-1"]
6c5cf702d85ff25cf9e7bfd16534197d
NoteIn the first test case, the optimal strategy is as follows: Red chooses to color the subtrees of nodes $$$2$$$ and $$$3$$$. Blue chooses to color the subtree of node $$$4$$$. At the end of this process, nodes $$$2$$$ and $$$3$$$ are red, node $$$4$$$ is blue, and node $$$1$$$ is white. The score of the game is $$$1 \cdot (2 - 1) = 1$$$.In the second test case, the optimal strategy is as follows: Red chooses to color the subtree of node $$$4$$$. This colors both nodes $$$4$$$ and $$$5$$$. Blue does not have any options, so nothing is colored blue. At the end of this process, nodes $$$4$$$ and $$$5$$$ are red, and nodes $$$1$$$, $$$2$$$ and $$$3$$$ are white. The score of the game is $$$3 \cdot (2 - 0) = 6$$$.For the third test case: The score of the game is $$$4 \cdot (2 - 1) = 4$$$.
Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.The game works as follows: there is a tree of size $$$n$$$, rooted at node $$$1$$$, where each node is initially white. Red and Blue get one turn each. Red goes first. In Red's turn, he can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree red. However, to make the game fair, Red is only allowed to color $$$k$$$ nodes of the tree. In other words, after Red's turn, at most $$$k$$$ of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon. Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let $$$w$$$ be the number of white nodes, $$$r$$$ be the number of red nodes, and $$$b$$$ be the number of blue nodes. The score of the game is $$$w \cdot (r - b)$$$.Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?
Print one integer — the resulting score if both Red and Blue play optimally.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — the number of vertices in the tree and the maximum number of red nodes. Next $$$n - 1$$$ lines contains description of edges. The $$$i$$$-th line contains two space separated integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the $$$i$$$-th edge of the tree. It's guaranteed that given edges form a tree.
standard output
standard input
PyPy 3
Python
2,400
train_100.jsonl
535b2792a219d2a75a8872e852b573ca
256 megabytes
["4 2\n1 2\n1 3\n1 4", "5 2\n1 2\n2 3\n3 4\n4 5", "7 2\n1 2\n1 3\n4 2\n3 5\n6 3\n6 7", "4 1\n1 2\n1 3\n1 4"]
PASSED
import sys input = sys.stdin.buffer.readline n, k = [*map(int, input().split())] d = [[] for i in range(n)] p, h, l, v = [0]*n, [-1]*n, [0]*n, [0]*n for _ in range(n-1): a, b = [int(i)-1 for i in input().split()] d[a].append(b) d[b].append(a) q, p[0] = [0], -1 leaves = [] while q: q1 = [] for i in q: for j in d[i]: if j != p[i]: q1.append(j) p[j] = i if len(d[j]) == 1: leaves.append(j) q = q1 for i in leaves[::-1]: c, x = 0, i while x != -1 and h[x] < c: h[x] = c; c+=1; l[x]=i; x=p[x]; t = sorted(list(range(n)), key=lambda x: h[x], reverse=True) r = nb = 0 for i in t: if not v[i]: r += 1 nb += h[i]+1 v[i] = 1 x = l[i] while not v[x]: v[x] = 1; x = p[x] if r == k: break rr = max((nb-i)*(i+nb-n) for i in range(r, k+1)) rl = min((nb-k+i)*(k+nb-n+i) for i in range(max(n-nb-k+1,1))) print(rr if n-nb < k else rl)
1640356500
[ "math", "games", "trees", "graphs" ]
[ 1, 0, 1, 1, 0, 0, 0, 1 ]
3 seconds
["1 1 0 1 6 -1 -1 -1"]
ab89b5642465e632547fb57b9895beb6
NoteFor $$$k = 0$$$, to make the string $$$a$$$ have no occurrence of 101, you can do one character change as follows.100101011 $$$\rightarrow$$$ 100100011For $$$k = 1$$$, you can also change a single character.100101011 $$$\rightarrow$$$ 100001011For $$$k = 2$$$, no changes are needed.
The Winter holiday will be here soon. Mr. Chanek wants to decorate his house's wall with ornaments. The wall can be represented as a binary string $$$a$$$ of length $$$n$$$. His favorite nephew has another binary string $$$b$$$ of length $$$m$$$ ($$$m \leq n$$$).Mr. Chanek's nephew loves the non-negative integer $$$k$$$. His nephew wants exactly $$$k$$$ occurrences of $$$b$$$ as substrings in $$$a$$$. However, Mr. Chanek does not know the value of $$$k$$$. So, for each $$$k$$$ ($$$0 \leq k \leq n - m + 1$$$), find the minimum number of elements in $$$a$$$ that have to be changed such that there are exactly $$$k$$$ occurrences of $$$b$$$ in $$$a$$$.A string $$$s$$$ occurs exactly $$$k$$$ times in $$$t$$$ if there are exactly $$$k$$$ different pairs $$$(p,q)$$$ such that we can obtain $$$s$$$ by deleting $$$p$$$ characters from the beginning and $$$q$$$ characters from the end of $$$t$$$.
Output $$$n - m + 2$$$ integers — the $$$(k+1)$$$-th integer denotes the minimal number of elements in $$$a$$$ that have to be changed so there are exactly $$$k$$$ occurrences of $$$b$$$ as a substring in $$$a$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq m \leq n \leq 500$$$) — size of the binary string $$$a$$$ and $$$b$$$ respectively. The second line contains a binary string $$$a$$$ of length $$$n$$$. The third line contains a binary string $$$b$$$ of length $$$m$$$.
standard output
standard input
PyPy 3
Python
2,200
train_102.jsonl
ff71665530d2b690ed550e27d5f5aeb7
512 megabytes
["9 3\n100101011\n101"]
PASSED
def main(): n, m = readIntArr() a = input() b = input() maxCnt = n - m + 1 depthTxn = [[-1, -1] for _ in range(m + 1)] # depthTxn[currentDepth][0 or 1] = new maximum depth def getMaxDepth(c): # c : xxxxx # b : yyyyy # depth <-> for depth in range(m, -1, -1): if len(c) < depth: continue if depth == 0: c2 = '' else: c2 = c[-depth:] b2 = b[:depth] # print('c:{} depth:{} c2:{} b2:{}'.format(c, depth,c2,b2)) if c2 == b2: return depth for currDepth in range(m + 1): c = b[:currDepth] for i in range(2): c2 = c + str(i) # print('currDepth:{} c2:{}'.format(currDepth, c2)) depthTxn[currDepth][i] = getMaxDepth(c2) # print(depthTxn) dp = [[[505 for _ in range(maxCnt + 1)] for __ in range(m + 1)] for ___ in range(n)] # dp[i][depth][cnts] for i in range(n): for prevDepth in range(m + 1): if prevDepth > i: continue for c in range(2): add = 0 if str(c) != a[i]: add = 1 currDepth = depthTxn[prevDepth][c] for cnts in range(maxCnt): if i - 1 >= 0: prevVal = dp[i-1][prevDepth][cnts] else: if cnts == 0: prevVal = 0 else: prevVal = 505 if prevDepth == m: dp[i][currDepth][cnts+1] = min(dp[i][currDepth][cnts+1], prevVal + add) else: dp[i][currDepth][cnts] = min(dp[i][currDepth][cnts], prevVal + add) ans = [505]* (maxCnt + 1) for cnts in range(maxCnt + 1): for depth in range(m): ans[cnts] = min(ans[cnts], dp[n-1][depth][cnts]) if cnts >= 1: ans[cnts] = min(ans[cnts], dp[n-1][m][cnts-1]) for i in range(maxCnt + 1): if ans[i] == 505: ans[i] = -1 oneLineArrayPrint(ans) # print(dp) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(i,j,k): print('! {} {} {}'.format(i,j,k)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil import math # from math import floor,ceil # for Python2 for _abc in range(1): main()
1633181700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n1 2", "3\n1 3 4"]
5c64671081f9f5332d0ad57503091a54
null
Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1, a2, ..., an. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute.
If Valera can't win the dispute print in the first line -1. Otherwise, print in the first line integer k (0 ≤ k ≤ n). In the second line print k distinct space-separated integers — the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order. If there exists multiple answers, you are allowed to print any of them.
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105), that denote the number of counters Valera has and the number of pairs of counters connected by wires. Each of the following m lines contains two space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that mean that counters with numbers ui and vi are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input. The last line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 105), where ai is the value that Ignat choose for the i-th counter.
standard output
standard input
Python 2
Python
2,100
train_018.jsonl
c8561010c7952d253b787470b827a6a0
256 megabytes
["5 5\n2 3\n4 1\n1 5\n5 3\n2 1\n1 1 2 0 2", "4 2\n1 2\n3 4\n0 0 0 0"]
PASSED
def main(): n, m = map(int, raw_input().split()) data = {} for pos in xrange(n): data[pos] = [pos] for i in xrange(m): a, b = map(int, raw_input().split()) a, b = a - 1, b - 1 data[a].append(b) data[b].append(a) est = [0 for i in xrange(n)] ar = map(int, raw_input().split()) results = set() queue = set([i for i, x in enumerate(ar) if x == 0]) seen = set() while len(queue): pos = queue.pop() seen.add(pos) results.add(pos) for i in data[pos]: est[i] += 1 if i in queue: queue.remove(i) if est[i] == ar[i] and i not in seen: queue.add(i) for i in xrange(n): if est[i] == ar[i]: print -1 return print len(results) results = [x + 1 for x in results] print ' '.join(map(str, results)) if __name__ == '__main__': main()
1352647800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["14 0", "1995 1995"]
c19afaa6c46cd361e0e5ccee61f6f520
null
You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj.
On a single line output the coordinates of Mj, space separated.
On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000.
standard output
standard input
Python 2
Python
1,800
train_007.jsonl
5888d6e920262cae6ff75cf6e79c8617
256 megabytes
["3 4\n0 0\n1 1\n2 3\n-5 3", "3 1\n5 5\n1000 1000\n-1000 1000\n3 100"]
PASSED
#!/usr/bin/env python def mul(a, b): res = [] for i in range(len(b)): res.append(a*b[i]) return tuple(res) def add(a, b): res = [] for i in range(len(a)): res.append(a[i]+b[i]) return tuple(res) n, j = tuple(map(int, raw_input().split())) m0 = tuple(map(int, raw_input().split())) a = [] for k in range(n): a.append(tuple(map(int, raw_input().split()))) par = j / (2*n) j = j % (2*n) sign = 1 if par % 2 == 1: sign = -1 s = 1 sum = (0, 0) while j != 0: sum = add(sum, mul(2*s, a[(j-1)%n])) s = -s j -= 1 sum = add(sum, mul(s, m0)) print sum[0], sum[1]
1280149200
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["Bicarp", "Bicarp", "Bicarp", "Monocarp"]
028882706ed58b61b4672fc3e76852c4
NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy.
Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.
If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes).
The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even.
standard output
standard input
Python 3
Python
1,700
train_004.jsonl
3bafa2be1a5dbf477c24e2809102146e
256 megabytes
["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"]
PASSED
n = int(input()) word = input() tot = 0 for i in range(n): if word[i] == '?': inc = 9 else: inc = 2 * int(word[i]) tot += (2 * (i < n//2) - 1) * inc print(["Monocarp", "Bicarp"][tot == 0])
1568543700
[ "math", "games" ]
[ 1, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5\n6\n5\n2\n9"]
8736df815ea0fdf390cc8d500758bf84
null
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,300
train_001.jsonl
cefa9829ec2c484aef797e8e4e06e0e9
256 megabytes
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
PASSED
n=int(input()) s=str(input()) f=int(input()) d={} for i in range(n): if s[i] not in d: d[s[i]]=[i] else: d[s[i]].append(i) for i in range(f): c=str(input()) h={} m=0 for j in range(len(c)): if(c[j] not in h): h[c[j]]=1 if(d[c[j]][0]>m): m=d[c[j]][0] else: if(d[c[j]][h[c[j]]]>m): m=d[c[j]][h[c[j]]] h[c[j]]=h[c[j]]+1 else: h[c[j]]=h[c[j]]+1 print(m+1)
1561905900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["4\n6 3 2 3", "-1"]
df0b20cf9b848f7406a13378126f301f
null
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number  - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each.
standard output
standard input
Python 3
Python
2,300
train_040.jsonl
8f004c223ab44ac6b47eec457ec2435d
256 megabytes
["6\nabacbb\nbabcba", "3\naba\nbba"]
PASSED
n = int(input()) s = input() t = input() if sorted(s) != sorted(t): print(-1) else: ans = [] for i in t: j = 0 for j in range(n): if i == s[j]: break ans.append(n-j-1) ans.append(1) ans.append(n) s = "".join(reversed(s[:j])) + s[j+1:] + s[j] print(len(ans)) for i in ans: print(i, end=' ')
1519574700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["bbba", "cccccbba"]
77e2a6ba510987ed514fed3bd547b5ab
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
Print the lexicographically maximum subsequence of string s.
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
standard output
standard input
Python 3
Python
1,100
train_013.jsonl
40b3d7e774acf27016df11f5a7f0275b
256 megabytes
["ababba", "abbcbccacbbcbaaba"]
PASSED
s = input() bigger = 'a' res = '' for i in range(len(s)-1,-1,-1): if s[i] >= bigger: res = s[i] + res bigger = s[i] print(res)
1339506000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\n4\n7"]
f3a27e4dc3085712608ecf844e663dfd
null
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
standard output
standard input
Python 3
Python
1,300
train_011.jsonl
6c2a1fd8b138ccd09bd98da0ccb5c34c
256 megabytes
["10\n2 1\n3 1\n4 2\n5 1\n6 2\n7 5\n8 6\n9 8\n10 5\n1 0 1 1 0 1 0 1 0 1\n1 0 1 0 0 1 1 1 0 1"]
PASSED
import fileinput def levels(n, e): l = [0 for _ in range(n)] q = [(0, -1, 0)] while q: v, u, d = q.pop() l[v] = d for w in e[v]: if w != u: q.append((w, v, d+1)) return l def solve(n, e, x, g): l = levels(n, e) f = [0, 0] q = [(0, -1)] z = [] while q: v, u = q.pop() if v == -1: f = u continue q.append((-1, f[:])) d = l[v]%2 if (x[v]+f[d])%2 != g[v]: f[d] = (f[d]+1)%2 z.append(v) for w in e[v]: if w != u: q.append((w, v)) print(len(z)) for v in z: print(v+1) f = fileinput.input() n = int(f.readline()) e = [[] for _ in range(n)] for _ in range(n-1): v, w = tuple(map(int, f.readline().rstrip().split())) e[v-1].append(w-1) e[w-1].append(v-1) x = list(map(int, f.readline().rstrip().split())) g = list(map(int, f.readline().rstrip().split())) solve(n, e, x, g)
1399822800
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["Yes\nNo\nNo\nYes", "No"]
bda76c8ccd3ba7d073a8f923d772361c
NoteIn the first test case it is easy to see that the array is integral: $$$\left \lfloor \frac{1}{1} \right \rfloor = 1$$$, $$$a_1 = 1$$$, this number occurs in the arry $$$\left \lfloor \frac{2}{2} \right \rfloor = 1$$$ $$$\left \lfloor \frac{5}{5} \right \rfloor = 1$$$ $$$\left \lfloor \frac{2}{1} \right \rfloor = 2$$$, $$$a_2 = 2$$$, this number occurs in the array $$$\left \lfloor \frac{5}{1} \right \rfloor = 5$$$, $$$a_3 = 5$$$, this number occurs in the array $$$\left \lfloor \frac{5}{2} \right \rfloor = 2$$$, $$$a_2 = 2$$$, this number occurs in the array Thus, the condition is met and the array is integral.In the second test case it is enough to see that$$$\left \lfloor \frac{7}{3} \right \rfloor = \left \lfloor 2\frac{1}{3} \right \rfloor = 2$$$, this number is not in $$$a$$$, that's why it is not integral.In the third test case $$$\left \lfloor \frac{2}{2} \right \rfloor = 1$$$, but there is only $$$2$$$ in the array, that's why it is not integral.
You are given an array $$$a$$$ of $$$n$$$ positive integers numbered from $$$1$$$ to $$$n$$$. Let's call an array integral if for any two, not necessarily different, numbers $$$x$$$ and $$$y$$$ from this array, $$$x \ge y$$$, the number $$$\left \lfloor \frac{x}{y} \right \rfloor$$$ ($$$x$$$ divided by $$$y$$$ with rounding down) is also in this array.You are guaranteed that all numbers in $$$a$$$ do not exceed $$$c$$$. Your task is to check whether this array is integral.
For each test case print Yes if the array is integral and No otherwise.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$c$$$ ($$$1 \le n \le 10^6$$$, $$$1 \le c \le 10^6$$$) — the size of $$$a$$$ and the limit for the numbers in the array. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le c$$$) — the array $$$a$$$. Let $$$N$$$ be the sum of $$$n$$$ over all test cases and $$$C$$$ be the sum of $$$c$$$ over all test cases. It is guaranteed that $$$N \le 10^6$$$ and $$$C \le 10^6$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_091.jsonl
e3581bc6269fd5004753d95079b9d865
512 megabytes
["4\n\n3 5\n\n1 2 5\n\n4 10\n\n1 3 3 7\n\n1 2\n\n2\n\n1 1\n\n1", "1\n\n1 1000000\n\n1000000"]
PASSED
from collections import defaultdict, Counter,deque from math import sqrt, log10, log, floor, factorial,gcd,ceil,log2 from bisect import bisect_left, bisect_right,insort from itertools import permutations,combinations import sys, io, os input = sys.stdin.readline input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # sys.setrecursionlimit(10000) inf = float('inf') mod = 10 ** 9 + 7 def yn(a): print("YES" if a else "NO") cl = lambda a, b: (a + b - 1) // b t=int(input()) for i in range(t): n,c=[int(i) for i in input().split()] l=[int(i) for i in input().split()] l=sorted(set(l)) counter=[0 for i in range(c+1)] just_greater=[-1 for i in range(c+2)] for i in l: counter[i]=1 for i in range(c,-1,-1): if counter[i]: just_greater[i]=i else: just_greater[i]=just_greater[i+1] if counter[1]==0: print("No") continue flg=1 for i in range(1,c+1): if counter[i]==0: found=1 for start in l: next=start*i if next<=c: next=just_greater[next] if next!=-1 and next<start*(i+1): found=0 break else: break if found==0: flg=0 break if flg: print("Yes") else: print("No") """ 100 5 20 1 2 3 4 20 """
1646560500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Infinite\nFinite\nInfinite\nFinite"]
388450021f2f33177d905879485bb531
null
Consider the set of all nonnegative integers: $$${0, 1, 2, \dots}$$$. Given two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^4$$$). We paint all the numbers in increasing number first we paint $$$0$$$, then we paint $$$1$$$, then $$$2$$$ and so on.Each number is painted white or black. We paint a number $$$i$$$ according to the following rules: if $$$i = 0$$$, it is colored white; if $$$i \ge a$$$ and $$$i - a$$$ is colored white, $$$i$$$ is also colored white; if $$$i \ge b$$$ and $$$i - b$$$ is colored white, $$$i$$$ is also colored white; if $$$i$$$ is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors.For example, if $$$a=3$$$, $$$b=5$$$, then the colors of the numbers (in the order from $$$0$$$) are: white ($$$0$$$), black ($$$1$$$), black ($$$2$$$), white ($$$3$$$), black ($$$4$$$), white ($$$5$$$), white ($$$6$$$), black ($$$7$$$), white ($$$8$$$), white ($$$9$$$), ...Note that: It is possible that there are infinitely many nonnegative integers colored black. For example, if $$$a = 10$$$ and $$$b = 10$$$, then only $$$0, 10, 20, 30$$$ and any other nonnegative integers that end in $$$0$$$ when written in base 10 are white. The other integers are colored black. It is also possible that there are only finitely many nonnegative integers colored black. For example, when $$$a = 1$$$ and $$$b = 10$$$, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored black is infinite.If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).
For each test case, print one line containing either "Infinite" or "Finite" (without the quotes). Output is case-insensitive (i.e. "infinite", "inFiNite" or "finiTE" are all valid answers).
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ lines follow, each line contains two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^4$$$).
standard output
standard input
PyPy 3
Python
1,000
train_005.jsonl
660aeacbab8aee24d13269408d58f40f
256 megabytes
["4\n10 10\n1 10\n6 9\n7 3"]
PASSED
tests = int(input()) for _ in range(tests): n, k = map(int, input().split()) n, k = max(n, k), min(n, k) while n % k != 0: n %= k n, k = k, n if k == 1: print("Finite") else: print("Infinite")
1572618900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO\nYES"]
c7e4f544ec8b4972291542e66aff5df5
NoteIn the first test case, one can apply the operation with $$$x = 3$$$ to obtain the array $$$[2, 2, 0, 2]$$$, and then apply the operation with $$$x = 2$$$ to obtain $$$[0, 0, 0, 0]$$$.In the second test case, all numbers are already equal.In the fourth test case, applying the operation with $$$x = 4$$$ results in the array $$$[1, 1, 1, 1]$$$.
You are given an array of $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$. You can make the following operation: choose an integer $$$x \geq 2$$$ and replace each number of the array by the remainder when dividing that number by $$$x$$$, that is, for all $$$1 \leq i \leq n$$$ set $$$a_i$$$ to $$$a_i \bmod x$$$.Determine if it is possible to make all the elements of the array equal by applying the operation zero or more times.
For each test case, print a line with YES if you can make all elements of the list equal by applying the operation. Otherwise, print NO. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,200
train_091.jsonl
c40085c9aac07680bff9d03432479d0b
256 megabytes
["4\n4\n2 5 6 8\n3\n1 1 1\n5\n4 1 7 0 8\n4\n5 9 17 5"]
PASSED
t=int(input()) for _ in range(t): n=int(input()) lst=list(map(int,input().split())) tempmax=max(lst) temparr = lst.copy() dct={} for i in range(n): if(temparr[i] not in dct): dct[temparr[i]]=1 else: dct[temparr[i]]+=1 if(n==1): print("YES") elif (len(dct) == 1): print("YES") elif(1 in dct): found=False for i in dct.keys(): if(i+1 in dct): print("NO") found=True break if(found==False): print("YES") else: print("YES")
1648132500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["-1\n0\n2\n2"]
71ee54d8881f20ae4b1d8bb9783948c0
null
You are given two strings $$$s$$$ and $$$t$$$ of equal length $$$n$$$. In one move, you can swap any two adjacent characters of the string $$$s$$$.You need to find the minimal number of operations you need to make string $$$s$$$ lexicographically smaller than string $$$t$$$.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, print in a separate line the minimal number of operations you need to make string $$$s$$$ lexicographically smaller than string $$$t$$$, or $$$-1$$$, if it's impossible.
The first line of input contains one integer $$$q$$$ ($$$1 \le q \le 10\,000$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. The third line of each test case contains the string $$$t$$$ consisting of $$$n$$$ lowercase English letters. 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
2,200
train_101.jsonl
35c7f1c9d14502bce20fd854cbae6159
256 megabytes
["4\n1\na\na\n3\nrll\nrrr\n3\ncaa\naca\n5\nababa\naabba"]
PASSED
import os,sys from random import randint import random 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 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") class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # 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(' '))) # cnt = [0] * 200 # for i in range(n): # cnt[abs(a[i])] += 1 # ans = 0 # for i in range(200): # if i == 0: # ans += min(1, cnt[i]) # else: # ans += min(2, cnt[i]) # print(ans) # for _ in range(int(input())): # n = int(input()) # s = input() # ans = [s[0] * 2] # for i in range(1, n): # if s[i] > s[i - 1]: # ans.append(s[:i] + s[:i][::-1]) # break # if s[i] < s[i - 1]: # ans.append(s[:i + 1] + s[:i + 1][::-1]) # ans.append(s[:i] + s[:i][::-1]) # ans.append(s + s[::-1]) # ans.sort() # print(ans[0]) def lowbit(x): return x & (-x) class BIT: def __init__(self, x): """transform list into BIT""" self.bit = x for i in range(len(x)): j = i + lowbit(i) if j < len(x): x[j] += x[i] def update(self, idx, x): """updates bit[idx] += x""" idx += 1 while idx < len(self.bit): self.bit[idx] += x idx += lowbit(idx) def query(self, end): """calc sum(bit[1:end+1])""" x = 0 while end: x += self.bit[end] end -= lowbit(end) return x for _ in range(int(input())): n = int(input()) s = input() t = input() if s < t: print(0) continue if ''.join(sorted(s)) >= t: print(-1) continue p = [n for _ in range(26)] for i in range(n): if p[ord(s[i]) - ord('a')] == n: p[ord(s[i]) - ord('a')] = i i = j = 0 # vis = SortedList() vis = set() fen = BIT([0] * (n + 2)) ans = float('inf') res = 0 while i < n and j < n: while i in vis: vis.remove(i) fen.update(i, -1) i += 1 if i >= n: break for k in range(26): if p[k] <= i or p[k] in vis: tmp = max(i, p[k]) + 1 while tmp < n and (s[tmp] != s[p[k]] or tmp in vis): tmp += 1 p[k] = tmp if s[i] < t[j]: ans = min(ans, res) break mn = n for k in range(ord(t[j]) - ord('a')): mn = min(mn, p[k]) if mn != n: # ans = min(ans, res + mn - i - (vis.bisect_left(mn) - vis.bisect_right(i))) ans = min(ans, res + mn - i - (fen.query(mn) - fen.query(i + 1))) if s[i] == t[j]: i += 1 j += 1 else: if i < p[ord(t[j]) - ord('a')] < mn: idx = p[ord(t[j]) - ord('a')] # res += idx - i - (vis.bisect_left(idx) - vis.bisect_right(i)) res += idx - i - (fen.query(idx) - fen.query(i + 1)) vis.add(idx) fen.update(idx, 1) j += 1 else: break print(ans if ans < float('inf') else -1)
1640792100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1 4", "-1", "4 3", "1 2 3 6"]
3afa68fbe090683ffe16c3141aafe76e
NoteIn the first example, one of the possible divisions into two performances is as follows: in the first performance artists $$$1$$$ and $$$4$$$ should take part. Then the number of artists in the first performance who can perform as clowns is equal to $$$1$$$. And the number of artists in the second performance who can perform as acrobats is $$$1$$$ as well.In the second example, the division is not possible.In the third example, one of the possible divisions is as follows: in the first performance artists $$$3$$$ and $$$4$$$ should take part. Then in the first performance there are $$$2$$$ artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is $$$2$$$ as well.
Polycarp is a head of a circus troupe. There are $$$n$$$ — an even number — artists in the troupe. It is known whether the $$$i$$$-th artist can perform as a clown (if yes, then $$$c_i = 1$$$, otherwise $$$c_i = 0$$$), and whether they can perform as an acrobat (if yes, then $$$a_i = 1$$$, otherwise $$$a_i = 0$$$).Split the artists into two performances in such a way that: each artist plays in exactly one performance, the number of artists in the two performances is equal (i.e. equal to $$$\frac{n}{2}$$$), the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance.
Print $$$\frac{n}{2}$$$ distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer $$$-1$$$.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5\,000$$$, $$$n$$$ is even) — the number of artists in the troupe. The second line contains $$$n$$$ digits $$$c_1 c_2 \ldots c_n$$$, the $$$i$$$-th of which is equal to $$$1$$$ if the $$$i$$$-th artist can perform as a clown, and $$$0$$$ otherwise. The third line contains $$$n$$$ digits $$$a_1 a_2 \ldots a_n$$$, the $$$i$$$-th of which is equal to $$$1$$$, if the $$$i$$$-th artist can perform as an acrobat, and $$$0$$$ otherwise.
standard output
standard input
PyPy 2
Python
1,800
train_006.jsonl
7b94f1abdd8ec6d193ce9ccc608808d6
256 megabytes
["4\n0011\n0101", "6\n000000\n111111", "4\n0011\n1100", "8\n00100101\n01111100"]
PASSED
#!/usr/bin/env python2 """ This file is part of https://github.com/cheran-senthil/PyRival Copyright 2019 Cheran Senthilkumar <[email protected]> """ from __future__ import division, print_function import itertools import os import sys from atexit import register from io import BytesIO class dict(dict): """dict() -> new empty dictionary""" def items(self): """D.items() -> a set-like object providing a view on D's items""" return dict.iteritems(self) def keys(self): """D.keys() -> a set-like object providing a view on D's keys""" return dict.iterkeys(self) def values(self): """D.values() -> an object providing a view on D's values""" return dict.itervalues(self) def gcd(x, y): """greatest common divisor of x and y""" while y: x, y = y, x % y return x range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') def main(): n = int(input()) a = zip(map(int, input()), map(int, input())) m = [[], [], [], []] for i, j in enumerate(a): m[j[0] * 2 + j[1]].append(i + 1) p1 = [0, 0, len(m[2]), 0] p2 = [0, len(m[1]), 0, 0] u = min(abs(p1[2] - p2[1]), len(m[3])) if p1[2] < p2[1]: p1[3] = u else: p2[3] = u p1[3] += (len(m[3]) - u) // 2 p2[3] += (len(m[3]) - u) // 2 f1 = (len(m[3]) - u) % 2 if p1[2] + p1[3] < p2[1] + p2[3]: u = min(abs(p1[2] + p1[3] - p2[1] - p2[3]), p2[1]) p2[1] -= u p1[1] += u else: u = min(abs(p1[2] + p1[3] - p2[1] - p2[3]), p1[2]) p1[2] -= u p2[2] += u if p1[2] + p1[3] != p2[1] + p2[3]: print(-1) return l1 = p1[1] + p1[2] + p1[3] l2 = p2[1] + p2[2] + p2[3] u = min(abs(l1 - l2), len(m[0])) if l1 < l2: p1[0] = u else: p2[0] = u p1[0] += (len(m[0]) - u) // 2 p2[0] += (len(m[0]) - u) // 2 f2 = (len(m[0]) - u) % 2 l1 = p1[0] + p1[1] + p1[2] + p1[3] l2 = p2[0] + p2[1] + p2[2] + p2[3] if abs(l1 - l2) > 1: print(-1) return if f1 == f2 == 1: if abs(l1 - l2) == 0: if p1[2]: p1[0] += 1 p1[3] += 1 p1[2] -= 1 p2[2] += 1 elif p2[1]: p2[0] += 1 p2[3] += 1 p2[1] -= 1 p1[1] += 1 else: print(-1) return else: print(-1) return elif f2 == 1: if abs(l1 - l2) == 1: p1[0] += l1 < l2 p2[0] += l1 > l2 else: print(-1) return elif f1 == 1: if abs(l1 - l2) == 1: if p1[2]: p1[2] -= 1 p1[3] += 1 p2[2] += 1 if p2[1]: p2[1] -= 1 p2[3] += 1 p1[1] += 1 else: print(-1) return elif abs(l1 - l2) == 1: print(-1) return s = [] for i, j in enumerate(p1): s += m[i][:j] print(*s) if __name__ == '__main__': main()
1552035900
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
3 seconds
["1", "1 1 2", "0 1 1 1 2 2 2"]
079382c58c726aaab21ca209ca3f4d2f
NoteIn the first test we can change $$$1$$$ to $$$2$$$, so the answer is $$$1$$$.In the second test: $$$[1]$$$ can be changed into $$$[2]$$$, $$$[1, 4]$$$ can be changed into $$$[3, 4]$$$, $$$[1, 4, 2]$$$ can be changed into $$$[2, 3, 2]$$$.
New Year is just around the corner, which means that in School 179, preparations for the concert are in full swing.There are $$$n$$$ classes in the school, numbered from $$$1$$$ to $$$n$$$, the $$$i$$$-th class has prepared a scene of length $$$a_i$$$ minutes.As the main one responsible for holding the concert, Idnar knows that if a concert has $$$k$$$ scenes of lengths $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_k$$$ minutes, then the audience will get bored if there exist two integers $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le k$$$ and $$$\gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r) = r - l + 1$$$, where $$$\gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r)$$$ is equal to the greatest common divisor (GCD) of the numbers $$$b_l$$$, $$$b_{l + 1}$$$, $$$\ldots$$$, $$$b_{r - 1}$$$, $$$b_r$$$.To avoid boring the audience, Idnar can ask any number of times (possibly zero) for the $$$t$$$-th class ($$$1 \le t \le k$$$) to make a new scene $$$d$$$ minutes in length, where $$$d$$$ can be any positive integer. Thus, after this operation, $$$b_t$$$ is equal to $$$d$$$. Note that $$$t$$$ and $$$d$$$ can be different for each operation.For a sequence of scene lengths $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_{k}$$$, let $$$f(b)$$$ be the minimum number of classes Idnar has to ask to change their scene if he wants to avoid boring the audience.Idnar hasn't decided which scenes will be allowed for the concert, so he wants to know the value of $$$f$$$ for each non-empty prefix of $$$a$$$. In other words, Idnar wants to know the values of $$$f(a_1)$$$, $$$f(a_1$$$,$$$a_2)$$$, $$$\ldots$$$, $$$f(a_1$$$,$$$a_2$$$,$$$\ldots$$$,$$$a_n)$$$.
Print a sequence of $$$n$$$ integers in a single line — $$$f(a_1)$$$, $$$f(a_1$$$,$$$a_2)$$$, $$$\ldots$$$, $$$f(a_1$$$,$$$a_2$$$,$$$\ldots$$$,$$$a_n)$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of classes in the school. The second line contains $$$n$$$ positive integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the lengths of the class scenes.
standard output
standard input
PyPy 3-64
Python
2,000
train_084.jsonl
f874b2c6f3ff65deaf6afb1b56072c85
256 megabytes
["1\n1", "3\n1 4 2", "7\n2 12 4 8 18 3 6"]
PASSED
from math import gcd import sys class segmenttree: def __init__(self, n, default=0, func=lambda a, b: a + b): self.tree, self.n, self.func, self.default = [0] * (2 * n), n, func, default def fill(self, arr): self.tree[self.n:] = arr for i in range(self.n - 1, 0, -1): self.tree[i] = self.func(self.tree[i << 1], self.tree[(i << 1) + 1]) # get interval[l,r) def query(self, l, r): res, l, r = self.default, l + self.n, r + self.n while l < r: if l & 1: res = self.func(res, self.tree[l]) l += 1 if r & 1: r -= 1 res = self.func(res, self.tree[r]) l, r = l >> 1, r >> 1 return res def __setitem__(self, ix, val): ix += self.n self.tree[ix] = val while ix > 1: self.tree[ix >> 1] = self.func(self.tree[ix], self.tree[ix ^ 1]) ix >>= 1 def __getitem__(self, item): return self.tree[item + self.n] input = lambda: sys.stdin.buffer.readline().decode().strip() n, a = int(input()), [int(x) for x in input().split()] tree, ans, lst = segmenttree(n, 0, lambda a, b: gcd(a, b)), 0, 0 tree.fill(a) for i in range(n): be, en = lst, i while be <= en: md = (be + en) >> 1 val = tree.query(md, i + 1) if val == i - md + 1: lst = i + 1 ans += 1 break elif val < i - md + 1: be = md + 1 else: en = md - 1 print(ans, end=' ')
1643553300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["1", "-1"]
886029b385c099b3050b7bc6978e433b
NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.
Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.
Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes).
The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \le K \le N \le 10^{18}$$$; $$$1 \le M, \,\, L \le 10^{18}$$$) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.
standard output
standard input
Python 3
Python
1,400
train_001.jsonl
a6b477e341f3884a5de6da10a6c550fe
256 megabytes
["20 15 2 3", "10 11 2 4"]
PASSED
import sys n,m,k,l= map(int, sys.stdin.readline().split(' ')) ans=(l+k)//m if(ans*m<(l+k)): ans+=1 if(ans*m<=n): print(ans) else: print(-1)
1540398900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 5 9 21", "1 10 28 64 136"]
2ae1a4d4f2e58b359c898d1ff38edb9e
NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$. In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively.
There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.
Suppose the set of all fun values is $$$f_1, f_2, \dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.
The only line consists of a single integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number of people playing with the ball.
standard output
standard input
Python 3
Python
1,400
train_019.jsonl
9a73c26bf4c0b35b7a3db74305c97404
256 megabytes
["6", "16"]
PASSED
from collections import Counter,defaultdict,deque #alph = 'abcdefghijklmnopqrstuvwxyz' #from math import factorial as fact #import math #tt = 1#int(input()) #total=0 #n = int(input()) #n,m,k = [int(x) for x in input().split()] #n = int(input()) #n,m = [int(x) for x in input().split()] def divisors(n): i = 1 divs = [] while i*i<=n: if n%i==0: divs.append(i) if i*i!=n: divs.append(n//i) i+=1 return divs n = int(input()) p = divisors(n) res = [] for el in p: a = n//el k = (1+n-el+1)*a//2 res.append(k) res.sort() print(*res)
1546180500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n2\n3\n3"]
6280a3373ab8fc34bb41fd98648019a6
NoteSample explanation:In the first test case, the graph constructed from the bracket sequence (), is just a graph containing nodes $$$1$$$ and $$$2$$$ connected by a single edge. In the second test case, the graph constructed from the bracket sequence ()(()) would be the following (containing two connected components): Definition of Underlined Terms: 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. The subsegment $$$s[l \ldots r]$$$ denotes the sequence $$$[s_l, s_{l + 1}, \ldots, s_r]$$$. A connected component is a set of vertices $$$X$$$ such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to $$$X$$$ violates this rule.
Last summer, Feluda gifted Lalmohan-Babu a balanced bracket sequence $$$s$$$ of length $$$2 n$$$.Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $$$2 n$$$ vertices using the balanced bracket sequence $$$s$$$. For any two distinct vertices $$$i$$$ and $$$j$$$ ($$$1 \le i &lt; j \le 2 n$$$), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the subsegment $$$s[i \ldots j]$$$ forms a balanced bracket sequence.Determine the number of connected components in Topshe's graph.See the Notes section for definitions of the underlined terms.
For each test case, output a single integer — the number of connected components in Topshe's graph.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of opening brackets in string $$$s$$$. The second line of each test case contains a string $$$s$$$ of length $$$2 n$$$ — a balanced bracket sequence consisting of $$$n$$$ opening brackets "(", and $$$n$$$ closing brackets ")". It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,300
train_106.jsonl
cff1ed2636535a3247b2b608a1bf5168
256 megabytes
["4\n\n1\n\n()\n\n3\n\n()(())\n\n3\n\n((()))\n\n4\n\n(())(())"]
PASSED
n = int(input()) for i in range(n): trash = int(input()) miew = input() balance = 0 groups = 0 recently_closed = False for j in range(len(miew)): char = miew[j] if char == '(': balance += 1 recently_closed = False else: if balance > 0 and recently_closed: groups += 1 if balance > 0: balance -= 1 recently_closed = True else: groups += 1 # print(groups, j) groups += balance + 1 print(groups)
1662474900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2"]
5db2ae5b2c91b29e4fe4a45ab864e3f1
NoteThe subsegment $$$[3, 4]$$$ is the longest among all subsegments with maximum arithmetic mean.
You are given array $$$a_1, a_2, \dots, a_n$$$. Find the subsegment $$$a_l, a_{l+1}, \dots, a_r$$$ ($$$1 \le l \le r \le n$$$) with maximum arithmetic mean $$$\frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i}$$$ (in floating-point numbers, i.e. without any rounding).If there are many such subsegments find the longest one.
Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean.
The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the array $$$a$$$.
standard output
standard input
Python 3
Python
1,100
train_013.jsonl
99eb0d33ab3caad5421514caf206c448
256 megabytes
["5\n6 1 6 6 0"]
PASSED
from sys import stdin n=int(stdin.readline()) arr=list(map(int,stdin.readline().split())) a=max(arr) ans=[] count=0 for i in range(n): if arr[i]==a: count+=1 else: count=0 ans.append(count) print(max(ans))
1550504400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2 4 1 3\n1 2 3"]
0d5f4320fc2c7662d21e09a51baf21db
NoteIn the first test case the minimum absolute difference of consecutive elements equals $$$\min \{\lvert 4 - 2 \rvert, \lvert 1 - 4 \rvert, \lvert 3 - 1 \rvert \} = \min \{2, 3, 2\} = 2$$$. It's easy to prove that this answer is optimal.In the second test case each permutation of numbers $$$1, 2, 3$$$ is an optimal answer. The minimum absolute difference of consecutive elements equals to $$$1$$$.
For his birthday, Kevin received the set of pairwise distinct numbers $$$1, 2, 3, \ldots, n$$$ as a gift.He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $$$p_1, p_2, \ldots, p_n$$$, he wants to maximize the value $$$$$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert,$$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Help Kevin to do that.
For each test case print a single line containing $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) describing the arrangement that maximizes the minimum absolute difference of consecutive elements. Formally, you have to print a permutation $$$p$$$ which maximizes the value $$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert$$$. If there are multiple optimal solutions, print any of them.
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \le n \leq 1\,000$$$) — the size of the set.
standard output
standard input
Python 3
Python
800
train_104.jsonl
8d3b27312c36ca031f54acc6c8291afc
256 megabytes
["2\n\n4\n\n3"]
PASSED
def sol(n1): dt = [0] * n1 dt3 = [0] * n1 c = 0 i, cnt = 0, 0 h = (n1 // 2) +1 for i in range(0, n1//2): dt[i * 2] = i + 1 # if ( i * 2 + 1 < n1 ): if ( h + dt[i * 2] <= n1): dt[i * 2 + 1] = h + dt[i * 2] if n1+1 %2: # dt[n1-1] = n1 dt3[1:0] = dt dt3[0] = h dt = dt3[0:n1] return dt # 5 3 6 1 4 2 # 4 1 5 2 6 3 dt2 = dt * 2 f = check(n1, dt) dx = dt2[h: n1 + h] b = check(n1, dx ) if f > b: return dt else: return dx def check(n1, dt): sol = [] mn = n1 + 1 for i in range(n1 - 1): mn = min(mn, abs(dt[i + 1] - dt[i])) return mn n = input() for i in range(int(n)): t = int(input()) dt = sol(t) ans = str(dt[0]) for i in dt[1:]: ans += " " + str(i) print(ans)
1666511400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\na d\nb a", "7\nl e\ne d\nd c\nc p\np o\no r\nr a"]
f82f38972afa33e779c8fb7d34849db7
NoteIn first example it's enough to buy two spells: ('a','d') and ('b','a'). Then first letters will coincide when we will replace letter 'a' with 'd'. Second letters will coincide when we will replace 'b' with 'a'. Third letters will coincide when we will at first replace 'b' with 'a' and then 'a' with 'd'.
Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.This story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.More formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length n consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (c1, c2) (where c1 and c2 are some lowercase English letters), which can arbitrary number of times transform a single letter c1 to c2 and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.
In the first line output a single integer — the minimum amount of mana t required for rescuing love of Valya and Tolya. In the next t lines output pairs of space-separated lowercase English letters — spells that Tolya's grandmother should buy. Spells and letters in spells can be printed in any order. If there are many optimal answers, output any.
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of the letterings. The second line contains a string with length n, consisting of lowercase English letters — the lettering on Valya's pullover. The third line contains the lettering on Tolya's t-shirt in the same format.
standard output
standard input
Python 3
Python
1,600
train_032.jsonl
32ab1d2a62af2a2e4e0e2a96b9799134
256 megabytes
["3\nabb\ndad", "8\ndrpepper\ncocacola"]
PASSED
n = int(input()) t = input() v = input() s = list(set(list(t)).union(set(list(v)))) uf = [i for i in range(len(s))] def find(uf,i): p = uf[i] return p if i==p else find(uf,p) def union(uf,i,j): uf[find(uf,i)] = find(uf,j) res = [] for i in range(n): ti = s.index(t[i]) vi = s.index(v[i]) if (find(uf,ti) != find(uf,vi)): union(uf,ti,vi) res.append((t[i],v[i])) print(len(res)) for i in range(len(res)): print(res[i][0],res[i][1])
1518861900
[ "strings", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 1, 0 ]
2 seconds
["3\n2\n4", "13\n3\n8\n9"]
756866daf45951854d5400b209af3bb0
NoteThe first example is shown in the picture.In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.
For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.
The first line contains two integers n and q (1 ≤ n ≤ 1018, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers xi (1 ≤ xi ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.
standard output
standard input
Python 3
Python
1,700
train_058.jsonl
87a75c29fa227028f017195276182e90
512 megabytes
["4 3\n2\n3\n4", "13 4\n10\n5\n4\n8"]
PASSED
import math from decimal import Decimal def na(): n = int(input()) b = [int(x) for x in input().split()] return n,b def nab(): n = int(input()) b = [int(x) for x in input().split()] c = [int(x) for x in input().split()] return n,b,c def dv(): n, m = map(int, input().split()) return n,m def dva(): n, m = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] return n,m,b def eratosthenes(n): sieve = list(range(n + 1)) for i in sieve: if i > 1: for j in range(i + i, len(sieve), i): sieve[j] = 0 return sorted(set(sieve)) def nm(): n = int(input()) b = [int(x) for x in input().split()] m = int(input()) c = [int(x) for x in input().split()] return n,b,m,c def dvs(): n = int(input()) m = int(input()) return n, m n, q = map(int, input().split()) ans = [] for i in range(q): x = int(input()) ans.append(x) for i in ans: d = 2 * n - i while d % 2 == 0: d //= 2 print(n - d // 2)
1520583000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["+++-", "++-"]
30f64b963310911196ebf5d624c01cc3
null
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i &lt; n).Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array. It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i &lt; n).
standard output
standard input
Python 3
Python
1,900
train_003.jsonl
e0d6a42581e28d990fa0f1c946bb8979
256 megabytes
["4\n1 2 3 5", "3\n3 3 5"]
PASSED
n = int(input()) arr = list(map(int, input().split())) if n == 1: print('+') elif n == 2: print('-+') else: ans = ['+'] cur = arr[-1] for i in range(n - 2, -1, -1): if cur > 0: cur -= arr[i] ans.append('-') else: cur += arr[i] ans.append('+') ans.reverse() if cur < 0: for i in range(n): if ans[i] == '-': ans[i] = '+' else: ans[i] = '-' print(''.join(ans))
1357659000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["7", "76", "129"]
ef0ad7b228351a268c3f6bfac68b1002
NoteIn the first sample there are three pairs of cells of same color: in cells $$$(1, 1)$$$ and $$$(2, 3)$$$, in cells $$$(1, 2)$$$ and $$$(2, 2)$$$, in cells $$$(1, 3)$$$ and $$$(2, 1)$$$. The manhattan distances between them are $$$3$$$, $$$1$$$ and $$$3$$$, the sum is $$$7$$$.
Egor has a table of size $$$n \times m$$$, with lines numbered from $$$1$$$ to $$$n$$$ and columns numbered from $$$1$$$ to $$$m$$$. Each cell has a color that can be presented as an integer from $$$1$$$ to $$$10^5$$$.Let us denote the cell that lies in the intersection of the $$$r$$$-th row and the $$$c$$$-th column as $$$(r, c)$$$. We define the manhattan distance between two cells $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table $$$3 \times 4$$$ the manhattan distance between $$$(1, 2)$$$ and $$$(3, 3)$$$ is $$$3$$$, one of the shortest paths is the following: $$$(1, 2) \to (2, 2) \to (2, 3) \to (3, 3)$$$. Egor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.
Print one integer — the the sum of manhattan distances between each pair of cells of the same color.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \le m$$$, $$$n \cdot m \leq 100\,000$$$) — number of rows and columns in the table. Each of next $$$n$$$ lines describes a row of the table. The $$$i$$$-th line contains $$$m$$$ integers $$$c_{i1}, c_{i2}, \ldots, c_{im}$$$ ($$$1 \le c_{ij} \le 100\,000$$$) — colors of cells in the $$$i$$$-th row.
standard output
standard input
PyPy 3-64
Python
1,400
train_091.jsonl
16c7f3582cfab9ccb46038e0fbb1af7f
256 megabytes
["2 3\n1 2 3\n3 2 1", "3 4\n1 1 2 2\n2 1 1 2\n2 2 1 1", "4 4\n1 1 2 3\n2 1 1 2\n3 1 2 1\n1 1 2 1"]
PASSED
tiles = input() tiles = tiles.split(" ") n = int(tiles[0]) m = int(tiles[1]) def arr_man(arr): arr = sorted(arr) res = 0 sum = 0 for i, e in enumerate(arr): res += (e * i - sum) sum += e return res coords = {} final_sum = 0 for i in range(n): row = input() row = row.split(" ") for j, c in enumerate(row): if c in coords: coords[c][0].append(i) coords[c][1].append(j) else: coords[c] = ([i], [j]) final_sum = sum([arr_man(x) + arr_man(y) for x, y in coords.values()]) print(final_sum)
1646560500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["5", "3", "2"]
fead36831dbcb1c0bdf6b6965b751ad8
NoteIn the first example the resulting string s is "winlosewinwinlwinwin"In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary.In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab".
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.The anthem is the string s of no more than 105 small Latin letters and question marks. The most glorious victory is the string t of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.Note that the occurrences of string t in s can overlap. Check the third example for clarification.
Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.
The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 105). The second line contains string of small Latin letters t (1 ≤ |t| ≤ 105). Product of lengths of strings |s|·|t| won't exceed 107.
standard output
standard input
PyPy 3
Python
2,300
train_080.jsonl
f6a5f910765c65c33514431661ca02e4
256 megabytes
["winlose???winl???w??\nwin", "glo?yto?e??an?\nor", "??c?????\nabcab"]
PASSED
def prefix(st): t = 0 p = [0] * (len(st) + 1) o = [0] * (len(st) + 1) for i in range(2, len(st)): while t > 0 and st[i] != st[t + 1]: t = p[t] if st[i] == st[t + 1]: t += 1 p[i] = t while t > 0: o[t] = 1 t = p[t] return o s = ' ' + input() t = ' ' + input() o = prefix(t) m = len(t) - 1 ans = [[0, 0] for _ in range(len(s) + 5)] ans[0][1] = float('-inf') for i in range(1, len(s)): j = m ans[i][1] = float('-inf') for j in range(m, 0, -1): if s[i - m + j] != '?' and s[i - m + j] != t[j]: break if o[j - 1]: ans[i][1] = max(ans[i][1], ans[i - m + j - 1][1] + 1) if j == 1: ans[i][1] = max(ans[i][1], ans[i - m][0] + 1) ans[i][0] = max(ans[i][1], ans[i - 1][0]) if ans[len(s) - 1][0] == 7: print(o.count(1)) else: print(ans[len(s) - 1][0])
1494860700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["YES\n10100"]
981e9991fb5dbd085db8a408c29564d4
NoteThe picture corresponding to the first example: And one of possible answers:
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. There are no self-loops or multiple edges in the given graph.You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).
If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length $$$m$$$. The $$$i$$$-th element of this string should be '0' if the $$$i$$$-th edge of the graph should be directed from $$$u_i$$$ to $$$v_i$$$, and '1' otherwise. Edges are numbered in the order they are given in the input.
The first line contains two integer numbers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and edges, respectively. The following $$$m$$$ lines contain edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). There are no multiple edges in the given graph, i. e. for each pair ($$$u_i, v_i$$$) there are no other pairs ($$$u_i, v_i$$$) and ($$$v_i, u_i$$$) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph).
standard output
standard input
Python 3
Python
1,700
train_000.jsonl
eec5ba0c7e518e8a79ad11d803d8c20b
256 megabytes
["6 5\n1 5\n2 1\n1 4\n3 1\n6 1"]
PASSED
import sys sys.setrecursionlimit(10000000) a, b = tuple([int(i) for i in input().split()]) save = {} printl = ['']*(b) data = [''] for i in range(a): data.append(set()) for i in range(b): a = input().split() c = int(a[0]) d = int(a[1]) save[(c,d)] = i data[c].add(d) data[d].add(c) done = set() def search(prev, a, isforward): if isforward: good = '1' bad = '0' else: good = '0' bad = '1' for e in data[a]: if e in done or e == prev: continue if (a,e) in save: p = save[(a,e)] if printl[p] != '': if printl[p] != good: print('NO') sys.exit() else: printl[p] = good search(a, e, not isforward) else: p = save[(e,a)] if printl[p] != '': if printl[p] != bad: print('NO') sys.exit() else: printl[p] = bad search(a, e, not isforward) done.add(a) layer = {1} good = '0' bad = '1' while len(layer) > 0: good, bad = bad, good new = set() for a in layer: for e in data[a]: # if e in done: # continue if (a,e) in save: p = save[(a,e)] if printl[p] != '': if printl[p] != good: print('NO') sys.exit() else: printl[p] = good new.add(e) else: p = save[(e,a)] if printl[p] != '': if printl[p] != bad: print('NO') sys.exit() else: printl[p] = bad new.add(e) #done.add(a) layer = new # try: # search(-1, 1, True) # except Exception as e: # print(e.__class__) print('YES') print(''.join(printl))
1554041100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2\n1\n12"]
59ec1518d55bf81ee7cadba3a918c890
NoteThe greatest common divisor of a set of integers is the largest integer $$$g$$$ such that all elements of the set are divisible by $$$g$$$.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and $$$f(S)$$$ for any non-empty subset is $$$2$$$, thus the greatest common divisor of these values if also equal to $$$2$$$.In the second sample case the subset $$$\{1\}$$$ in the left half is connected to vertices $$$\{1, 2\}$$$ of the right half, with the sum of numbers equal to $$$2$$$, and the subset $$$\{1, 2\}$$$ in the left half is connected to vertices $$$\{1, 2, 3\}$$$ of the right half, with the sum of numbers equal to $$$3$$$. Thus, $$$f(\{1\}) = 2$$$, $$$f(\{1, 2\}) = 3$$$, which means that the greatest common divisor of all values of $$$f(S)$$$ is $$$1$$$.
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset $$$S$$$ of vertices of the left half we define $$$N(S)$$$ as the set of all vertices of the right half adjacent to at least one vertex in $$$S$$$, and $$$f(S)$$$ as the sum of all numbers in vertices of $$$N(S)$$$. Find the greatest common divisor of $$$f(S)$$$ for all possible non-empty subsets $$$S$$$ (assume that GCD of empty set is $$$0$$$).Wu is too tired after his training to solve this problem. Help him!
For each test case print a single integer — the required greatest common divisor.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 500\,000$$$) — the number of test cases in the given test set. Test case descriptions follow. The first line of each case description contains two integers $$$n$$$ and $$$m$$$ ($$$1~\leq~n,~m~\leq~500\,000$$$) — the number of vertices in either half of the graph, and the number of edges respectively. The second line contains $$$n$$$ integers $$$c_i$$$ ($$$1 \leq c_i \leq 10^{12}$$$). The $$$i$$$-th number describes the integer in the vertex $$$i$$$ of the right half of the graph. Each of the following $$$m$$$ lines contains a pair of integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), describing an edge between the vertex $$$u_i$$$ of the left half and the vertex $$$v_i$$$ of the right half. It is guaranteed that the graph does not contain multiple edges. Test case descriptions are separated with empty lines. The total value of $$$n$$$ across all test cases does not exceed $$$500\,000$$$, and the total value of $$$m$$$ across all test cases does not exceed $$$500\,000$$$ as well.
standard output
standard input
PyPy 2
Python
2,300
train_007.jsonl
51b12d6f7c60d3623b7463c6d3ff09bd
512 megabytes
["3\n2 4\n1 1\n1 1\n1 2\n2 1\n2 2\n\n3 4\n1 1 1\n1 1\n1 2\n2 2\n2 3\n\n4 7\n36 31 96 29\n1 2\n1 3\n1 4\n2 2\n2 4\n3 1\n4 3"]
PASSED
from __future__ import print_function,division #from sortedcontainers import SortedList import sys #sys.__stdout__.flush() def gc(a,b): while b: a,b=b,a%b return a le=sys.__stdin__.read().split("\n") le.pop() le=le[::-1] af=[] for z in range(int(le.pop())): if z: le.pop() n,m=map(int,le.pop().split()) c=list(map(int,le.pop().split())) v=[[] for k in range(n)] for k in range(m): a,b=map(int,le.pop().split()) v[b-1].append(a-1) di={} for k in range(n): cl=tuple(sorted(v[k])) if cl: if cl in di: di[cl]+=c[k] else: di[cl]=c[k] d=0 for k in di: d=gc(di[k],d) af.append(d) print("\n".join(map(str,af)))
1583573700
[ "number theory", "math", "graphs" ]
[ 0, 0, 1, 1, 1, 0, 0, 0 ]
2 seconds
["2 2 2 2 2 2", "2 2 2", "1 2 1 2 2 2 1 2"]
2c279b3065d8da8021051241677d9cf1
null
Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1 + x2) must be as large as possible. If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java.Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0.
Print n space-separated integers, the i-th of them should equal either 1, if Petya keeps the number that follows i-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input.
The first line contains integer n (1 ≤ n ≤ 105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018.
standard output
standard input
PyPy 2
Python
2,700
train_031.jsonl
62b50314fc5253b6f92223e559a2845b
256 megabytes
["6\n1 2 3 4 5 6", "3\n1000000000000 1000000000000 1000000000000", "8\n1 1 2 2 3 3 4 4"]
PASSED
import sys range = xrange input = raw_input n = int(input()) A = [int(x) for x in input().split()] # Reorder the bits big = 60 mapper = [0]*big ind = big - 1 xor = 0 for a in A: xor ^= a for j in reversed(range(big)): if xor & (1 << j) == 0: mapper[j] = ind ind -= 1 for j in reversed(range(big)): if xor & (1 << j): mapper[j] = ind ind -= 1 B = [] for a in A: tmp = 0 for j in range(big): if a & (1 << j): tmp += 1 << mapper[j] B.append(tmp) A = B # returns a subset of A with maximum xor def max_xor(A): who = [] how = {} base = {} for i in range(n): a = A[i] tmp = 0 while a > 0: b = a.bit_length() - 1 if b in how: a ^= base[b] tmp ^= how[b] else: base[b] = a how[b] = tmp | (1 << len(who)) who.append(i) break x = 0 tmp = 0 for j in sorted(how, reverse = True): if not x & (1 << j): x ^= base[j] tmp ^= how[j] B = [who[j] for j in range(len(who)) if tmp & (1 << j)] return B ans = [1]*n for i in max_xor(A): ans[i] = 2 print ' '.join(str(x) for x in ans)
1354807800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6", "7"]
274ae43b10bb15e270788d36590713c7
NoteIn the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $$$6$$$.In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $$$(1, 4)$$$. For these two stations the distance is $$$2$$$.
Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.Right now he has a map of some imaginary city with $$$n$$$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $$$u$$$ and $$$v$$$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $$$w$$$ that the original map has a tunnel between $$$u$$$ and $$$w$$$ and a tunnel between $$$w$$$ and $$$v$$$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.
Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.
The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \ne v_i$$$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $$$n$$$ stations and $$$n - 1$$$ tunnels form a tree.
standard output
standard input
Python 2
Python
2,000
train_030.jsonl
4768a3c7934bfedb57ea18cfa295b226
512 megabytes
["4\n1 2\n1 3\n1 4", "4\n1 2\n2 3\n3 4"]
PASSED
import collections import sys Stats = collections.namedtuple( 'Stats', [ 'odd_paths_to_root', 'even_paths_to_root', 'result', 'sum_paths_to_root', 'size', ]) def _solve(children_stats): sum_paths_to_root = 0 odd_paths_to_root = 0 even_paths_to_root = 1 result = 0 size = 1 for s in children_stats: odd_paths_to_root += s.even_paths_to_root even_paths_to_root += s.odd_paths_to_root sum_paths_to_root += s.sum_paths_to_root + s.size size += s.size for s in children_stats: result += s.result paths_through_root = 0 paths_through_root_mod_2 = 0 paths_through_root_mod_2_finish = 0 for s in children_stats: paths_through_root += (s.sum_paths_to_root + s.size) * (size - s.size) paths_through_root_mod_2_finish += ( (s.even_paths_to_root) # odd paths to v from s ) paths_through_root_mod_2 += ( (even_paths_to_root - s.odd_paths_to_root - 1) * # even paths to v not from s (s.even_paths_to_root) # odd paths to v from s ) paths_through_root_mod_2 += ( (odd_paths_to_root - s.even_paths_to_root) * # odd paths to v not from s (s.odd_paths_to_root) # even paths from v to s ) paths_through_root_mod_2 = paths_through_root_mod_2 / 2 + paths_through_root_mod_2_finish result += (paths_through_root - paths_through_root_mod_2)/2 + paths_through_root_mod_2 return Stats( odd_paths_to_root, even_paths_to_root, result, sum_paths_to_root, size, ) def solve(adj): stack = [1] unprocessed_adj = [] on_stack = {1} ready = set() stats = {} parent = {} while stack: v = stack[-1] if v not in ready: for u in adj[v]: if u not in on_stack: stack.append(u) parent[u] = v on_stack.add(u) ready.add(v) else: stack.pop(-1) stats[v] = _solve([stats[u] for u in adj[v] if parent.get(v) != u]) return stats[1] if __name__ == '__main__': n = int(raw_input().strip()) adj = [[] for i in range(n+1)] for i in range(n-1): a, b = map(int, raw_input().strip().split(' ')) adj[a].append(b) adj[b].append(a) stats = solve(adj) print stats.result
1538636700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["26", "0"]
9cd17c2617b6cde593ef12b2a0a807fb
NoteIn the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.Here |x| denotes the length of string x.Please note that it's possible that there is no such string (answer is 0).
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x1 &lt; x2 &lt; ... &lt; xk where p matches s. More formally, for each xi (1 ≤ i ≤ k) he condition sxisxi + 1... sxi + |p| - 1 = p is fullfilled.Then Malekas wrote down one of subsequences of x1, x2, ... xk (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.Answer can be very large, so Tavas wants you to print the answer modulo 109 + 7.
In a single line print the answer modulo 1000 000 007.
The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1 ≤ n ≤ 106 and 0 ≤ m ≤ n - |p| + 1). The second line contains string p (1 ≤ |p| ≤ n). The next line contains m space separated integers y1, y2, ..., ym, Malekas' subsequence (1 ≤ y1 &lt; y2 &lt; ... &lt; ym ≤ n - |p| + 1).
standard output
standard input
Python 3
Python
1,900
train_008.jsonl
ad26e658856607edd1d011030c3f6763
256 megabytes
["6 2\nioi\n1 3", "5 2\nioi\n1 2"]
PASSED
# -*- coding: utf-8 -*- def solve(): n, m = map(int, input().split()) p = input() if m == 0: return powmod(n) delta = len(p) - 1 ys = map(int, input().split()) tail = 0 free_chars = 0 for y in ys: if y > tail: free_chars += y - tail - 1 elif not is_consistent(p, tail - y + 1): return 0 tail = y + delta free_chars += n - tail return powmod(free_chars) ok_set = set() def is_consistent(p, margin): global ok_set if margin in ok_set: return True elif p[:margin] == p[-margin:]: ok_set.add(margin) return True else: return False def powmod(p): mod = 10**9 + 7 pbin = bin(p)[2:][-1::-1] result = 26 if pbin[0] == '1' else 1 tmp = 26 for bit in pbin[1:]: tmp *= tmp tmp %= mod if bit == '1': result *= tmp result %= mod return result print(solve()) # Made By Mostafa_Khaled
1429029300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["3\n32767\n0\n0"]
356bd72aa9143681f1efd695969a8c8e
NoteIn the first test case the resulting value of d is hhahahaha.
Polycarp came up with a new programming language. There are only two types of statements in it: "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each. "x = a + b": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators. All variable names and strings only consist of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters.The result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.Polycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.
For each set of input data, output the number of occurrences of the haha substring in the string that was written to the variable in the last statement.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of statements in the program. All variable names and strings are guaranteed to consist only of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters. This is followed by $$$n$$$ lines describing the statements in the format described above. It is guaranteed that the program is correct.
standard output
standard input
PyPy 3
Python
2,100
train_097.jsonl
12828bf63b0ff3e74d77f7ea39882a6b
256 megabytes
["4\n6\na := h\nb := aha\nc = a + b\nc = c + c\ne = c + c\nd = a + c\n15\nx := haha\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\n1\nhaha := hah\n5\nhaahh := aaaha\nahhhh = haahh + haahh\nhaahh = haahh + haahh\nahhhh = ahhhh + haahh\nahhaa = haahh + ahhhh"]
PASSED
def naiveSolve(): return def countHaha(s): n=len(s) cnt=0 for i in range(n): if s[i:i+4]=='haha': cnt+=1 return cnt def main(): t=int(input()) allans=[] for _ in range(t): n=int(input()) d=dict() # var:[pre,suf,haha cnts] for __ in range(n): inn=input().split() curr=inn[0] if len(inn)==3: # assign obj=[inn[2][:3],inn[2][-3:],countHaha(inn[2])] d[curr]=obj else: obj1,obj2=d[inn[2]],d[inn[4]] pre=(obj1[0]+obj2[0])[:3] # takes care of short string 1 suf=(obj1[1]+obj2[1])[-3:] # takes care of short string 2 hahaCnts=obj1[2]+obj2[2]+countHaha(obj1[1]+obj2[0]) newObj=[pre,suf,hahaCnts] d[curr]=newObj allans.append(d[curr][2]) multiLineArrayPrint(allans) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(' '.join([str(x) for x in ans]))) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 for _abc in range(1): main()
1623335700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2", "2"]
03d6b61be6ca0ac9dd8259458f41da59
null
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
Output a single integer representing the maximum number of the train routes which can be closed.
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
standard output
standard input
PyPy 3
Python
2,000
train_020.jsonl
52bf62e6730c6c8583a3a54a5108ae71
256 megabytes
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
PASSED
import os, sys from io import IOBase, BytesIO py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO, self).read() def readline(self): while self.newlines == 0: s = self._fill() self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # Cout implemented in Python import sys class ostream: def __lshift__(self, a): sys.stdout.write(str(a)) return self cout = ostream() endl = "\n" import heapq def solve(): """ 1. First we calculate shortest path using dijkstra. We 1.1) While comparison of distances, in case of equal shortest paths, -> Maybe we can keep (dist, num_trains_encountered, next_node) in heapq. choose the one with more train network. 2. All train paths not on shortest path can be eliminated. """ n, m, k = map(int, input().split()) adj_list = {x: [] for x in range(n + 1)} dist = [float("inf")] * (n + 1) dist[1] = 0 hq = [(0, 1)] for _ in range(m): u, v, x = map(int, input().split()) adj_list[u].append((v, x, False)) adj_list[v].append((u, x, False)) for _ in range(k): v, y = map(int, input().split()) adj_list[1].append((v, y, True)) adj_list[v].append((1, y, True)) visited = [False] * (n + 1) prev = {} train_used = [0] * (n + 1) # Dist, Train found, Next Node. while hq: d, node = heapq.heappop(hq) if visited[node]: continue visited[node] = True for edge in adj_list[node]: nxt, w, isTrain = edge if not visited[nxt]: if d + w < dist[nxt]: dist[nxt] = d + w if isTrain: train_used[nxt] = 1 if d + w == dist[nxt] and train_used[nxt] == 1 and not isTrain: train_used[nxt] = 0 heapq.heappush(hq, (d + w, nxt)) cout<<k - sum(train_used)<<"\n" def main(): solve() if __name__ == "__main__": main()
1405774800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["3 4 6 5", "9 8 12 6 8", "3 3"]
8b727bacddcf1db490982ec388903d29
NoteConsider the first example:$$$x = [1, 2, 3, 4]$$$, so for the permutation $$$p_1(4) = [1, 2, 3, 4]$$$ the answer is $$$|1 - 2| + |2 - 3| + |3 - 4| = 3$$$; for the permutation $$$p_2(4) = [2, 1, 3, 4]$$$ the answer is $$$|2 - 1| + |1 - 3| + |3 - 4| = 4$$$; for the permutation $$$p_3(4) = [3, 1, 2, 4]$$$ the answer is $$$|2 - 3| + |3 - 1| + |1 - 4| = 6$$$; for the permutation $$$p_4(4) = [4, 1, 2, 3]$$$ the answer is $$$|2 - 3| + |3 - 4| + |4 - 1| = 5$$$. Consider the second example:$$$x = [2, 1, 5, 3, 5]$$$, so for the permutation $$$p_1(5) = [1, 2, 3, 4, 5]$$$ the answer is $$$|2 - 1| + |1 - 5| + |5 - 3| + |3 - 5| = 9$$$; for the permutation $$$p_2(5) = [2, 1, 3, 4, 5]$$$ the answer is $$$|1 - 2| + |2 - 5| + |5 - 3| + |3 - 5| = 8$$$; for the permutation $$$p_3(5) = [3, 1, 2, 4, 5]$$$ the answer is $$$|3 - 2| + |2 - 5| + |5 - 1| + |1 - 5| = 12$$$; for the permutation $$$p_4(5) = [4, 1, 2, 3, 5]$$$ the answer is $$$|3 - 2| + |2 - 5| + |5 - 4| + |4 - 5| = 6$$$; for the permutation $$$p_5(5) = [5, 1, 2, 3, 4]$$$ the answer is $$$|3 - 2| + |2 - 1| + |1 - 4| + |4 - 1| = 8$$$.
Let's define $$$p_i(n)$$$ as the following permutation: $$$[i, 1, 2, \dots, i - 1, i + 1, \dots, n]$$$. This means that the $$$i$$$-th permutation is almost identity (i.e. which maps every element to itself) permutation but the element $$$i$$$ is on the first position. Examples: $$$p_1(4) = [1, 2, 3, 4]$$$; $$$p_2(4) = [2, 1, 3, 4]$$$; $$$p_3(4) = [3, 1, 2, 4]$$$; $$$p_4(4) = [4, 1, 2, 3]$$$. You are given an array $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_i \le n$$$).Let $$$pos(p, val)$$$ be the position of the element $$$val$$$ in $$$p$$$. So, $$$pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1$$$.Let's define a function $$$f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|$$$, where $$$|val|$$$ is the absolute value of $$$val$$$. This function means the sum of distances between adjacent elements of $$$x$$$ in $$$p$$$.Your task is to calculate $$$f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$$$.
Print $$$n$$$ integers: $$$f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$$$.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$) — the number of elements in each permutation and the number of elements in $$$x$$$. The second line of the input contains $$$m$$$ integers ($$$m$$$, not $$$n$$$) $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_i \le n$$$), where $$$x_i$$$ is the $$$i$$$-th element of $$$x$$$. Elements of $$$x$$$ can repeat and appear in arbitrary order.
standard output
standard input
Python 3
Python
2,000
train_005.jsonl
24a26c27577bd071791f6d29a231e98a
256 megabytes
["4 4\n1 2 3 4", "5 5\n2 1 5 3 5", "2 10\n1 2 1 1 2 2 2 2 2 2"]
PASSED
import sys n,m = [int(x) for x in input().split()] X = [int(x) - 1 for x in input().split()] s = 0 right = [[] for _ in range(n)] left = [[] for _ in range(n)] for j in range(m - 1): a,b = X[j], X[j + 1] if a == b: continue if a > b: a,b = b,a right[a].append(b) left[b].append(a) s += b - a out = [s] for i in range(1, n): for b in right[i - 1]: s -= b for b in left[i - 1]: s -= b + 1 for b in right[i]: s -= b - i for b in left[i]: s -= i - b - 1 for b in right[i]: s += b for b in left[i]: s += b + 1 for b in right[i - 1]: s += b - (i - 1) - 1 for b in left[i - 1]: s += (i - 1) - b out.append(s) print (' '.join(str(x) for x in out))
1569940500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n2 7 9 28"]
b0b4cadc46f9fd056bf7dc36d1cf51f2
null
You are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.
Print integer k on the first line — the least number of elements needed to add to the array a to make it co-prime. The second line should contain n + k integers aj — the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it. If there are multiple answers you can print any one of them.
The first line contains integer n (1 ≤ n ≤ 1000) — the number of elements in the given array. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.
standard output
standard input
PyPy 2
Python
1,200
train_008.jsonl
d2e6e06be671ccf9377e1eb641e09220
256 megabytes
["3\n2 7 28"]
PASSED
def gcd(a,b): if b==0:return a return gcd(b,a%b) n=int(raw_input()) a=map(int,raw_input().split()) ind=0 co=0 while ind<len(a)-1: if gcd(a[ind],a[ind+1])!=1: u=gcd(a[ind],a[ind+1]) a.insert(ind+1,1) ind+=2 co+=1 else:ind+=1 print co print ' '.join(map(str,a))
1460127600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"]
20f69ee5f04c8cbb769be3ab646031ab
null
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
standard output
standard input
Python 2
Python
1,500
train_036.jsonl
0a6c3acf612476ba9543ee5703a916fc
256 megabytes
["6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0"]
PASSED
def do(t): ret = "" for item in t: ret += "0"*(4-len(item)) + item + ":" return ret n = int(raw_input()) for i in range(n): ip6 = str(raw_input()).split("::") if len(ip6) == 2: prefix,postfix = ip6[0].split(":"),ip6[1].split(":") res = do(prefix) +"0000:"*(8-len(prefix) - len(postfix))+ do(postfix) print(res[:-1]) else: print(do(ip6[0].split(":"))[:-1])
1353938400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\n3\n6"]
d70ce3b16614129c5d697a9597bcd2e3
NoteIn the first example it is possible to construct these graphs: 1 - 2, 1 - 3; 1 - 2, 1 - 3, 2 - 4; 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.
Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.
The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1.
standard output
standard input
Python 3
Python
2,100
train_018.jsonl
d84386d74e18609a864cb73abe208a05
256 megabytes
["3\n3\n4\n6"]
PASSED
#! /usr/bin/env python # http://codeforces.com/problemset/problem/818/F # Problem name ::: F. Level Generation # submission number #212055293 #508427854 def newest_approach(n): from math import floor, ceil, sqrt quad_solv = sqrt(2*n+1/4)-1/2 x = floor(quad_solv) y = ceil(quad_solv) xed = int(x*(x-1)/2 + n - x) xbr = n - x ybr = n - y yed = 2*ybr if xed > yed: print(xed) # print("nodes = %s :: edges = %s :: bridges = %s" % (n, xed, xbr)) else: print(yed) # print("nodes = %s :: edges = %s :: bridges = %s" % (n, yed, ybr)) return def main(): import sys data = [line.rstrip() for line in sys.stdin.readlines()] num_graphs = data[0] graph_sizes = [int(x) for x in data[1:]] for val in graph_sizes: # binary_search(val) # new_approach(val) newest_approach(val) if __name__ == '__main__': main()
1498748700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3 1 2 3\n2 4 5\n3 4 5 2\n2 1 3\n\n2 6 2\n3 3 5 1\n3 4 7 8\n\n2 2 1\n2 2 1\n2 2 1"]
7cc46ebe80756a5827f3b8ce06bc7974
null
The Hat is a game of speedy explanation/guessing words (similar to Alias). It's fun. Try it! In this problem, we are talking about a variant of the game when the players are sitting at the table and everyone plays individually (i.e. not teams, but individual gamers play).$$$n$$$ people gathered in a room with $$$m$$$ tables ($$$n \ge 2m$$$). They want to play the Hat $$$k$$$ times. Thus, $$$k$$$ games will be played at each table. Each player will play in $$$k$$$ games.To do this, they are distributed among the tables for each game. During each game, one player plays at exactly one table. A player can play at different tables.Players want to have the most "fair" schedule of games. For this reason, they are looking for a schedule (table distribution for each game) such that: At any table in each game there are either $$$\lfloor\frac{n}{m}\rfloor$$$ people or $$$\lceil\frac{n}{m}\rceil$$$ people (that is, either $$$n/m$$$ rounded down, or $$$n/m$$$ rounded up). Different numbers of people can play different games at the same table. Let's calculate for each player the value $$$b_i$$$ — the number of times the $$$i$$$-th player played at a table with $$$\lceil\frac{n}{m}\rceil$$$ persons ($$$n/m$$$ rounded up). Any two values of $$$b_i$$$must differ by no more than $$$1$$$. In other words, for any two players $$$i$$$ and $$$j$$$, it must be true $$$|b_i - b_j| \le 1$$$. For example, if $$$n=5$$$, $$$m=2$$$ and $$$k=2$$$, then at the request of the first item either two players or three players should play at each table. Consider the following schedules: First game: $$$1, 2, 3$$$ are played at the first table, and $$$4, 5$$$ at the second one. The second game: at the first table they play $$$5, 1$$$, and at the second  — $$$2, 3, 4$$$. This schedule is not "fair" since $$$b_2=2$$$ (the second player played twice at a big table) and $$$b_5=0$$$ (the fifth player did not play at a big table). First game: $$$1, 2, 3$$$ are played at the first table, and $$$4, 5$$$ at the second one. The second game: at the first table they play $$$4, 5, 2$$$, and at the second one  — $$$1, 3$$$. This schedule is "fair": $$$b=[1,2,1,1,1]$$$ (any two values of $$$b_i$$$ differ by no more than $$$1$$$). Find any "fair" game schedule for $$$n$$$ people if they play on the $$$m$$$ tables of $$$k$$$ games.
For each test case print a required schedule  — a sequence of $$$k$$$ blocks of $$$m$$$ lines. Each block corresponds to one game, a line in a block corresponds to one table. In each line print the number of players at the table and the indices of the players (numbers from $$$1$$$ to $$$n$$$) who should play at this table. If there are several required schedules, then output any of them. We can show that a valid solution always exists. You can output additional blank lines to separate responses to different sets of inputs.
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case consists of one line that contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le m \le \lfloor\frac{n}{2}\rfloor$$$, $$$1 \le k \le 10^5$$$) — the number of people, tables and games, respectively. It is guaranteed that the sum of $$$nk$$$ ($$$n$$$ multiplied by $$$k$$$) over all test cases does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,000
train_093.jsonl
f14abe739c2c7bfc6183f00ef5a96907
256 megabytes
["3\n5 2 2\n8 3 1\n2 1 3"]
PASSED
import sys ip = sys.stdin.readline for _ in range(int(ip())): n, m, k = map(int, ip().split()) for r in range(k): index = 0 l1 = [(j + 1 - (r * (n % m) * (n // m + 1)) + n) % n if (j + 1 - (r * (n % m) * (n // m + 1)) + n) % n !=0 else n for j in range(n)] for i in range(m): print(n // m + (i < n % m), end=" ") for j in range(n // m + (i < n % m)): print(l1[index], end=" ") index += 1 print() print()
1640010900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nYES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO"]
4c0b0cb8a11cb1fd40fef47616987029
NoteThe first five test cases contain the strings "YES", "yES", "yes", "Yes", "YeS". All of these are equal to "YES", where each character is either uppercase or lowercase.
There is a string $$$s$$$ of length $$$3$$$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.
For each test case, output "YES" (without quotes) if $$$s$$$ satisfies the condition, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yES", "yes" and "Yes" will be recognized as a positive response).
The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string $$$s$$$ consisting of three characters. Each character of $$$s$$$ is either an uppercase or lowercase English letter.
standard output
standard input
Python 3
Python
800
train_086.jsonl
124e6973cf4a7a3d863a2ca716ff3bbb
256 megabytes
["10\n\nYES\n\nyES\n\nyes\n\nYes\n\nYeS\n\nNoo\n\norZ\n\nyEz\n\nYas\n\nXES"]
PASSED
n=int(input()) for i in range(0,n): first=str(input()); if(first.upper()=="YES"): print("YES") else: print("NO")
1657636500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1", "3 4"]
c80cdf090685d40fd34c3fd082a81469
null
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.
Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.
The first line contains two integers n and m (1 ≤ n, m ≤ 100)  — the size of the table.
standard output
standard input
Python 2
Python
2,400
train_048.jsonl
4fd6f3b42ffeec2ce4fae8770f7d49e2
256 megabytes
["1 1", "1 2"]
PASSED
n, m = map(int, raw_input().split()) def f(k): if k == 1: return [1] elif k == 2: return [3, 4] elif k % 2: return [2] + [1] * (k - 2) + [(k + 1) / 2] else: return [1] * (k - 1) + [(k - 1)/ 2] for i in f(n): for j in f(m): print i * j, print
1397749200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3 3 1\n-1\n2 4 6\n69 420 666\n12345678 87654321 100000000"]
43041076ddd0bbfac62cd4abf4536282
NoteIn the first test case, $$$a=3$$$, $$$b=3$$$, $$$c=1$$$, so $$$(3 \oplus 3)+(3 \oplus 1) + (3 \oplus 1)=0+2+2=4$$$.In the second test case, there are no solutions.In the third test case, $$$(2 \oplus 4)+(4 \oplus 6) + (2 \oplus 6)=6+2+4=12$$$.
You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.
For each test case, print any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$. If no such integers exist, print $$$-1$$$.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).
standard output
standard input
PyPy 3-64
Python
800
train_088.jsonl
bd012ea6920bd4a6b0d9d7ed76b888a8
256 megabytes
["5\n\n4\n\n1\n\n12\n\n2046\n\n194723326"]
PASSED
for i in range(int(input())): a=int(input()) if a%2!=0: print(-1) else: print(0,a//2,a//2)
1656945300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES", "YES", "NO"]
2c58d94f37a9dd5fb09fd69fc7788f0d
NoteIn the first sample the initial array fits well.In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.In the third sample Yarosav can't get the array he needs.
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.Help Yaroslav.
In the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the array elements.
standard output
standard input
Python 3
Python
1,100
train_006.jsonl
bca8c1127737176135c0149a92c5f935
256 megabytes
["1\n1", "3\n1 1 2", "4\n7 7 7 7"]
PASSED
#!/usr/bin/env python # coding: utf-8 # In[204]: # # n = int(input()) # # line = list(map(int, input().split())) # # line = list(str(input())) # In[1]: from collections import Counter # In[ ]: # 56 # 516 76 516 197 516 427 174 516 706 813 94 37 516 815 516 516 937 483 16 516 842 516 638 691 516 635 516 516 453 263 516 516 635 257 125 214 29 81 516 51 362 516 677 516 903 516 949 654 221 924 516 879 516 516 972 516 # 100 # 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 # 46 # 314 723 314 314 314 235 314 314 314 314 270 314 59 972 314 216 816 40 314 314 314 314 314 314 314 381 314 314 314 314 314 314 314 789 314 957 114 942 314 314 29 314 314 72 314 314 # In[33]: n = int(input()) line = list(map(int, input().split())) # In[36]: if len(line) == 1: print("YES") else: count_dict = Counter(line) seg_val = [] seg_tmp = [] seg_len = 0 n_seg = 0 max_count = max(count_dict.values()) max_key = [] accum = 0 for k, v in count_dict.items(): if v != max_count: accum += count_dict[k] else: max_key.append(k) max_key = set(max_key) for i in range(n): if i == 0 or line[i] == line[i-1]: seg_tmp.append(line[i]) if len(seg_tmp) > 1 and (line[i] != line[i-1] or i == n-1): seg_len = max(seg_len, len(seg_tmp)) n_seg += 1 seg_val.append(seg_tmp[0]) seg_tmp = [] seg_val = set(seg_val) max_len = n//2 if n%2 == 0 else (n//2 + 1) if (seg_len > max_len) or (accum < max_count - 1 and len(max_key) < 2): print("NO") else: print("YES") # In[ ]:
1365694200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n2\n10 11", "0\n5\n14 9 28 11 16"]
b5eb2bbdba138a4668eb9736fb5258ac
NoteOperation represents the operation of bitwise exclusive OR. In other words, it is the XOR operation.
Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties: for all x the following inequality holds l ≤ x ≤ r; 1 ≤ |S| ≤ k; lets denote the i-th element of the set S as si; value must be as small as possible. Help Victor find the described set.
Print the minimum possible value of f(S). Then print the cardinality of set |S|. Then print the elements of the set in any order. If there are multiple optimal sets, you can print any of them.
The first line contains three space-separated integers l, r, k (1 ≤ l ≤ r ≤ 1012; 1 ≤ k ≤ min(106, r - l + 1)).
standard output
standard input
Python 2
Python
2,300
train_029.jsonl
8167425a4277409614cdf123d68ac905
256 megabytes
["8 15 3", "8 30 7"]
PASSED
import sys def numbers_of_one(n): res=0 while n: if n&1:res+=1 n>>=1 return res def brute_force(l,r,k): numbers=[i for i in range(l,r+1)] n=len(numbers) aux=r<<2 res=[] # import ipdb;ipdb.set_trace() for subset in range(1,1<<(r-l+1)): if numbers_of_one(subset)<=k: tmp,tmp_l=0,[] for j in range(n): if 1<<j&subset: tmp^=numbers[j] tmp_l.append(numbers[j]) if tmp<aux: aux=tmp res=tmp_l return aux,len(res),res def main(): inName='' outName='' if inName is not '' : sys.stdin=open(inName,'r') if outName is not '': sys.stdout=open(outName,'w') l,r,k=map(int,raw_input().strip().split()) if r-l<5: sol=brute_force(l,r,k) else: if k==1: sol=(l,1,[l]) if k==2: sol=(1,2,[l,l+1] if l%2==0 else [l+1,l+2]) if k>=4: if l%2==1:l+=1 sol=(0,4,[l,l+1,l+2,l+3]) if k==3: bl,br=bin(l),bin(r) szl,szr=len(bl)-2,len(br)-2 ispossible=False if szr>=szl+2: ispossible=True if szr==szl+1 and br[3]=='1': ispossible=True if ispossible: aux=2**(szl)+2**(szl-1) sol=(0,3,[l,aux,l^aux]) else: sol=(1,2,[l,l+1] if l%2==0 else [l+1,l+2]) xor,count,numbers=sol print xor print count print " ".join(map(str,numbers)) main()
1408548600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["? 1 2 3\n\n? 2 3 4\n\n? 3 4 1\n\n? 4 1 2\n\n! 2 3"]
84e79bd83c51a4966b496bb767ec4f0d
NoteArray from sample: $$$[1, 2, 0, 3]$$$.
This is an interactive problem.We picked an array of whole numbers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) and concealed exactly one zero in it! Your goal is to find the location of this zero, that is, to find $$$i$$$ such that $$$a_i = 0$$$.You are allowed to make several queries to guess the answer. For each query, you can think up three distinct indices $$$i, j, k$$$, and we will tell you the value of $$$\max(a_i, a_j, a_k) - \min(a_i, a_j, a_k)$$$. In other words, we will tell you the difference between the maximum and the minimum number among $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$.You are allowed to make no more than $$$2 \cdot n - 2$$$ queries, and after that you have two tries to guess where the zero is. That is, you have to tell us two numbers $$$i$$$ and $$$j$$$ and you win if $$$a_i = 0$$$ or $$$a_j = 0$$$.Can you guess where we hid the zero?Note that the array in each test case is fixed beforehand and will not change during the game. In other words, the interactor is not adaptive.
null
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 500$$$). Description of the test cases follows. The first and only line of each test case contains an integer $$$n$$$ ($$$4 \le n \le 1000$$$) — the length of the array that we picked. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.
standard output
standard input
PyPy 3-64
Python
2,000
train_108.jsonl
800f9dc80ec285a65de19b14bcb9801e
256 megabytes
["1\n\n4\n\n2\n\n3\n\n3\n\n2"]
PASSED
from sys import stdin, stdout, exit input = stdin.readline def f(i, j, k): aaa = [i, j, k] aaa.sort() i, j, k = aaa[0], aaa[1], aaa[2] if (i, j, k) in d.keys(): return d[(i, j, k)] print('?', i, j, k) stdout.flush() a = int(input()) d[(i, j, k)] = a return a t = int(input()) for _ in range(t): n = int(input()) d = dict() aa = [] for x in range(3, n + 1): b = f(1, 2, x) aa.append([b, x]) aa.sort() bb = [] if aa[0][0] == aa[-1][0]: for x in range(1, n + 1): if x == 3 or x == 4: continue c = f(3, 4, x) bb.append([c, x]) bb.sort() if bb[0][0] == bb[-1][0]: t1 = f(1, 2, 3) t2 = f(3, 4, 1) if t1 > t2: print('!', 1, 2) else: print('!', 3, 4) else: tt1, tt2, tt3, tt4 = 1, 2, bb[-1][1], bb[-2][1] if bb[-1][1] == 1 or bb[-1][1] == 2: tt3 = 3 if bb[-2][1] == 1 or bb[-2][1] == 2 or bb[-2][1] == tt3: if tt3 == 3: tt4 = 4 else: tt4 = 3 cc1 = f(tt1, tt2, tt3) cc2 = f(tt1, tt2, tt4) cc3 = f(tt1, tt3, tt4) cc4 = f(tt2, tt3, tt4) cc34 = min(cc3, cc4) if cc34 < cc1: print('!', tt1, tt2) else: print('!', tt3, tt4) stdout.flush() else: if aa[-1][0] > aa[-2][0]: b1 = aa[-1][1] a1 = 1 ee = [] for x in range(1, n + 1): if x == b1 or x == a1: continue tt = f(b1, a1, x) ee.append([tt, x]) ee.sort() if ee[-1][0] == ee[0][0]: print('!', b1, a1) else: print('!', b1, ee[-1][1]) stdout.flush() else: b1 = aa[-1][1] b2 = aa[-2][1] ee = [] for x in range(1, n + 1): if x == b1 or x == b2: continue tt = f(b1, b2, x) ee.append([tt, x]) ee.sort() if ee[0][0] == ee[-1][0]: print('!', b1, b2) else: print('!', ee[-1][1], b1) stdout.flush() print() stdout.flush()
1644158100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1", "2"]
cf7520d88e10ba171de443f36fdd2b73
NoteIn the first example only component $$$[3, 4, 5]$$$ is also a cycle.The illustration above corresponds to the second example.
You are given an undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. Your task is to find the number of connected components which are cycles.Here are some definitions of graph theory.An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $$$a$$$ is connected with a vertex $$$b$$$, a vertex $$$b$$$ is also connected with a vertex $$$a$$$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.Two vertices $$$u$$$ and $$$v$$$ belong to the same connected component if and only if there is at least one path along edges connecting $$$u$$$ and $$$v$$$.A connected component is a cycle if and only if its vertices can be reordered in such a way that: the first vertex is connected with the second vertex by an edge, the second vertex is connected with the third vertex by an edge, ... the last vertex is connected with the first vertex by an edge, all the described edges of a cycle are distinct. A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. There are $$$6$$$ connected components, $$$2$$$ of them are cycles: $$$[7, 10, 16]$$$ and $$$[5, 11, 9, 15]$$$.
Print one integer — the number of connected components which are also cycles.
The first line contains two integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) — number of vertices and edges. The following $$$m$$$ lines contains edges: edge $$$i$$$ is given as a pair of vertices $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$). There is no multiple edges in the given graph, i.e. for each pair ($$$v_i, u_i$$$) there no other pairs ($$$v_i, u_i$$$) and ($$$u_i, v_i$$$) in the list of edges.
standard output
standard input
PyPy 3
Python
1,500
train_003.jsonl
deaf6c00ab8765d764d4c1168f86e444
256 megabytes
["5 4\n1 2\n3 4\n5 4\n3 5", "17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6"]
PASSED
from sys import stdin def main(): n, m = map(int, stdin.readline().split()) adj = [[] for _ in range(n)] for _ in range(m): v, u = map(int, stdin.readline().split()) adj[v - 1].append(u - 1) adj[u - 1].append(v - 1) check = [False] * n stack = [] count = 0 for i in range(n): if not check[i]: first = i cycle = 1 stack = [(i, -1)] while stack: c, p = stack.pop() if check[c]: continue else: check[c] = True if len(adj[c]) > 2 or len(adj[c]) <= 1: cycle = 0 for nb in adj[c]: if nb != p: stack.append((nb, i)) count += cycle print(count) if __name__ == "__main__": main()
1525615500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1\n2 \n2\n1 3", "-1"]
810f267655da0ad14538c275fd13821d
NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. or (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).
If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.
The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1  ≤  ui,  vi  ≤  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.
standard output
standard input
Python 3
Python
1,500
train_021.jsonl
223444aaeb7e32c4d17c4332dc3b6329
256 megabytes
["4 2\n1 2\n2 3", "3 3\n1 2\n2 3\n1 3"]
PASSED
n,m=map(int,input().split()) flag=False f=[0]*100001 E=[[] for i in range(n+1)] e=[tuple(map(int,input().split())) for _ in range(m)] for u,v in sorted(e): E[u]+=[v]; E[v]+=[u] def bfs(nom,col): ch=[(nom,col)] while ch: v,c=ch.pop() if f[v]==0: f[v]=c for u in E[v]: if f[u]==0: ch+=[(u,3-c)] for x in range(1,n+1): if f[x]==0: bfs(x,1) for u,v in e: if f[u]==f[v]: flag=True; break if flag: print(-1) else: a=[i for i in range(n+1) if f[i]==1] b=[i for i in range(n+1) if f[i]==2] print(len(a)); print(*a) print(len(b)); print(*b) # Made By Mostafa_Khaled
1467219900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["3\n1 3\n3 2\n3 1", "0"]
e4dc319588cc8eca6a5c3d824e504c22
NoteLet coin $$$i$$$ facing upwards be denoted as $$$i$$$ and coin $$$i$$$ facing downwards be denoted as $$$-i$$$.The series of moves performed in the first sample changes the coins as such: $$$[~~~2,~~~1,~~~3]$$$ $$$[-3,~~~1,-2]$$$ $$$[-3,~~~2,-1]$$$ $$$[~~~1,~~~2,~~~3]$$$ In the second sample, the coins are already in their correct positions so there is no need to swap.
There are $$$n$$$ coins labeled from $$$1$$$ to $$$n$$$. Initially, coin $$$c_i$$$ is on position $$$i$$$ and is facing upwards (($$$c_1, c_2, \dots, c_n)$$$ is a permutation of numbers from $$$1$$$ to $$$n$$$). You can do some operations on these coins. In one operation, you can do the following:Choose $$$2$$$ distinct indices $$$i$$$ and $$$j$$$.Then, swap the coins on positions $$$i$$$ and $$$j$$$.Then, flip both coins on positions $$$i$$$ and $$$j$$$. (If they are initially faced up, they will be faced down after the operation and vice versa)Construct a sequence of at most $$$n+1$$$ operations such that after performing all these operations the coin $$$i$$$ will be on position $$$i$$$ at the end, facing up.Note that you do not need to minimize the number of operations.
In the first line, output an integer $$$q$$$ $$$(0 \leq q \leq n+1)$$$ — the number of operations you used. In the following $$$q$$$ lines, output two integers $$$i$$$ and $$$j$$$ $$$(1 \leq i, j \leq n, i \ne j)$$$ — the positions you chose for the current operation.
The first line contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the number of coins. The second line contains $$$n$$$ integers $$$c_1,c_2,\dots,c_n$$$ ($$$1 \le c_i \le n$$$, $$$c_i \neq c_j$$$ for $$$i\neq j$$$).
standard output
standard input
PyPy 3
Python
2,800
train_095.jsonl
0bc3f723083d60933a9affb01c4deb52
256 megabytes
["3\n2 1 3", "5\n1 2 3 4 5"]
PASSED
def swap(i, j): graph[i], graph[j] = -graph[j], -graph[i] ans.append((i, j)) def solve_pair(x, y): swap(x, y) i = x while (graph[-graph[i]] > 0): swap(i, -graph[i]) i = -graph[i] while (graph[-graph[i]] > 0): swap(i, -graph[i]) swap(i, -graph[i]) n = int(input()) j = 1 graph = [0] solved = set() for i in input().split(): graph.append(int(i)) if (int(i) == j): solved.add(j) j+=1 ans = [] cycles = set() for x in range(1, n+1): if not (x in solved): i = x solved.add(i) i = graph[i] while (i != x): solved.add(i) i = graph[i] cycles.add(i) while (len(cycles) > 1): solve_pair(cycles.pop(), cycles.pop()) if (len(cycles) == 1): j = 1 while (not (j == n+1 or j == graph[j])): j+=1 if (j != n+1): solve_pair(j, cycles.pop()) else: i, j = graph[1], graph[graph[1]] swap(1, graph[1]) solve_pair(i, j) print(len(ans)) for i in ans: print(i[0], i[1])
1614519300
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["24", "1574", "0", "667387032"]
51406f6578e8de38100c6af082bfb05e
NoteIn the first example there are: $$$6$$$ pairs of substrings "a" and "b", each with valid merging sequences "01" and "10"; $$$3$$$ pairs of substrings "a" and "bb", each with a valid merging sequence "101"; $$$4$$$ pairs of substrings "aa" and "b", each with a valid merging sequence "010"; $$$2$$$ pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010"; $$$2$$$ pairs of substrings "aaa" and "b", each with no valid merging sequences; $$$1$$$ pair of substrings "aaa" and "bb" with a valid merging sequence "01010"; Thus, the answer is $$$6 \cdot 2 + 3 \cdot 1 + 4 \cdot 1 + 2 \cdot 2 + 2 \cdot 0 + 1 \cdot 1 = 24$$$.
You are given two strings $$$x$$$ and $$$y$$$, both consist only of lowercase Latin letters. Let $$$|s|$$$ be the length of string $$$s$$$.Let's call a sequence $$$a$$$ a merging sequence if it consists of exactly $$$|x|$$$ zeros and exactly $$$|y|$$$ ones in some order.A merge $$$z$$$ is produced from a sequence $$$a$$$ by the following rules: if $$$a_i=0$$$, then remove a letter from the beginning of $$$x$$$ and append it to the end of $$$z$$$; if $$$a_i=1$$$, then remove a letter from the beginning of $$$y$$$ and append it to the end of $$$z$$$. Two merging sequences $$$a$$$ and $$$b$$$ are different if there is some position $$$i$$$ such that $$$a_i \neq b_i$$$.Let's call a string $$$z$$$ chaotic if for all $$$i$$$ from $$$2$$$ to $$$|z|$$$ $$$z_{i-1} \neq z_i$$$.Let $$$s[l,r]$$$ for some $$$1 \le l \le r \le |s|$$$ be a substring of consecutive letters of $$$s$$$, starting from position $$$l$$$ and ending at position $$$r$$$ inclusive.Let $$$f(l_1, r_1, l_2, r_2)$$$ be the number of different merging sequences of $$$x[l_1,r_1]$$$ and $$$y[l_2,r_2]$$$ that produce chaotic merges. Note that only non-empty substrings of $$$x$$$ and $$$y$$$ are considered.Calculate $$$\sum \limits_{1 \le l_1 \le r_1 \le |x| \\ 1 \le l_2 \le r_2 \le |y|} f(l_1, r_1, l_2, r_2)$$$. Output the answer modulo $$$998\,244\,353$$$.
Print a single integer — the sum of $$$f(l_1, r_1, l_2, r_2)$$$ over $$$1 \le l_1 \le r_1 \le |x|$$$ and $$$1 \le l_2 \le r_2 \le |y|$$$ modulo $$$998\,244\,353$$$.
The first line contains a string $$$x$$$ ($$$1 \le |x| \le 1000$$$). The second line contains a string $$$y$$$ ($$$1 \le |y| \le 1000$$$). Both strings consist only of lowercase Latin letters.
standard output
standard input
PyPy 3-64
Python
2,400
train_104.jsonl
ae7e9bae89e36a685ae40ec87ba72964
256 megabytes
["aaa\nbb", "code\nforces", "aaaaa\naaa", "justamassivetesttocheck\nhowwellyouhandlemodulooperations"]
PASSED
s=[0]+list(input()) t=[0]+list(input()) n=len(s)-1 m=len(t)-1 mod=998244353 for i in range(1,n+1): s[i]=ord(s[i])-96 for i in range(1,m+1): t[i]=ord(t[i])-96 def _(i,j,fs,ft,al): if min(i,j)<0:return -1 return (((i*(m+1)+j)*2+fs)*2+ft)*2+al dp=[0]*(n+3)*(m+3)*2*2*2 for i in range(n+1): for j in range(m+1): for bit in range(4): fs=(bit>>0)&1 ft=(bit>>1)&1 if fs==ft==0:continue if fs==1 and ft==0: if s[i]!=s[i-1]: dp[_(i,j,1,0,0)]+=dp[_(i-1,j,1,0,0)] dp[_(i,j,1,0,0)]%=mod if i>=1:dp[_(i,j,1,0,0)]+=1 elif fs==0 and ft==1: if t[j]!=t[j-1]: dp[_(i,j,0,1,1)]+=dp[_(i,j-1,0,1,1)] dp[_(i,j,0,1,1)]%=mod if j>=1:dp[_(i,j,0,1,1)]+=1 else: if s[i]!=s[i-1]: dp[_(i,j,1,1,0)]+=dp[_(i-1,j,1,1,0)] if s[i]!=t[j]: dp[_(i,j,1,1,0)]+=dp[_(i-1,j,1,1,1)]+dp[_(i-1,j,0,1,1)] dp[_(i,j,1,1,0)]%=mod if t[j]!=t[j-1]: dp[_(i,j,1,1,1)]+=dp[_(i,j-1,1,1,1)] if t[j]!=s[i]: dp[_(i,j,1,1,1)]+=dp[_(i,j-1,1,1,0)]+dp[_(i,j-1,1,0,0)] dp[_(i,j,1,1,1)]%=mod ans=0 for i in range(1,n+1): for j in range(1,m+1): ans+=dp[_(i,j,1,1,1)]+dp[_(i,j,1,1,0)] ans%=mod print(ans)
1616079000
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
1 second
["YES\nNO", "YES\nNO"]
5c1707b614dc3326a9bb092e6ca24280
NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.
The mobile application store has a new game called "Subway Roller".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.
For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.
Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.
standard output
standard input
Python 3
Python
1,700
train_011.jsonl
a43d3e942c8ca54d6c87d3423ee4b4a4
256 megabytes
["2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....", "2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY..."]
PASSED
T = int(input()) for t in range(T): n, k = map(int, input().split(' ')[:2]) s = ["","",""] for i in range(3): s[i] = input() s[0] += '.' * (n*3) s[1] += '.' * (n*3) s[2] += '.' * (n*3) def top(): return [s[0][0] != '.', s[1][0] != '.', s[2][0] != '.'] def shift(): s[0] = s[0][1:] s[1] = s[1][1:] s[2] = s[2][1:] return top() p = [s[0][0] == 's', s[1][0] == 's', s[2][0] == 's'] for i in range(1, n): np = [False, False, False] if p[0] == True and s[0][1] == '.': np[0] = True np[1] = True if p[1] == True and s[1][1] == '.': np[0] = True np[1] = True np[2] = True if p[2] == True and s[2][1] == '.': np[1] = True np[2] = True p = np s0, s1, s2 = shift() if s0: p[0] = False if s1: p[1] = False if s2: p[2] = False # my move ended s0, s1, s2 = shift() if s0: p[0] = False if s1: p[1] = False if s2: p[2] = False s0, s1, s2 = shift() if s0: p[0] = False if s1: p[1] = False if s2: p[2] = False if p[0] or p[1] or p[2]: print("YES") else: print("NO")
1444641000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
f94165f37e968442fa7f8be051018ad9
NoteThe picture shows the tree from the first example:
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
standard output
standard input
Python 3
Python
1,800
train_038.jsonl
6276d6fe09749355a2c6c883c4ded9f2
256 megabytes
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
PASSED
def find_ancestor(i, father): if father[i] == i: return i father[i] = find_ancestor(father[i], father) return father[i] def connect(i, j, father, n_child): i_anc = find_ancestor(i, father) j_anc = find_ancestor(j, father) if n_child[i_anc] > n_child[j_anc]: n_child[i_anc] += n_child[j_anc] father[j_anc] = i_anc else: n_child[j_anc] += n_child[i_anc] father[i_anc] = j_anc n, m = map(int, input().split()) edges = [] father = [i for i in range(n)] n_child = [1]*n for i in range(n-1): i, j, w = map(int, input().split()) edges.append((i-1, j-1, w)) edges.sort(key=lambda x: -x[2]) queries = list(map(int, input().split())) s_queries = sorted(queries) # final map the index to the query ans = {} w_limit = [] ans_cum = 0 for query in s_queries: while len(edges) and edges[-1][2] <= query: i, j, w = edges[-1] edges.pop() i_anc = find_ancestor(i, father) j_anc = find_ancestor(j, father) # it's tree father may not be same ans_cum += n_child[i_anc] * n_child[j_anc] connect(i, j, father, n_child) ans[query] = ans_cum print(" ".join(list(map(str, [ans[query] for query in queries]))))
1567175700
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
eea15ff7e939bfcc7002cacbc8a1a3a5
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
standard output
standard input
PyPy 2
Python
1,300
train_002.jsonl
134d8be64008fe6aadcf84c23931e120
256 megabytes
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
PASSED
T = input() for _ in xrange(T): N = input() ll = [] for _ in xrange(N): ll.append(raw_input()) oc = 0 for i in xrange(N-1, -1, -1): for j in xrange(N-1, -1, -1): if ll[i][j] == "1": oc += 1 seen = set() for i in xrange(N-1, -1, -1): for j in xrange(N-1, -1, -1): if ll[i][j] == "0": break if ll[i][j] == "1" and (i, j) not in seen: q = [(i, j)] seen.add((i, j)) while len(q) > 0: x, y = q.pop(-1) if x > 0 and ll[x-1][y] == "1" and (x-1, y) not in seen: q.append((x-1, y)) seen.add((x-1, y)) if y > 0 and ll[x][y-1] == "1" and (x,y-1) not in seen: q.append((x, y-1)) seen.add((x, y-1)) for j in xrange(N-1, -1, -1): for i in xrange(N-1, -1, -1): if ll[i][j] == "0": break if ll[i][j] == "1" and (i, j) not in seen: q = [(i, j)] seen.add((i, j)) while len(q) > 0: x, y = q.pop(-1) if x > 0 and ll[x-1][y] == "1" and (x-1, y) not in seen: q.append((x-1, y)) seen.add((x-1, y)) if y > 0 and ll[x][y-1] == "1" and (x,y-1) not in seen: q.append((x, y-1)) seen.add((x, y-1)) if oc != len(seen): print "NO" else: print "YES"
1590327300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["17\n33\n401"]
168dbc4994529f5407a440b0c71086da
null
There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw? The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses.
For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
The first line contains integer t (1 ≤ t ≤ 104) — the number of test cases. The second line contains t space-separated integers ni (1 ≤ ni ≤ 109) — the sides of the square for each test sample.
standard output
standard input
PyPy 2
Python
1,200
train_003.jsonl
8bc650809d3c38e40907508e9d622e6d
256 megabytes
["3\n4 8 100"]
PASSED
n = int(raw_input()) parts = [int(x) for x in raw_input().split()] for p in parts: if p % 2 == 0: print p * 4 + 1 else: if (p + 3) % 4 == 0: res = 1 + (((p + 3) / 4) - 1) * 4 print res * 2 + 1 elif (p + 1) % 4 == 0 : res = 3 + (((p + 1) / 4) - 1) * 4 print res + 1
1338737400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["NO", "cbd", "abda"]
788ae500235ca7b7a7cd320f745d1070
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
standard output
standard input
Python 3
Python
1,700
train_008.jsonl
a05a078168deb527aed10baa84d17216
256 megabytes
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
PASSED
#!/usr/bin/python3 import sys def solve(s, k): l = len(s) for i in range(l-1, -1, -1): prev = s[max(i-2, 0):i] z = s[i] + 1 while z in prev: z += 1 if z >= k: continue # Gotcha! ret = s[:i] + [z] while len(ret) < l: prev = ret[max(len(ret)-2, 0):len(ret)] z = 0 while z in prev: z += 1 ret.append(z) return ret return None if __name__ == '__main__': l, k = map(int, sys.stdin.readline().split()) s = [ord(c) - ord('a') for c in sys.stdin.readline().strip()] ans = solve(s, k) if ans is None: print('NO') else: print(''.join(chr(ord('a') + x) for x in ans))
1410103800
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\n7\n47837"]
b7e36ca8a96dd7951359070d4953beec
NoteIn the first test case, $$$m = 2$$$, which is prime, and $$$n + m = 7 + 2 = 9$$$, which is not prime.In the second test case, $$$m = 7$$$, which is prime, and $$$n + m = 2 + 7 = 9$$$, which is not prime.In the third test case, $$$m = 47837$$$, which is prime, and $$$n + m = 75619 + 47837 = 123456$$$, which is not prime.
Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.
For each test case, output a line containing a prime number $$$m$$$ ($$$2 \leq m \leq 10^5$$$) such that $$$n + m$$$ is not prime. It can be proven that under the constraints of the problem, such $$$m$$$ always exists. If there are multiple solutions, you can output any of them.
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The only line of each test case contains a prime number $$$n$$$ ($$$2 \leq n \leq 10^5$$$).
standard output
standard input
PyPy 3-64
Python
800
train_096.jsonl
774f0c599354fb300cb5f0feecf78838
256 megabytes
["3\n\n7\n\n2\n\n75619"]
PASSED
def solve(): j = int(input()) if j != 2: print(3) else: print(2) for t in range(int(input())): solve()
1667034600
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["2\n3 1\n1 3", "3\n1 1\n6 5\n8 7", "-1"]
c6c4a833843d479c94f9ebd3e2774775
NoteIn the first sample string "cbaabc" = "cba" + "abc".In the second sample: "ayrat" = "a" + "yr" + "at".
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.
The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating. If the answer is not -1, then the following n lines should contain two integers xi and yi — numbers of ending blocks in the corresponding piece. If xi ≤ yi then this piece is used in the regular order, and if xi &gt; yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.
First line of the input contains the string s — the coating that is present in the shop. Second line contains the string t — the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.
standard output
standard input
Python 3
Python
2,000
train_078.jsonl
5e81abdbd5f336c0f6a7e42c4ebd7e79
512 megabytes
["abc\ncbaabc", "aaabrytaaa\nayrat", "ami\nno"]
PASSED
s = input() t = input() revS = s[::-1] n = len(s) cur=1 start=-1 end=-1 revFlag=0 errFlag=0 i=0 res=[] while i < len(t): if s.find(t[i:i+cur]) != -1 and i+cur <= len(t) and s.find(t[i:i+cur]) + cur <= n: start = s.find(t[i:i+cur]) + 1 end = start + cur - 1 cur += 1 elif revS.find(t[i:i+cur]) != -1 and i+cur <= len(t) and revS.find(t[i:i+cur]) + cur <= n: start = n - revS.find(t[i:i+cur]) end = start - cur + 1 cur += 1 else: if (start == -1 and end == -1) and (s.find(t[i:i+cur]) == -1 and revS.find(t[i:i+cur]) == -1): errFlag = 1 break i += cur - 1 cur = 1 res.append(str(start) + " " + str(end)) start = -1 end = -1 if errFlag != 1: print(len(res)) for p in res: print(p) else: print(-1)
1452261900
[ "strings", "trees" ]
[ 0, 0, 0, 0, 0, 0, 1, 1 ]
1 second
["YES\n1 9\n1 5\n1 10\n1 6\n1 2", "NO", "YES\n3 5 1 3\n1 7\n1 2"]
5185f842c7c24d4118ae3661f4418a1d
null
Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning.
In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition.
The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
standard input
Python 2
Python
1,700
train_002.jsonl
c790b269a6f03e54a3cb4a99631ca2a4
256 megabytes
["5 5 3\n2 6 10 5 9", "5 5 3\n7 14 2 9 5", "5 3 1\n1 2 3 7 5"]
PASSED
n,k,p=raw_input().strip().split(' ') n,k,p=int(n),int(k),int(p) arr=list(map(int,raw_input().strip().split(' '))) odd=[j for j in arr if j&1] even=[j for j in arr if not j&1] if (k-p)>len(odd) or p>len(even)+(len(odd)-k+p)/2 or len(odd)%2!=(k-p)%2: print 'NO' else: print 'YES' count,j=0,0 while j<len(even) and count<p-1: print 1,even[j] j+=1 count+=1 i=1 while i<len(odd) and count<p-1: print 2,odd[i],odd[i-1] i+=2 count+=1 if count!=p and k-p==0: print len(odd[i-1:])+len(even[j:]), for i in odd[i-1:]: print i, for i in even[j:]: print i elif count!=p: if j<len(even): print 1,even[j] j+=1 else: print 2,odd[i],odd[i-1] i+=2 count=0 i-=1 while j<len(even) and i<len(odd) and count<k-p-1: print 2,odd[i],even[j] i,j,count=i+1,j+1,count+1 while i<len(odd) and count<k-p-1: print 1,odd[i] count+=1 i+=1 if k-p!=0: print len(odd[i:])+len(even[j:]), for k in xrange(i,len(odd)): print odd[k], for t in xrange(j,len(even)): print even[t],
1401895800
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["YES\n010001\n100100\n001010\nNO\nYES\n11\n11\nYES\n1100\n1100\n0011\n0011\nYES\n1\n1"]
8aa648ff5adc0cf7b20fea52d2c34759
null
You are given four positive integers $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$). Find any such rectangular matrix of size $$$n \times m$$$ that satisfies all of the following conditions: each row of the matrix contains exactly $$$a$$$ ones; each column of the matrix contains exactly $$$b$$$ ones; all other elements are zeros. If the desired matrix does not exist, indicate this.For example, for $$$n=3$$$, $$$m=6$$$, $$$a=2$$$, $$$b=1$$$, there exists a matrix satisfying the conditions above:$$$$$$ \begin{vmatrix} 0 &amp; 1 &amp; 0 &amp; 0 &amp; 0 &amp; 1 \\ 1 &amp; 0 &amp; 0 &amp; 1 &amp; 0 &amp; 0 \\ 0 &amp; 0 &amp; 1 &amp; 0 &amp; 1 &amp; 0 \end{vmatrix} $$$$$$
For each test case print: "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or "NO" (without quotes) if it does not exist. To print the matrix $$$n \times m$$$, print $$$n$$$ rows, each of which consists of $$$m$$$ numbers $$$0$$$ or $$$1$$$ describing a row of the matrix. Numbers must be printed without spaces.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is described by four positive integers $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$), where $$$n$$$ and $$$m$$$ are the sizes of the matrix, and $$$a$$$ and $$$b$$$ are the number of ones for rows and columns, respectively.
standard output
standard input
PyPy 3
Python
1,900
train_000.jsonl
94a7d72264d735562157d6bb6d342f3e
256 megabytes
["5\n3 6 2 1\n2 2 2 1\n2 2 2 2\n4 4 2 2\n2 1 1 2"]
PASSED
# python3 q7.py < test.txt t = int(input()) for i in range(t): n, m, a, b = map(int, input().split()) if n * a != m * b: print('NO') continue print('YES') shift = 0 for j in range(1, m): if (j * n) % m == 0: shift = j break col = [j for j in range(a)] ans = [[0 for j in range(m)] for k in range(n)] for j in range(n): for k in col: ans[j][k] = 1 for k in range(m): print(ans[j][k], end = '') print('') col = [(x + shift) % (m) for x in col]
1590327300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["10", "12"]
f6be5319ad3733d07a8ffd089fc44c71
Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Print a single integer — the minimal possible time in seconds.
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
standard output
standard input
Python 3
Python
2,400
train_000.jsonl
f3b52703a3398876a22c97bbec7ae1b5
256 megabytes
["2\n3 5\n5 3", "2\n5 3\n3 5"]
PASSED
# python3 import sys from collections import namedtuple def readline(): return map(int, input().split()) def readlines(): for line in sys.stdin.readlines(): yield map(int, line.split()) class State(namedtuple('State', 'payload time floor')): def hook(self, pivot, a, b): lo, up = min(pivot, a, self.floor), max(pivot, a, self.floor) return tuple(x for x in self.payload if x < lo or up < x) + (b,), \ self.time + abs(self.floor - pivot) + abs(pivot - a) def choices_to_take_next(self, a, b): floor = self.floor payload, time = self.hook(floor, a, b) if len(payload) < 5: yield payload, time if floor > a: pivots = (x for x in self.payload if x > floor) elif floor == a: pivots = () else: pivots = (x for x in self.payload if x < floor) else: pivots = self.payload for pivot in pivots: yield self.hook(pivot, a, b) def time_to_get_free(payload, floor): if payload: lo, up = min(payload), max(payload) return abs(lo-up) + min(abs(floor-lo), abs(floor-up)) else: return 0 def main(): n, = readline() floor = 1 positions = {(): 0} # empty elevator, time = 0 for (a, b) in readlines(): max_acceptable_time = min(positions.values()) + 16 - abs(floor - a) new_positions = dict() for payload, time in positions.items(): state = State(payload, time, floor) for npayload, ntime in state.choices_to_take_next(a, b): if ntime <= max_acceptable_time: npayload = tuple(sorted(npayload)) if new_positions.setdefault(npayload, ntime) > ntime: new_positions[npayload] = ntime positions = new_positions floor = a return min(t + time_to_get_free(p, floor) for p, t in positions.items()) \ + 2 * n print(main())
1526395500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4\n0\n9"]
d638f524fe07cb8e822b5c6ec3fe8216
NoteIn the first example, the array elements can be rearranged as follows: $$$[6, 3, 5, 3]$$$.In the third example, the array elements can be rearranged as follows: $$$[4, 4, 2, 1, 1]$$$.
You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let's call a pair of indices $$$i$$$, $$$j$$$ good if $$$1 \le i &lt; j \le n$$$ and $$$\gcd(a_i, 2a_j) &gt; 1$$$ (where $$$\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$).Find the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.
For each test case, output a single integer — the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$) — the number of elements in the array. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.
standard output
standard input
PyPy 3-64
Python
900
train_085.jsonl
41f15511be886488a70eb56581aee085
256 megabytes
["3\n4\n3 6 5 3\n2\n1 7\n5\n1 4 2 4 1"]
PASSED
from math import gcd for _ in range(int(input())): n = int(input()) cnt = 0 seq = tuple(map(int, input().split())) for i in range(n): for j in range(i + 1, n): a, b = seq[i], seq[j] if gcd(a, 2 * b) > 1 or gcd(b, a * 2) > 1: cnt += 1 print(cnt)
1622817300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n3", "2\n1 2", "0"]
0df064fd0288c2ac4832efa227107a0e
null
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0.
The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one.
standard output
standard input
Python 3
Python
1,500
train_021.jsonl
44ef1bcdf34b51a2efb57835b1501269
256 megabytes
["abdrakadabra\nabrakadabra", "aa\na", "competition\ncodeforces"]
PASSED
s = input().strip() t = input().strip() diff = len(s) - 1 for i in range(len(t)): if s[i] != t[i]: diff = i break for i in range(diff + 1, len(s)): if s[i] != t[i - 1]: print(0) import sys; sys.exit() start = diff while start != 0 and s[start - 1] == s[diff]: start -= 1 print(diff - start + 1) print(' '.join(map(str, range(start + 1, diff + 2))))
1287904200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2.5 seconds
["4\n3\n4\n2\n3\n4\n1\n2\n3\n4", "5\n3\n3\n3"]
c90c7a562c8221dd428c807c919ae156
NoteIn the first example Misha's mother is interested in the first $$$10$$$ years after the rule was introduced. The host cities these years are 4, 3, 4, 2, 3, 4, 1, 2, 3, 4.In the second example the host cities after the new city is introduced are 2, 3, 1, 2, 3, 5, 1, 2, 3, 4, 5, 1.
Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first $$$n$$$ olympiads the organizers introduced the following rule of the host city selection.The host cities of the olympiads are selected in the following way. There are $$$m$$$ cities in Berland wishing to host the olympiad, they are numbered from $$$1$$$ to $$$m$$$. The host city of each next olympiad is determined as the city that hosted the olympiad the smallest number of times before. If there are several such cities, the city with the smallest index is selected among them.Misha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first $$$n$$$ olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house.
Print $$$q$$$ integers. The $$$i$$$-th of them should be the city the olympiad will be hosted in the year $$$k_i$$$.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \leq n, m, q \leq 500\,000$$$) — the number of olympiads before the rule was introduced, the number of cities in Berland wishing to host the olympiad, and the number of years Misha's mother is interested in, respectively. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq m$$$), where $$$a_i$$$ denotes the city which hosted the olympiad in the $$$i$$$-th year. Note that before the rule was introduced the host city was chosen arbitrarily. Each of the next $$$q$$$ lines contains an integer $$$k_i$$$ ($$$n + 1 \leq k_i \leq 10^{18}$$$) — the year number Misha's mother is interested in host city in.
standard output
standard input
PyPy 2
Python
2,200
train_018.jsonl
7fbfbf4d7b0928052a38ba6dd170f875
512 megabytes
["6 4 10\n3 1 1 1 2 2\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16", "4 5 4\n4 4 5 1\n15\n9\n13\n6"]
PASSED
class seg: def __init__(self, n): self.n = n m = 1 while m < n: m *= 2 self.m = m self.data = [0]*(2 * m) def add(self, ind): ind += self.m while ind: self.data[ind] += 1 ind >>= 1 def binary(self,k): ind = 1 while ind < self.m: ind <<= 1 if self.data[ind] < k: k -= self.data[ind] ind |= 1 return ind - self.m # This mergesort can be like 7 times faster than build in sort # (for stupid reasons) def mergesort(n, key, reverse=False): A = list(range(n)) B = list(A) n = len(A) for i in range(0, n - 1, 2): if key(A[i]) > key(A[i ^ 1]): A[i], A[i ^ 1] = A[i ^ 1], A[i] width = 2 while width < n: for i in range(0, n, 2 * width): R1, R2 = min(i + width, n), min(i + 2 * width, n) j, k = R1, i while i < R1 and j < R2: if key(A[i]) > key(A[j]): B[k] = A[j] j += 1 else: B[k] = A[i] i += 1 k += 1 while i < R1: B[k] = A[i] k += 1 i += 1 while k < R2: B[k] = A[k] k += 1 A, B = B, A width *= 2 if reverse: A.reverse() return A def main(): n, m, q = [int(x) for x in input().split()] A = [int(x) for x in input().split()] hosts = [0.0]*m for a in A: hosts[a-1] += 1.0 order = mergesort(m, hosts.__getitem__) years = [] s = 0.0 for before,i in enumerate(order): years.append(before * hosts[i] - s) s += hosts[i] big = 1000000000000 big -= big % m bigf = float(big) def mapper(x): if len(x) <= 12: return float(x) return (int(x) % m) + bigf B = [mapper(x) - n - 1 for x in sys.stdin.buffer.read().split()] qorder = mergesort(q, B.__getitem__, reverse=True) ans = [0]*q segg = seg(m) for before,i in enumerate(order): segg.add(i) while qorder and (before == m-1 or years[before + 1] > B[qorder[-1]]): qind = qorder.pop() q = int((B[qind] - years[before]) % (before + 1)) ans[qind] = segg.binary(q + 1) + 1 print '\n'.join(str(x) for x in ans) ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is different which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A if __name__== "__main__": main()
1560677700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["8\n198\n-17\n2999999997\n0\n1"]
1f435ba837f59b007167419896c836ae
NoteIn the first query frog jumps $$$5$$$ to the right, $$$2$$$ to the left and $$$5$$$ to the right so the answer is $$$5 - 2 + 5 = 8$$$.In the second query frog jumps $$$100$$$ to the right, $$$1$$$ to the left, $$$100$$$ to the right and $$$1$$$ to the left so the answer is $$$100 - 1 + 100 - 1 = 198$$$.In the third query the answer is $$$1 - 10 + 1 - 10 + 1 = -17$$$.In the fourth query the answer is $$$10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$$$.In the fifth query all frog's jumps are neutralized by each other so the answer is $$$0$$$.The sixth query is the same as the fifth but without the last jump so the answer is $$$1$$$.
A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally: if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$; otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.
Print $$$t$$$ integers. The $$$i$$$-th integer should be the answer for the $$$i$$$-th query.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. Each of the next $$$t$$$ lines contain queries (one query per line). The query is described as three space-separated integers $$$a, b, k$$$ ($$$1 \le a, b, k \le 10^9$$$) — the lengths of two types of jumps and the number of jumps, respectively.
standard output
standard input
Python 3
Python
800
train_006.jsonl
3c33641a665dc5186fa005d089a543b4
256 megabytes
["6\n5 2 3\n100 1 4\n1 10 5\n1000000000 1 6\n1 1 1000000000\n1 1 999999999"]
PASSED
from math import ceil as c t = int(input()) while t != 0: a, b, k = map(int, input().split()) j_right = c(k / 2) j_left = k // 2 print((j_right * a) - (j_left * b)) t -= 1
1542378900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Alice\nBob\nAlice\nAlice"]
2bfd566ef883efec5211b01552b45218
NoteIn the first test case, Alice can win by moving to vertex $$$1$$$. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices $$$1$$$ or $$$6$$$ is farthest from Alice.
Alice and Bob are playing a fun game of tree tag.The game is played on a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. Recall that a tree on $$$n$$$ vertices is an undirected, connected graph with $$$n-1$$$ edges.Initially, Alice is located at vertex $$$a$$$, and Bob at vertex $$$b$$$. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most $$$da$$$ from the current vertex. And in a move, Bob can jump to a vertex with distance at most $$$db$$$ from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.If after at most $$$10^{100}$$$ moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.Determine the winner if both players play optimally.
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains five integers $$$n,a,b,da,db$$$ ($$$2\le n\le 10^5$$$, $$$1\le a,b\le n$$$, $$$a\ne b$$$, $$$1\le da,db\le n-1$$$)  — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following $$$n-1$$$ lines describe the edges of the tree. The $$$i$$$-th of these lines contains two integers $$$u$$$, $$$v$$$ ($$$1\le u, v\le n, u\ne v$$$), denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,900
train_023.jsonl
9e32d7caaf92ef430521ff4df73027dc
256 megabytes
["4\n4 3 2 1 2\n1 2\n1 3\n1 4\n6 6 1 2 5\n1 2\n6 5\n2 3\n3 4\n4 5\n9 3 9 2 5\n1 2\n1 6\n1 9\n1 3\n9 5\n7 9\n4 8\n4 3\n11 8 11 3 3\n1 2\n11 9\n4 9\n6 5\n2 10\n3 2\n5 9\n8 3\n7 4\n7 10"]
PASSED
from collections import deque def dfs(x): length[x] = 0 queue = deque() queue.append(x) while queue: y = queue.popleft() for z in t[y]: if length[z] is None: length[z] = length[y]+1 queue.append(z) for _ in range(int(input())): n,a,b,da,db = list(map(int,input().split())) t = [[] for i in range(n)] for x in range(n-1): u,v = list(map(int,input().split())) t[u-1].append(v-1) t[v-1].append(u-1) length = [None]*n dfs(a-1) lb = length[b-1] mx = max(length) nex = length.index(mx) length = [None]*n dfs(nex) if da >= lb or 2 * da >= db or 2 * da >= max(length): print("Alice") else: print("Bob")
1599402900
[ "games", "trees" ]
[ 1, 0, 0, 0, 0, 0, 0, 1 ]
10 seconds
["NO\nYES\n1 2\n6\n2 3\nYES\n1 1\n1\n1\nYES\n3 2\n3 7 4\n12 14"]
f596e0bcefde8227e8a7b9d923da828a
null
You are given two sets of positive integers $$$A$$$ and $$$B$$$. You have to find two non-empty subsets $$$S_A \subseteq A$$$, $$$S_B \subseteq B$$$ so that the least common multiple (LCM) of the elements of $$$S_A$$$ is equal to the least common multiple (LCM) of the elements of $$$S_B$$$.
For each test case, if there do not exist two subsets with equal least common multiple, output one line with NO. Otherwise, output one line with YES, followed by a line with two integers $$$|S_A|, |S_B|$$$ ($$$1 \leq |S_A| \leq n$$$, $$$1 \leq |S_B| \leq m$$$), the sizes of the subsets $$$S_A$$$ and $$$S_B$$$ The next line should contain $$$|S_A|$$$ integers $$$x_1, x_2, \ldots, x_{|S_A|}$$$, the elements of $$$S_A$$$, followed by a line with $$$|S_B|$$$ integers $$$y_1, y_2, \ldots, y_{|S_B|}$$$, the elements of $$$S_B$$$. If there are multiple possible pairs of subsets, you can print any.
The input consists of multiple test cases. The first line of the input contains one integer $$$t$$$ ($$$1 \leq t \leq 200$$$), the number of test cases. For each test case, there is one line containing two integers $$$n, m$$$ ($$$1 \leq n, m \leq 1000$$$), the sizes of the sets $$$A$$$ and $$$B$$$, respectively. The next line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 4 \cdot 10^{36}$$$), the elements of $$$A$$$. The next line contains $$$m$$$ distinct integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 4 \cdot 10^{36}$$$), the elements of $$$B$$$. The sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases is at most $$$1000$$$.
standard output
standard input
PyPy 3
Python
3,200
train_092.jsonl
f0c2aece285fddc23cc7af1d79bbbf3e
512 megabytes
["4\n3 4\n5 6 7\n2 8 9 10\n4 4\n5 6 7 8\n2 3 4 9\n1 3\n1\n1 2 3\n5 6\n3 4 9 7 8\n2 15 11 14 20 12"]
PASSED
import math for _ in range(int(input())): n, m = [*map(int, input().split())] N, M = 1<<(len(bin(n-1))-2), 1<<(len(bin(m-1))-2) a = [*map(int, input().split())] b = [*map(int, input().split())] d = [[math.gcd(i,j) for i in b] for j in a] d1, d2 = [[0]*(M<<1) for i in range(n)], [[0]*(N<<1) for i in range(m)] def upd(d, i): while i>1: d[i>>1]=math.gcd(d[i], d[i^1]); i>>=1 s1, s2 = set(range(n)), set(range(m)) def updr(s1, s2, d1, d2, t, i, now): s1.discard(i) for idx in list(s2): if idx > now: break x=d2[idx] if x[1] == 1: x[i+t]=0 upd(x,i+t) if x[1] != 1: updr(s2, s1, d2, d1, M+N-t, idx, now) for i in range(max(m,n)): if i < n: for j in s2: d1[i][j+M] = a[i] // d[i][j] for j in range(M-1, 0, -1): d1[i][j] = math.gcd(d1[i][j<<1], d1[i][j<<1|1]) if d1[i][1] != 1: updr(s1, s2, d1, d2, N, i, i) if i < m: for j in s1: d2[i][j+N] = b[i] // d[j][i] for j in range(N-1, 0, -1): d2[i][j] = math.gcd(d2[i][j<<1], d2[i][j<<1|1]) if d2[i][1] != 1: updr(s2, s1, d2, d1, M, i, i) # print(i, len(s1), len(s2)) if len(s1): print('YES'); print(len(s1), len(s2)); print(*[a[i] for i in s1]); print(*[b[i] for i in s2]) else: print('NO')
1648132500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["5\n6\n2\n948683296\n2996666667"]
10812427d3052ce91cd0951911d3acb9
NoteIn the first test case, $$$5$$$ luxury numbers in range $$$[8, 19]$$$ are: $$$8, 9, 12, 15, 16$$$.
While working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football.Since she started engaging in sports activities, Ela switches to trying a new sport on days she considers being "Luxury" days. She counts the days since she started these activities, in which the day she starts is numbered as day $$$1$$$. A "Luxury" day is the day in which the number of this day is a luxurious number. An integer $$$x$$$ is called a luxurious number if it is divisible by $$${\lfloor \sqrt{x} \rfloor}$$$.Here $$$\lfloor r \rfloor$$$ denotes the "floor" of a real number $$$r$$$. In other words, it's the largest integer not greater than $$$r$$$.For example: $$$8$$$, $$$56$$$, $$$100$$$ are luxurious numbers, since $$$8$$$ is divisible by $$$\lfloor \sqrt{8} \rfloor = \lfloor 2.8284 \rfloor = 2$$$, $$$56$$$ is divisible $$$\lfloor \sqrt{56} \rfloor = \lfloor 7.4833 \rfloor = 7$$$, and $$$100$$$ is divisible by $$$\lfloor \sqrt{100} \rfloor = \lfloor 10 \rfloor = 10$$$, respectively. On the other hand $$$5$$$, $$$40$$$ are not, since $$$5$$$ are not divisible by $$$\lfloor \sqrt{5} \rfloor = \lfloor 2.2361 \rfloor = 2$$$, and $$$40$$$ are not divisible by $$$\lfloor \sqrt{40} \rfloor = \lfloor 6.3246 \rfloor = 6$$$.Being a friend of Ela, you want to engage in these fitness activities with her to keep her and yourself accompanied (and have fun together, of course). Between day $$$l$$$ and day $$$r$$$, you want to know how many times she changes the activities.
For each test case, output an integer that denotes the answer.
Each test contains multiple test cases. The first line has the number of test cases $$$t$$$ ($$$1 \le t \le 10\ 000$$$). The description of the test cases follows. The only line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^{18}$$$) — the intervals at which you want to know how many times Ela changes her sports.
standard output
standard input
Python 3
Python
1,300
train_094.jsonl
a646f1ee91fa92b98867c263fba6bb61
256 megabytes
["5\n\n8 19\n\n8 20\n\n119 121\n\n1 100000000000000000\n\n1234567891011 1000000000000000000"]
PASSED
import sys,math input=sys.stdin.readline for _ in range(int(input())): #n=int(input()) l,r=map(int,input().split()) #a=list(map(int,input().split())) a=math.isqrt(l) b=math.isqrt(r) ans=0 if a==b: if r>=a**2>=l: ans+=1 if r>=(a**2)+2*a>=l: ans+=1 if r>=(a**2)+a>=l: ans+=1 else: if a+1<=b-1: ans+=3*(b-1-a) if a**2>=l: ans+=1 if (a**2)+2*a>=l: ans+=1 if (a**2)+a>=l: ans+=1 if b**2<=r: ans+=1 if (b**2)+2*b<=r: ans+=1 if (b**2)+b<=r: ans+=1 print(ans)
1665153300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
8 seconds
["8.0000000000 0.0000000000\n5.0000000000 -3.0000000000\n4.2568551745 -2.6691306064\n4.2568551745 -3.6691306064"]
fb46e7a175719eabd9f82a116bccd678
NoteThe following pictures shows the state of the arm after each operation. The coordinates of point F are printed after applying each operation. For simplicity, we only show the blue endpoints of a segment (with the exception for the red endpoint of the first segment). For instance, the point labeled B is the blue endpoint for segment 1 and also the red endpoint for segment 2.Initial state: Extend segment 1 by 3. Rotate segment 3 by 90 degrees clockwise. Rotate segment 5 by 48 degrees clockwise. Extend segment 4 by 1.
Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.Roger can move his arm in two different ways: He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray. In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated. He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint. In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A. Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.
Print m lines. The i-th line should contain two real values, denoting the coordinates of the blue endpoint of the last segment after applying operations 1, ..., i. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if for all coordinates.
The first line of the input will contain two integers n and m (1 ≤ n, m ≤ 300 000) — the number of segments and the number of operations to perform. Each of the next m lines contains three integers xi, yi and zi describing a move. If xi = 1, this line describes a move of type 1, where yi denotes the segment number and zi denotes the increase in the length. If xi = 2, this describes a move of type 2, where yi denotes the segment number, and zi denotes the angle in degrees. (1 ≤ xi ≤ 2, 1 ≤ yi ≤ n, 1 ≤ zi ≤ 359)
standard output
standard input
PyPy 3
Python
2,500
train_064.jsonl
e6f2d9aa7a59ca5bcd62065bce87a4ee
256 megabytes
["5 4\n1 1 3\n2 3 90\n2 5 48\n1 4 1"]
PASSED
from cmath import rect import sys import math from functools import reduce class SegmentTree(): def __init__(self, L, function = lambda x,y: x+y): self.function = function N = self.size = len(L) M = 1 << N.bit_length() self.margin = 2*M - N self.L = [None for i in range(self.margin)] + L for i in range(M-1, 0, -1): x, y = self.L[i<<1], self.L[i<<1|1] self.L[i] = None if x is None or y is None else function(x, y) def modify(self, pos, value): p = pos + self.margin self.L[p] = value while p > 1: x, y = self.L[p], self.L[p^1] if p&1: x, y = y, x self.L[p>>1] = None if x is None or y is None else self.function(x, y) p>>=1 def query(self, left, right): l, r = left + self.margin, right + self.margin stack = [] void = True while l < r: if l&1: if void: result = self.L[l] void = False else: result = self.function(result, self.L[l]) l+=1 if r&1: r-=1 stack.append(self.L[r]) l>>=1 r>>=1 init = stack.pop() if void else result return reduce(self.function, reversed(stack), init) def degrect(r, phi): return rect(r, math.radians(phi)) def vsum(u, v): #u = (x + y*1j, phi) return (u[0] + v[0]*degrect(1, u[1]), (u[1] + v[1])%360) def solve(f): n, m = [int(x) for x in f.readline().split()] segments = [[1,0] for i in range(n)] arm = SegmentTree([(1,0) for i in range(n)], vsum) for line in f: q, i, a = [int(x) for x in line.split()] if q == 1: segments[i-1][0] += a else: segments[i-1][1] -= a arm.modify(i-1, (degrect(segments[i-1][0], segments[i-1][1]), segments[i-1][1])) query = arm.query(0,n)[0] print(query.real, query.imag) solve(sys.stdin)
1454087400
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["13\n1 0\n2 1\n3 2\n3 1\n2 2\n4 3\n4 1\n5 2\n5 1\n4 2\n2 3\n2 0\n1 1"]
b45e785361f3da9a56a0063cd4f97eaa
null
Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him. The map of the city where they live has a lot of squares, some of which are connected by roads. There is exactly one way between each pair of squares which does not visit any vertex twice. It turns out that the graph of the city is a tree.Denis is located at vertex $$$1$$$ at the time $$$0$$$. He wants to visit every vertex at least once and get back as soon as possible.Denis can walk one road in $$$1$$$ time. Unfortunately, the city is so large that it will take a very long time to visit all squares. Therefore, Denis took a desperate step. He pulled out his pocket time machine, which he constructed in his basement. With its help, Denis can change the time to any non-negative time, which is less than the current time.But the time machine has one feature. If the hero finds himself in the same place and at the same time twice, there will be an explosion of universal proportions and Nastya will stay unhappy. Therefore, Denis asks you to find him a route using a time machine that he will get around all squares and will return to the first and at the same time the maximum time in which he visited any square will be minimal.Formally, Denis's route can be represented as a sequence of pairs: $$$\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$$$, where $$$v_i$$$ is number of square, and $$$t_i$$$ is time in which the boy is now.The following conditions must be met: The route starts on square $$$1$$$ at time $$$0$$$, i.e. $$$v_1 = 1, t_1 = 0$$$ and ends on the square $$$1$$$, i.e. $$$v_k = 1$$$. All transitions are divided into two types: Being in the square change the time: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} &lt; t_i$$$. Walk along one of the roads: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$$$. Herewith, $$$v_i$$$ and $$$v_{i+1}$$$ are connected by road, and $$$t_{i+1} = t_i + 1$$$ All pairs $$$\{ v_i, t_i \}$$$ must be different. All squares are among $$$v_1, v_2, \ldots, v_k$$$. You need to find a route such that the maximum time in any square will be minimal, that is, the route for which $$$\max{(t_1, t_2, \ldots, t_k)}$$$ will be the minimum possible.
In the first line output the integer $$$k$$$ $$$(1 \leq k \leq 10^6)$$$  — the length of the path of Denis. In the next $$$k$$$ lines output pairs $$$v_i, t_i$$$  — pairs that describe Denis's route (as in the statement). All route requirements described in the statements must be met. It is guaranteed that under given restrictions there is at least one route and an answer whose length does not exceed $$$10^6$$$. If there are several possible answers, print any.
The first line contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the number of squares in the city. The next $$$n - 1$$$ lines contain two integers $$$u$$$ and $$$v$$$ $$$(1 \leq v, u \leq n, u \neq v)$$$ - the numbers of the squares connected by the road. It is guaranteed that the given graph is a tree.
standard output
standard input
PyPy 2
Python
2,600
train_062.jsonl
32a874cccbea623dcb665a32d92888f1
256 megabytes
["5\n1 2\n2 3\n2 4\n4 5"]
PASSED
import sys range = xrange input = raw_input from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) bfs = [0] for node in bfs: for nei in coupl[node]: del coupl[nei][coupl[nei].index(node)] bfs.append(nei) tree = [] time = [] @bootstrap def dfs(i, t = 0): tree.append(i) time.append(t) t0 = t deg = len(coupl[i]) lower = max(min(t - 1, deg), 0) upper = deg - lower ind = 0 while ind < len(coupl[i]) and upper: yield dfs(coupl[i][ind], t + 1) t += 1 tree.append(i) time.append(t) upper -= 1 ind += 1 t = t0 - lower - 1 tree.append(i) time.append(t) while lower: yield dfs(coupl[i][ind], t + 1) t += 1 tree.append(i) time.append(t) lower -= 1 ind += 1 yield dfs(0,0) print len(tree) - 1 print '\n'.join('%d %d' % (tree[i] + 1, time[i]) for i in range(len(tree) - 1))
1587653100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["First\nSecond\nSecond\nFirst\nFirst\nSecond\nFirst"]
0c9030689394ad4e126e5b8681f1535c
NoteIn the first test case, the first player will win the game. His winning strategy is: The first player should take the stones from the first pile. He will take $$$1$$$ stone. The numbers of stones in piles will be $$$[1, 5, 4]$$$. The second player should take the stones from the first pile. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 5, 4]$$$. The first player should take the stones from the second pile because the first pile is empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 1, 4]$$$. The second player should take the stones from the second pile because the first pile is empty. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 0, 4]$$$. The first player should take the stones from the third pile because the first and second piles are empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 0, 0]$$$. The second player will lose the game because all piles will be empty.
There are $$$n$$$ piles of stones, where the $$$i$$$-th pile has $$$a_i$$$ stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.
For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$)  — $$$a_i$$$ is equal to the number of stones in the $$$i$$$-th pile. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,100
train_003.jsonl
11990ae9d14d72d0413a6a13ca438076
256 megabytes
["7\n3\n2 5 4\n8\n1 1 1 1 1 1 1 1\n6\n1 2 3 4 5 6\n6\n1 1 2 1 2 2\n1\n1000000000\n5\n1 2 2 1 1\n3\n1 1 1"]
PASSED
for _ in range(int(input())): n = input() arr = input().split() # idx = 0 for v in arr: if v != '1': break idx += 1 # if idx != len(arr): print('First' if (idx+1)%2==1 else 'Second') else: print('First' if len(arr)%2==1 else 'Second')
1595342100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1.0000000", "2.0000000", "1.3284271", "My poor head =("]
c4b0f9263e18aac26124829cf3d880b6
NoteIn the first example the answer is restricted by the coffin's length (remember — coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember — arbitrary moves and rotations of the coffin are possible).
A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (l ≥ w) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him...
Print the maximally possible width of a coffin with absolute or relative error no more than 10 - 7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes). It is guaranteed that if the answer is positive, it will be not less than 10 - 7. All the hacks will also be checked to meet that condition.
The first line contains three space-separated integers a, b and l from the problem's statement (1 ≤ a, b, l ≤ 104).
standard output
standard input
Python 2
Python
2,500
train_080.jsonl
8f4f2271765b2d947686b1a8b2bbf9fb
256 megabytes
["2 2 1", "2 2 2", "2 2 3", "2 2 6"]
PASSED
EPS = 1e-8 def cross(a, b): return (a[0] * b[1]) - (a[1] * b[0]) def f(a, b, l, x): y = (l*l - x*x)**0.5 return cross( (a-x, b), (-x, y) ) def main(): a, b, l = map(int, raw_input().split()) if a > b: a, b = b, a if l <= a and a <= b: print "%.9lf" % l elif a < l and l <= b: print "%.9lf" % a else: lo = 0.0 hi = float(l) while (hi - lo) > EPS: x1 = lo + (hi-lo)/3.0 x2 = lo + (hi-lo)*2.0/3.0 if f(a, b, l, x1) > f(a, b, l, x2): lo = x1 else: hi = x2 ans = f(a, b, l, lo) / l if ans < EPS: print "My poor head =(" else: print "%.9lf" % ans if __name__ == "__main__": main()
1311346800
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
4 seconds
["YES\nNO\nYES\nYES\nYES"]
bcd34e88bcd70ad36acbe6c3b70aa45d
NoteThe first example is explained in the statement.In the second example, it is impossible to get the value $$$31$$$ from the numbers of the multiset $$$b$$$ by available operations.In the third example, we can proceed as follows: Replace $$$2$$$ with $$$2 \cdot 2 = 4$$$. We get $$$b = \{4, 14, 14, 26, 42\}$$$. Replace $$$14$$$ with $$$\lfloor \frac{14}{2} \rfloor = 7$$$. We get $$$b = \{4, 7, 14, 26, 42\}$$$. Replace $$$26$$$ with $$$\lfloor \frac{26}{2} \rfloor = 13$$$. We get $$$b = \{4, 7, 14, 13, 42\}$$$. Replace $$$42$$$ with $$$\lfloor \frac{42}{2} \rfloor = 21$$$. We get $$$b = \{4, 7, 14, 13, 21\}$$$. Replace $$$21$$$ with $$$\lfloor \frac{21}{2} \rfloor = 10$$$. We get $$$b = \{4, 7, 14, 13, 10\}$$$. Got equal multisets $$$a = \{4, 7, 10, 13, 14\}$$$ and $$$b = \{4, 7, 14, 13, 10\}$$$.
Multiset —is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. Two multisets are equal when each value occurs the same number of times. For example, the multisets $$$\{2,2,4\}$$$ and $$$\{2,4,2\}$$$ are equal, but the multisets $$$\{1,2,2\}$$$ and $$$\{1,1,2\}$$$ — are not.You are given two multisets $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ integers.In a single operation, any element of the $$$b$$$ multiset can be doubled or halved (rounded down). In other words, you have one of the following operations available for an element $$$x$$$ of the $$$b$$$ multiset: replace $$$x$$$ with $$$x \cdot 2$$$, or replace $$$x$$$ with $$$\lfloor \frac{x}{2} \rfloor$$$ (round down). Note that you cannot change the elements of the $$$a$$$ multiset.See if you can make the multiset $$$b$$$ become equal to the multiset $$$a$$$ in an arbitrary number of operations (maybe $$$0$$$).For example, if $$$n = 4$$$, $$$a = \{4, 24, 5, 2\}$$$, $$$b = \{4, 1, 6, 11\}$$$, then the answer is yes. We can proceed as follows: Replace $$$1$$$ with $$$1 \cdot 2 = 2$$$. We get $$$b = \{4, 2, 6, 11\}$$$. Replace $$$11$$$ with $$$\lfloor \frac{11}{2} \rfloor = 5$$$. We get $$$b = \{4, 2, 6, 5\}$$$. Replace $$$6$$$ with $$$6 \cdot 2 = 12$$$. We get $$$b = \{4, 2, 12, 5\}$$$. Replace $$$12$$$ with $$$12 \cdot 2 = 24$$$. We get $$$b = \{4, 2, 24, 5\}$$$. Got equal multisets $$$a = \{4, 24, 5, 2\}$$$ and $$$b = \{4, 2, 24, 5\}$$$.
For each test case, print on a separate line: YES if you can make the multiset $$$b$$$ become equal to $$$a$$$, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as positive answer).
The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. Each test case consists of three lines. The first line of the test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) —the number of elements in the multisets $$$a$$$ and $$$b$$$. The second line gives $$$n$$$ integers: $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le 10^9$$$) —the elements of the multiset $$$a$$$. Note that the elements may be equal. The third line contains $$$n$$$ integers: $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_1 \le b_2 \le \dots \le b_n \le 10^9$$$) — elements of the multiset $$$b$$$. Note that the elements may be equal. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_089.jsonl
6d5ac23ebf07c7e117684c2af2ff100d
256 megabytes
["5\n\n4\n\n2 4 5 24\n\n1 4 6 11\n\n3\n\n1 4 17\n\n4 5 31\n\n5\n\n4 7 10 13 14\n\n2 14 14 26 42\n\n5\n\n2 2 4 4 4\n\n28 46 62 71 98\n\n6\n\n1 2 10 16 64 80\n\n20 43 60 74 85 99"]
PASSED
#!/usr/bin/env python3 import io, os, sys from sys import stdin, stdout # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def input(): return stdin.readline().strip() def read_int_list(): return list(map(int, input().split())) def read_int_tuple(): return tuple(map(int, input().split())) def read_int(): return int(input()) from itertools import permutations, chain, combinations, product from math import factorial, gcd from collections import Counter, defaultdict, deque from heapq import heappush, heappop, heapify from bisect import bisect_left from functools import lru_cache import random ### CODE HERE import sys import array class BinaryTrie_pool: def __repr__(self) -> str: return f"{self.num_words, self.starts, self.child0, self.child1}" def alloc(self): self.num_words.append(0) self.starts.append(0) self.child0.append(-1) self.child1.append(-1) self.next_alloc += 1 return self.next_alloc - 1 def __init__(self): self.num_words = array.array('L') self.starts = array.array('L') self.child0 = array.array('l') self.child1 = array.array('l') self.next_alloc = 0 self.root = self.alloc() def anyChild(self, node): if self.child0[node] != -1 and self.starts[self.child0[node]] > 0: return self.child0[node] if self.child1[node] != -1 and self.starts[self.child1[node]] > 0: return self.child1[node] def insert(self, word): word = list(map(int, word)) node=self.root for i in word: self.starts[node] += 1 if i == 0 and self.child0[node] == -1: self.child0[node] = self.alloc() if i == 1 and self.child1[node] == -1: self.child1[node] = self.alloc() node = self.child0[node] if i == 0 else self.child1[node] self.num_words[node] += 1 self.starts[node] += 1 def findAnyWithPrefix(self, prefix): prefix = list(map(int, prefix)) node = self.findNode(prefix) if node == -1 or node is None: return None if self.starts[node] == 0: return None while self.num_words[node] == 0: node = self.anyChild(node) return node def containsWord(self, word): word = list(map(int, word)) node = self.findNode(word) if node == -1: return False return node.num_words > 0 def remove(self, word): word = list(map(int, word)) node=self.root self.starts[node] -= 1 for i in word: if i == 0 and self.child0[node] == -1: return None if i == 1 and self.child1[node] == -1: return None node = self.child0[node] if i == 0 else self.child1[node] self.starts[node] -= 1 self.num_words[node] -= 1 def removeAnyWithPrefix(self, prefix): prefix = list(map(int, prefix)) node=self.root for i in prefix: self.starts[node] -= 1 node = self.child0[node] if i == 0 else self.child1[node] if self.num_words[node] > 0: self.starts[node] -= 1 self.num_words[node] -= 1 return self.starts[node] -= 1 while self.num_words[node] == 0: node = self.anyChild(node) self.starts[node] -= 1 self.num_words[node] -= 1 def findNode(self, word): word = list(map(int, word)) node=self.root for i in word: if i == 0 and self.child0[node] == -1: return None if i == 1 and self.child1[node] == -1: return None node = self.child0[node] if i == 0 else self.child1[node] return node def startsWith(self, prefix): prefix = list(map(int, prefix)) node = self.findNode(prefix) if node == -1: return False return self.starts[node] > 0 def clean(arr): ret = [] for a in arr: x = a while x > 0 and x % 2 == 0: x //= 2 ret += [x] return sorted(ret)[::-1] def bin(x): return "{0:b}".format(x) def ans(A, B): A = clean(A) B = clean(B) A = [bin(x) for x in A] B = [bin(x) for x in B] t = BinaryTrie_pool() for b in B: t.insert(b) for a in A: w = t.findAnyWithPrefix(a) if w is None: return "NO" t.removeAnyWithPrefix(a) return "YES" if False: t = BinaryTrie_pool() t.insert("10") t.insert("100") print(t) print(t.anyChild(0)) else: for _ in range(read_int()): input() A = read_int_list() B = read_int_list() print(ans(A, B))
1657463700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["2\n3\n3\n319908071"]
4e9dfc5e988cebb9a92f0c0b7ec06981
NoteFor the first test case, the two valid assignments are$$$0000\\ 0000\\ 0000$$$and$$$0000\\ 0010\\ 0000$$$
Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an $$$n$$$ by $$$m$$$ grid ($$$1 \leq n, m \leq 2000$$$) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most $$$1$$$. If the number in some cell is strictly larger than $$$0$$$, it should be strictly greater than the number in at least one of the cells adjacent to it. Unfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a "0" or a "#". If a cell is labeled as "0", then the number in it must equal $$$0$$$. Otherwise, the number in it can be any nonnegative integer.Determine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo $$$10^9+7$$$.
For each test case, print one integer: the number of valid configurations modulo $$$10^9+7$$$.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 2000, nm \geq 2$$$) – the dimensions of the forest. $$$n$$$ lines follow, each consisting of one string of $$$m$$$ characters. Each of these characters is either a "0" or a "#". It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$2000$$$.
standard output
standard input
PyPy 3-64
Python
2,300
train_094.jsonl
bd602f37f0c4294d99c66cbd4a7f40b9
256 megabytes
["4\n3 4\n0000\n00#0\n0000\n2 1\n#\n#\n1 2\n##\n6 29\n#############################\n#000##0###0##0#0####0####000#\n#0#0##00#00##00####0#0###0#0#\n#0#0##0#0#0##00###00000##00##\n#000##0###0##0#0##0###0##0#0#\n#############################"]
PASSED
import sys input = sys.stdin.readline inf = float('inf') def getInt(): return int(input()) def getStr(): return input().strip() def getList(split=True): s = getStr() if split: s = s.split() return map(int, s) t = getInt() # t = 1 M = 10 ** 9 + 7 def solve(): n, m = getList() # we can figure out the solution by fixed the 0's in some certain cells , then for each subset of 0, caculate how many assignments such that the chosen cell is 0 and the other must be non-negative # It turns out for a particular subset there is EXACTLy one solution for it # proof # multi bfs, because all other cells must be nonegtive, any adjacents to 0 must be 1, this is equivalent for the first turn of multi bfs # can we assign any other cell to 1 ? no, because if that cell is assign 1 then there's must be a cell neighbor to it is 0, but if there is a 0 neighbor to it, then it should be makred before # from distance 2, 3 4, 5 .. we could prove the same way # i.e while bfs for distance 2 done , if we assign any other unvisted cell 0 1 then there is no possible solution since ther emust be either cell 0 or 1 next to it, but if there were it should be mared before a = "".join(getStr() for _ in range(n)) res = a.count("#") res = pow(2, res, M) res -= '0' not in a print(res % M) for _ in range(t): solve()
1622990100
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nNO"]
3d6cd0a82513bc2119c9af3d1243846f
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
standard output
standard input
PyPy 3
Python
800
train_003.jsonl
bc7743fd468905a1fe2b88aa56c6e06d
256 megabytes
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
PASSED
for i in range(int(input())): a = int(input()) d = {} for i in range(a): for x in input(): if x in d: d[x] += 1 else: d[x] = 1 key = True for i in d: if d[i] % a != 0: key = False if key: print("YES") else: print("NO")
1598798100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["YES\nNO\nYES"]
5172d358f1d451b42efff1019219a54d
NoteIn the first test case, you can take, for example, $$$a = 5$$$ as the size of the pack. Then if a customer wants to buy $$$3$$$ cans, he'll buy $$$5$$$ instead ($$$3 \bmod 5 = 3$$$, $$$\frac{5}{2} = 2.5$$$). The one who wants $$$4$$$ cans will also buy $$$5$$$ cans.In the second test case, there is no way to choose $$$a$$$.In the third test case, you can take, for example, $$$a = 80$$$.
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with $$$a$$$ cans in a pack with a discount and some customer wants to buy $$$x$$$ cans of cat food. Then he follows a greedy strategy: he buys $$$\left\lfloor \frac{x}{a} \right\rfloor$$$ packs with a discount; then he wants to buy the remaining $$$(x \bmod a)$$$ cans one by one. $$$\left\lfloor \frac{x}{a} \right\rfloor$$$ is $$$x$$$ divided by $$$a$$$ rounded down, $$$x \bmod a$$$ is the remainer of $$$x$$$ divided by $$$a$$$.But customers are greedy in general, so if the customer wants to buy $$$(x \bmod a)$$$ cans one by one and it happens that $$$(x \bmod a) \ge \frac{a}{2}$$$ he decides to buy the whole pack of $$$a$$$ cans (instead of buying $$$(x \bmod a)$$$ cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.You know that each of the customers that come to your shop can buy any number of cans from $$$l$$$ to $$$r$$$ inclusive. Can you choose such size of pack $$$a$$$ that each customer buys more cans than they wanted initially?
For each test case, print YES if you can choose such size of pack $$$a$$$ that each customer buys more cans than they wanted initially. Otherwise, print NO. You can print each character in any case.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the range of the number of cans customers can buy.
standard output
standard input
Python 3
Python
800
train_002.jsonl
b3f64d711652286b538a3276b2613397
256 megabytes
["3\n3 4\n1 2\n120 150"]
PASSED
t = int(input()) while(t>0): l,r = map(int,input().split()) if (r-l) < l: print("YES") else: print("NO") t = t-1
1603809300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Yes", "No", "No", "Yes"]
c54042eebaef01783a74d31521db9baa
NoteIn the first example, there are five points: (1, 7), (2, 5), (3, 8), (4, 6) and (5, 9). It's possible to draw a line that passes through points 1, 3, 5, and another one that passes through points 2, 4 and is parallel to the first one.In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.In the third example, it's impossible to satisfy both requirements at the same time.
Connect the countless points with lines, till we reach the faraway yonder.There are n points on a coordinate plane, the i-th of which being (i, yi).Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.
Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise. You can print each letter in any case (upper or lower).
The first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points. The second line contains n space-separated integers y1, y2, ..., yn ( - 109 ≤ yi ≤ 109) — the vertical coordinates of each point.
standard output
standard input
PyPy 3
Python
1,600
train_009.jsonl
5f5d6eabb2e1d6c2ebf1e8f7611a2e2d
256 megabytes
["5\n7 5 8 6 9", "5\n-1 -2 0 0 -5", "5\n5 4 3 2 1", "5\n1000000000 0 0 0 0"]
PASSED
n=int(input()) d=list(map(int,input().split())) a,b,c=d[:3] if b-a==c-b: e=b-a f=0 for i in range(3,n): if (d[i]-c)/(i-2)!=e: if f and(d[i]-g)/(i-h)!=e:print('No');exit() else:g,h=d[i],i;f=1 print('Yes'if f else'No') else: p1=p2=p3=1 e,f,g=b-a,c,2 h,j,k=c-b,a,0 l,m,o=(c-a)/2,b,1 for i in range(3,n): if(d[i]-b)/(i-1)!=e and(d[i]-f)/(i-g)!=e:p1=0 if(d[i]-c)/(i-2)!=h and(d[i]-j)/(i-k)!=h:p2=0 if(d[i]-c)/(i-2)!=l and(d[i]-m)/(i-o)!=l:p3=0 print('Yes'if p1+p2+p3 else'No')
1504272900
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1", "4"]
566adc43d2d6df257c26c5f5495a5745
NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.
In the only line output the amount of numbers written on the same page as the last number.
The only input line contains three space-separated integers b, n and c (2 ≤ b &lt; 10106, 1 ≤ n &lt; 10106, 1 ≤ c ≤ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.
standard output
standard input
Python 2
Python
2,400
train_037.jsonl
8942c37a5798feaf0256fc060bad7e39
64 megabytes
["2 3 3", "2 3 4"]
PASSED
#!/usr/bin/python primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, 17881, 17891, 17903, 17909, 17911, 17921, 17923, 17929, 17939, 17957, 17959, 17971, 17977, 17981, 17987, 17989, 18013, 18041, 18043, 18047, 18049, 18059, 18061, 18077, 18089, 18097, 18119, 18121, 18127, 18131, 18133, 18143, 18149, 18169, 18181, 18191, 18199, 18211, 18217, 18223, 18229, 18233, 18251, 18253, 18257, 18269, 18287, 18289, 18301, 18307, 18311, 18313, 18329, 18341, 18353, 18367, 18371, 18379, 18397, 18401, 18413, 18427, 18433, 18439, 18443, 18451, 18457, 18461, 18481, 18493, 18503, 18517, 18521, 18523, 18539, 18541, 18553, 18583, 18587, 18593, 18617, 18637, 18661, 18671, 18679, 18691, 18701, 18713, 18719, 18731, 18743, 18749, 18757, 18773, 18787, 18793, 18797, 18803, 18839, 18859, 18869, 18899, 18911, 18913, 18917, 18919, 18947, 18959, 18973, 18979, 19001, 19009, 19013, 19031, 19037, 19051, 19069, 19073, 19079, 19081, 19087, 19121, 19139, 19141, 19157, 19163, 19181, 19183, 19207, 19211, 19213, 19219, 19231, 19237, 19249, 19259, 19267, 19273, 19289, 19301, 19309, 19319, 19333, 19373, 19379, 19381, 19387, 19391, 19403, 19417, 19421, 19423, 19427, 19429, 19433, 19441, 19447, 19457, 19463, 19469, 19471, 19477, 19483, 19489, 19501, 19507, 19531, 19541, 19543, 19553, 19559, 19571, 19577, 19583, 19597, 19603, 19609, 19661, 19681, 19687, 19697, 19699, 19709, 19717, 19727, 19739, 19751, 19753, 19759, 19763, 19777, 19793, 19801, 19813, 19819, 19841, 19843, 19853, 19861, 19867, 19889, 19891, 19913, 19919, 19927, 19937, 19949, 19961, 19963, 19973, 19979, 19991, 19993, 19997, 20011, 20021, 20023, 20029, 20047, 20051, 20063, 20071, 20089, 20101, 20107, 20113, 20117, 20123, 20129, 20143, 20147, 20149, 20161, 20173, 20177, 20183, 20201, 20219, 20231, 20233, 20249, 20261, 20269, 20287, 20297, 20323, 20327, 20333, 20341, 20347, 20353, 20357, 20359, 20369, 20389, 20393, 20399, 20407, 20411, 20431, 20441, 20443, 20477, 20479, 20483, 20507, 20509, 20521, 20533, 20543, 20549, 20551, 20563, 20593, 20599, 20611, 20627, 20639, 20641, 20663, 20681, 20693, 20707, 20717, 20719, 20731, 20743, 20747, 20749, 20753, 20759, 20771, 20773, 20789, 20807, 20809, 20849, 20857, 20873, 20879, 20887, 20897, 20899, 20903, 20921, 20929, 20939, 20947, 20959, 20963, 20981, 20983, 21001, 21011, 21013, 21017, 21019, 21023, 21031, 21059, 21061, 21067, 21089, 21101, 21107, 21121, 21139, 21143, 21149, 21157, 21163, 21169, 21179, 21187, 21191, 21193, 21211, 21221, 21227, 21247, 21269, 21277, 21283, 21313, 21317, 21319, 21323, 21341, 21347, 21377, 21379, 21383, 21391, 21397, 21401, 21407, 21419, 21433, 21467, 21481, 21487, 21491, 21493, 21499, 21503, 21517, 21521, 21523, 21529, 21557, 21559, 21563, 21569, 21577, 21587, 21589, 21599, 21601, 21611, 21613, 21617, 21647, 21649, 21661, 21673, 21683, 21701, 21713, 21727, 21737, 21739, 21751, 21757, 21767, 21773, 21787, 21799, 21803, 21817, 21821, 21839, 21841, 21851, 21859, 21863, 21871, 21881, 21893, 21911, 21929, 21937, 21943, 21961, 21977, 21991, 21997, 22003, 22013, 22027, 22031, 22037, 22039, 22051, 22063, 22067, 22073, 22079, 22091, 22093, 22109, 22111, 22123, 22129, 22133, 22147, 22153, 22157, 22159, 22171, 22189, 22193, 22229, 22247, 22259, 22271, 22273, 22277, 22279, 22283, 22291, 22303, 22307, 22343, 22349, 22367, 22369, 22381, 22391, 22397, 22409, 22433, 22441, 22447, 22453, 22469, 22481, 22483, 22501, 22511, 22531, 22541, 22543, 22549, 22567, 22571, 22573, 22613, 22619, 22621, 22637, 22639, 22643, 22651, 22669, 22679, 22691, 22697, 22699, 22709, 22717, 22721, 22727, 22739, 22741, 22751, 22769, 22777, 22783, 22787, 22807, 22811, 22817, 22853, 22859, 22861, 22871, 22877, 22901, 22907, 22921, 22937, 22943, 22961, 22963, 22973, 22993, 23003, 23011, 23017, 23021, 23027, 23029, 23039, 23041, 23053, 23057, 23059, 23063, 23071, 23081, 23087, 23099, 23117, 23131, 23143, 23159, 23167, 23173, 23189, 23197, 23201, 23203, 23209, 23227, 23251, 23269, 23279, 23291, 23293, 23297, 23311, 23321, 23327, 23333, 23339, 23357, 23369, 23371, 23399, 23417, 23431, 23447, 23459, 23473, 23497, 23509, 23531, 23537, 23539, 23549, 23557, 23561, 23563, 23567, 23581, 23593, 23599, 23603, 23609, 23623, 23627, 23629, 23633, 23663, 23669, 23671, 23677, 23687, 23689, 23719, 23741, 23743, 23747, 23753, 23761, 23767, 23773, 23789, 23801, 23813, 23819, 23827, 23831, 23833, 23857, 23869, 23873, 23879, 23887, 23893, 23899, 23909, 23911, 23917, 23929, 23957, 23971, 23977, 23981, 23993, 24001, 24007, 24019, 24023, 24029, 24043, 24049, 24061, 24071, 24077, 24083, 24091, 24097, 24103, 24107, 24109, 24113, 24121, 24133, 24137, 24151, 24169, 24179, 24181, 24197, 24203, 24223, 24229, 24239, 24247, 24251, 24281, 24317, 24329, 24337, 24359, 24371, 24373, 24379, 24391, 24407, 24413, 24419, 24421, 24439, 24443, 24469, 24473, 24481, 24499, 24509, 24517, 24527, 24533, 24547, 24551, 24571, 24593, 24611, 24623, 24631, 24659, 24671, 24677, 24683, 24691, 24697, 24709, 24733, 24749, 24763, 24767, 24781, 24793, 24799, 24809, 24821, 24841, 24847, 24851, 24859, 24877, 24889, 24907, 24917, 24919, 24923, 24943, 24953, 24967, 24971, 24977, 24979, 24989, 25013, 25031, 25033, 25037, 25057, 25073, 25087, 25097, 25111, 25117, 25121, 25127, 25147, 25153, 25163, 25169, 25171, 25183, 25189, 25219, 25229, 25237, 25243, 25247, 25253, 25261, 25301, 25303, 25307, 25309, 25321, 25339, 25343, 25349, 25357, 25367, 25373, 25391, 25409, 25411, 25423, 25439, 25447, 25453, 25457, 25463, 25469, 25471, 25523, 25537, 25541, 25561, 25577, 25579, 25583, 25589, 25601, 25603, 25609, 25621, 25633, 25639, 25643, 25657, 25667, 25673, 25679, 25693, 25703, 25717, 25733, 25741, 25747, 25759, 25763, 25771, 25793, 25799, 25801, 25819, 25841, 25847, 25849, 25867, 25873, 25889, 25903, 25913, 25919, 25931, 25933, 25939, 25943, 25951, 25969, 25981, 25997, 25999, 26003, 26017, 26021, 26029, 26041, 26053, 26083, 26099, 26107, 26111, 26113, 26119, 26141, 26153, 26161, 26171, 26177, 26183, 26189, 26203, 26209, 26227, 26237, 26249, 26251, 26261, 26263, 26267, 26293, 26297, 26309, 26317, 26321, 26339, 26347, 26357, 26371, 26387, 26393, 26399, 26407, 26417, 26423, 26431, 26437, 26449, 26459, 26479, 26489, 26497, 26501, 26513, 26539, 26557, 26561, 26573, 26591, 26597, 26627, 26633, 26641, 26647, 26669, 26681, 26683, 26687, 26693, 26699, 26701, 26711, 26713, 26717, 26723, 26729, 26731, 26737, 26759, 26777, 26783, 26801, 26813, 26821, 26833, 26839, 26849, 26861, 26863, 26879, 26881, 26891, 26893, 26903, 26921, 26927, 26947, 26951, 26953, 26959, 26981, 26987, 26993, 27011, 27017, 27031, 27043, 27059, 27061, 27067, 27073, 27077, 27091, 27103, 27107, 27109, 27127, 27143, 27179, 27191, 27197, 27211, 27239, 27241, 27253, 27259, 27271, 27277, 27281, 27283, 27299, 27329, 27337, 27361, 27367, 27397, 27407, 27409, 27427, 27431, 27437, 27449, 27457, 27479, 27481, 27487, 27509, 27527, 27529, 27539, 27541, 27551, 27581, 27583, 27611, 27617, 27631, 27647, 27653, 27673, 27689, 27691, 27697, 27701, 27733, 27737, 27739, 27743, 27749, 27751, 27763, 27767, 27773, 27779, 27791, 27793, 27799, 27803, 27809, 27817, 27823, 27827, 27847, 27851, 27883, 27893, 27901, 27917, 27919, 27941, 27943, 27947, 27953, 27961, 27967, 27983, 27997, 28001, 28019, 28027, 28031, 28051, 28057, 28069, 28081, 28087, 28097, 28099, 28109, 28111, 28123, 28151, 28163, 28181, 28183, 28201, 28211, 28219, 28229, 28277, 28279, 28283, 28289, 28297, 28307, 28309, 28319, 28349, 28351, 28387, 28393, 28403, 28409, 28411, 28429, 28433, 28439, 28447, 28463, 28477, 28493, 28499, 28513, 28517, 28537, 28541, 28547, 28549, 28559, 28571, 28573, 28579, 28591, 28597, 28603, 28607, 28619, 28621, 28627, 28631, 28643, 28649, 28657, 28661, 28663, 28669, 28687, 28697, 28703, 28711, 28723, 28729, 28751, 28753, 28759, 28771, 28789, 28793, 28807, 28813, 28817, 28837, 28843, 28859, 28867, 28871, 28879, 28901, 28909, 28921, 28927, 28933, 28949, 28961, 28979, 29009, 29017, 29021, 29023, 29027, 29033, 29059, 29063, 29077, 29101, 29123, 29129, 29131, 29137, 29147, 29153, 29167, 29173, 29179, 29191, 29201, 29207, 29209, 29221, 29231, 29243, 29251, 29269, 29287, 29297, 29303, 29311, 29327, 29333, 29339, 29347, 29363, 29383, 29387, 29389, 29399, 29401, 29411, 29423, 29429, 29437, 29443, 29453, 29473, 29483, 29501, 29527, 29531, 29537, 29567, 29569, 29573, 29581, 29587, 29599, 29611, 29629, 29633, 29641, 29663, 29669, 29671, 29683, 29717, 29723, 29741, 29753, 29759, 29761, 29789, 29803, 29819, 29833, 29837, 29851, 29863, 29867, 29873, 29879, 29881, 29917, 29921, 29927, 29947, 29959, 29983, 29989, 30011, 30013, 30029, 30047, 30059, 30071, 30089, 30091, 30097, 30103, 30109, 30113, 30119, 30133, 30137, 30139, 30161, 30169, 30181, 30187, 30197, 30203, 30211, 30223, 30241, 30253, 30259, 30269, 30271, 30293, 30307, 30313, 30319, 30323, 30341, 30347, 30367, 30389, 30391, 30403, 30427, 30431, 30449, 30467, 30469, 30491, 30493, 30497, 30509, 30517, 30529, 30539, 30553, 30557, 30559, 30577, 30593, 30631, 30637, 30643, 30649, 30661, 30671, 30677, 30689, 30697, 30703, 30707, 30713, 30727, 30757, 30763, 30773, 30781, 30803, 30809, 30817, 30829, 30839, 30841, 30851, 30853, 30859, 30869, 30871, 30881, 30893, 30911, 30931, 30937, 30941, 30949, 30971, 30977, 30983, 31013, 31019, 31033, 31039, 31051, 31063, 31069, 31079, 31081, 31091, 31121, 31123, 31139, 31147, 31151, 31153, 31159, 31177, 31181, 31183, 31189, 31193, 31219, 31223, 31231, 31237, 31247, 31249, 31253, 31259, 31267, 31271, 31277, 31307, 31319, 31321, 31327, 31333, 31337, 31357, 31379, 31387, 31391, 31393, 31397, 31469, 31477, 31481, 31489, 31511, 31513, 31517, 31531, 31541, 31543, 31547, 31567, 31573, 31583, 31601, 31607, 31627, 31643, 31649, 31657, 31663, 31667, 31687, 31699, 31721, ] # can calculate for n up to 10^9 def phi(n): n0 = n result = n for p in primes: if n == 1: break if n % p != 0: continue while n % p == 0: n /= p result = result * (p-1) / p if n0 == n: return n-1 else: return result def modExp(a, b, n): c = 0 d = 1 bRep = [] bp = b while bp > 0: bRep.append(bp & 1) bp = bp >> 1 for bi in reversed(bRep): c *= 2 d = (d * d) % n if bi == 1: c += 1 d = (d * a) % n return d def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def ext_gcd(a, b): if b == 0: return (a, 1, 0) (dp, xp, yp) = ext_gcd(b, a % b) return (dp, yp, xp - a//b * yp) def mod_solve(a, b, n): (d, xp, yp) = ext_gcd(a, n) if b % d == 0: x0 = xp * (b/d) % n return x0 else: return None def chinese_remainder(a, n): N = reduce(lambda x, y: x * y, n, 1) m = map(lambda x: N/x, n) c = map(lambda (x, y): x * mod_solve(x, 1, y), zip(m, n)) result = 0 for i in xrange(len(a)): result += c[i] * a[i] return result % N ###################### def get_prime_exp(b, p): exp = 0 while b % p == 0: b = b / p exp += 1 return exp def mod_exp0(b, n, c): r = 1 for i in xrange(n): r = r * b % c return r def mod_large(n, c): nLen = len(n) LEN = 9 factor = 10 ** LEN nslots = nLen // LEN if nLen % LEN == 0 else nLen // LEN + 1 cRemainder = [None for i in xrange(nslots)] cRemainder[0] = 1 for i in xrange(1, nslots): cRemainder[i] = cRemainder[i-1] * factor % c result = 0 for i in xrange(nslots-1): if i > 0: result += cRemainder[i] * int(n[(i+1)*LEN-1:i*LEN-1:-1]) else: result += cRemainder[i] * int(n[(i+1)*LEN-1::-1]) result %= c if nslots > 1: result += cRemainder[nslots-1] * int(n[nLen:(nslots-1)*LEN-1:-1]) else: result += cRemainder[nslots-1] * int(n[nLen::-1]) result %= c return result # find (b ** n) mod (p ** m), where p is a prime def mod_exp_prime_power(b, n, p, m): c = p ** m if b % p == 0: k = get_prime_exp(b, p) if len(n) > 9 or k * int(n[::-1]) >= m: return 0 else: return modExp(b, int(n[::-1]), c) else: phic = c * (p-1) / p; n = mod_large(n, phic) return modExp(b, n, c) # calculates (b ** n) mod c using Chinese remainder theorem def mod_exp(b, n, c): if b == 0: return 0 if n != '0' else 1 pr = [] # primes ex = [] # exponentials cp = c for p in primes: if cp == 1: break if cp % p == 0: pr.append(p) exp = get_prime_exp(cp, p) cp = cp / (p ** exp) ex.append(exp) # cp is a prime itself if cp != 1: pr.append(cp) ex.append(1) ni = map(lambda (x, y): x ** y, zip(pr, ex)) ai = [] for i in xrange(len(pr)): ai.append(mod_exp_prime_power(b, n, pr[i], ex[i])) return chinese_remainder(ai, ni) def decrementAndReverse(n): n = list(n[::-1]) for i in xrange(len(n)): if n[i] != '0': n[i] = str(int(n[i])-1) break else: n[i] = '9' n = "".join(n).rstrip('0') if len(n) == 0: n = '0' return n def solve(): b, n, c = raw_input().split() b = b[::-1] n = decrementAndReverse(n) c = int(c) b = mod_large(b, c) r = (b + c - 1) * mod_exp(b, n, c) % c return r if r > 0 else c print solve()
1276182000
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
3 seconds
["1 3\n1 0\n3 0 1 2\n0"]
2c610873aa1a772a4c7f32cb74dd75fa
NoteConsider the example: in the first test case, the only possible value for the cyclic shift is $$$3$$$. If we shift $$$[1, 2, 3, 4]$$$ by $$$3$$$ positions, we get $$$[2, 3, 4, 1]$$$. Then we can swap the $$$3$$$-rd and the $$$4$$$-th elements to get the array $$$[2, 3, 1, 4]$$$; in the second test case, the only possible value for the cyclic shift is $$$0$$$. If we shift $$$[1, 2, 3]$$$ by $$$0$$$ positions, we get $$$[1, 2, 3]$$$. Then we don't change the array at all (we stated that we made at most $$$1$$$ swap), so the resulting array stays $$$[1, 2, 3]$$$; in the third test case, all values from $$$0$$$ to $$$2$$$ are possible for the cyclic shift: if we shift $$$[1, 2, 3]$$$ by $$$0$$$ positions, we get $$$[1, 2, 3]$$$. Then we can swap the $$$1$$$-st and the $$$3$$$-rd elements to get $$$[3, 2, 1]$$$; if we shift $$$[1, 2, 3]$$$ by $$$1$$$ position, we get $$$[3, 1, 2]$$$. Then we can swap the $$$2$$$-nd and the $$$3$$$-rd elements to get $$$[3, 2, 1]$$$; if we shift $$$[1, 2, 3]$$$ by $$$2$$$ positions, we get $$$[2, 3, 1]$$$. Then we can swap the $$$1$$$-st and the $$$2$$$-nd elements to get $$$[3, 2, 1]$$$; in the fourth test case, we stated that we didn't do any swaps after the cyclic shift, but no value of cyclic shift could produce the array $$$[1, 2, 3, 4, 6, 5]$$$.
An identity permutation of length $$$n$$$ is an array $$$[1, 2, 3, \dots, n]$$$.We performed the following operations to an identity permutation of length $$$n$$$: firstly, we cyclically shifted it to the right by $$$k$$$ positions, where $$$k$$$ is unknown to you (the only thing you know is that $$$0 \le k \le n - 1$$$). When an array is cyclically shifted to the right by $$$k$$$ positions, the resulting array is formed by taking $$$k$$$ last elements of the original array (without changing their relative order), and then appending $$$n - k$$$ first elements to the right of them (without changing relative order of the first $$$n - k$$$ elements as well). For example, if we cyclically shift the identity permutation of length $$$6$$$ by $$$2$$$ positions, we get the array $$$[5, 6, 1, 2, 3, 4]$$$; secondly, we performed the following operation at most $$$m$$$ times: pick any two elements of the array and swap them. You are given the values of $$$n$$$ and $$$m$$$, and the resulting array. Your task is to find all possible values of $$$k$$$ in the cyclic shift operation.
For each test case, print the answer in the following way: firstly, print one integer $$$r$$$ ($$$0 \le r \le n$$$) — the number of possible values of $$$k$$$ for the cyclic shift operation; secondly, print $$$r$$$ integers $$$k_1, k_2, \dots, k_r$$$ ($$$0 \le k_i \le n - 1$$$) — all possible values of $$$k$$$ in increasing order.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 3 \cdot 10^5$$$; $$$0 \le m \le \frac{n}{3}$$$). The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, each integer from $$$1$$$ to $$$n$$$ appears in this sequence exactly once) — the resulting array. The sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,100
train_105.jsonl
762dca833c006bee03c266b87ecb3620
256 megabytes
["4\n4 1\n2 3 1 4\n3 1\n1 2 3\n3 1\n3 2 1\n6 0\n1 2 3 4 6 5"]
PASSED
import sys input = sys.stdin.readline from collections import Counter for _ in range(int(input())): n, m = map(int, input().split()) A = list(map(int, input().split())) A = [a - 1 for a in A] B = [(i - a) % n for i, a in enumerate(A)] cnt = Counter(B) ans = [] X = list(range(1, n + 1)) for k in range(n): if n - cnt[k] > 2 * m: continue seen = [0] * n cycle = 0 cur = A[k:] + A[: k] for i in range(n): if seen[i]: continue while not seen[i]: seen[i] = 1 i = cur[i] cycle += 1 if n - cycle <= m: ans.append(k) print(len(ans), *ans)
1626964500
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]