prob_desc_time_limit
stringclasses
21 values
prob_desc_sample_outputs
stringlengths
5
329
src_uid
stringlengths
32
32
prob_desc_notes
stringlengths
31
2.84k
βŒ€
prob_desc_description
stringlengths
121
3.8k
prob_desc_output_spec
stringlengths
17
1.16k
βŒ€
prob_desc_input_spec
stringlengths
38
2.42k
βŒ€
prob_desc_output_to
stringclasses
3 values
prob_desc_input_from
stringclasses
3 values
lang
stringclasses
5 values
lang_cluster
stringclasses
1 value
difficulty
int64
-1
3.5k
βŒ€
file_name
stringclasses
111 values
code_uid
stringlengths
32
32
prob_desc_memory_limit
stringclasses
11 values
prob_desc_sample_inputs
stringlengths
5
802
exec_outcome
stringclasses
1 value
source_code
stringlengths
29
58.4k
prob_desc_created_at
stringlengths
10
10
tags
listlengths
1
5
hidden_unit_tests
stringclasses
1 value
labels
listlengths
8
8
1 second
["2\n2\n1\n2\n1"]
679a03b57d58907a221689483f59ca34
NoteIn the first test case the tree looks as follows: Firstly you can choose a bud vertex $$$4$$$ and re-hang it to vertex $$$3$$$. After that you can choose a bud vertex $$$2$$$ and re-hang it to vertex $$$7$$$. As a result, you will have the following tree with $$$2$$$ leaves: It can be proved that it is the minimal number of leaves possible to get.In the second test case the tree looks as follows: You can choose a bud vertex $$$3$$$ and re-hang it to vertex $$$5$$$. As a result, you will have the following tree with $$$2$$$ leaves: It can be proved that it is the minimal number of leaves possible to get.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $$$v$$$ (different from root) is the previous to $$$v$$$ vertex on the shortest path from the root to the vertex $$$v$$$. Children of the vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent.A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied: it is not a root, it has at least one child, and all its children are leaves. You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?
For each test case print a single integerΒ β€” the minimal number of leaves that is possible to get after some operations.
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 a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β β€” the number of the vertices in the given tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) meaning that there is an edge between vertices $$$u$$$ and $$$v$$$ in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,000
train_091.jsonl
6cfce800a7eb4cd259f7996cc66e23de
256 megabytes
["5\n7\n1 2\n1 3\n1 4\n2 5\n2 6\n4 7\n6\n1 2\n1 3\n2 4\n2 5\n3 6\n2\n1 2\n7\n7 3\n1 5\n1 3\n4 6\n4 7\n2 1\n6\n2 1\n2 3\n4 5\n3 4\n3 6"]
PASSED
from collections import deque import heapq from sys import * input = stdin.readline t = int(input()) for _ in range(t): n = int(input()) graph = [set() for _ in range(n+1)] for i in range(n-1): c, d = map(int, input().split()) graph[c].add(d) graph[d].add(c) dist = [-1] * (n+1) dist[0] = 0 dist[1] = 0 d = deque() d.append(1) parent = [0]*(n+1) while d: v = d.popleft() for i in graph[v]: if dist[i] != -1: continue dist[i] = dist[v] + 1 d.append(i) parent[i] = v QUE = [] for i in range(2,n+1): heapq.heappush(QUE, (-dist[i], i)) budcnt = 0 leafcnt = 0 used = [0]*(n+1) while QUE: DIST, CHILD = heapq.heappop(QUE) if used[CHILD] == 0: used[CHILD] = 1 PARENT = parent[CHILD] used[PARENT] = 1 if PARENT != 1: leafcnt += len(graph[PARENT]) - 1 budcnt += 1 for x in graph[PARENT]: if dist[PARENT] < dist[x]: used[x] = 1 graph[parent[PARENT]].remove(PARENT) if len(graph[1]) == 0: print(leafcnt-(budcnt-1)) else: print(len(graph[1])+leafcnt-budcnt)
1631457300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["1.000000000000000", "11.142135623730951"]
8996ae454ba3062e47a8aaab7fb1e33b
NoteThe figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0). The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal β€” their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β€” that's the strategy the flatlanders usually follow when they besiege cities.The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β‰₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β€” as a disk (including the border) with the center at the point where the radar is placed.
Print a single real number β€” the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≀ 104;Β 1 ≀ ri ≀ 104) β€” the city's coordinates and the distance from the city to the flatlanders, correspondingly. It is guaranteed that the cities are located at different points.
standard output
standard input
Python 3
Python
1,800
train_038.jsonl
baf1b4c501b576d98a7e83619312984b
256 megabytes
["0 0 1\n6 0 3", "-10 10 3\n10 -10 3"]
PASSED
x1,y1,r1=map(int,input().split()) x2,y2,r2=map(int,input().split()) d=((x1-x2)**2+(y1-y2)**2)**0.5 x=(d-r1-r2)/2 f=-x-min(r1,r2) if(x>=0): print(x) elif f>=0: print(f) else: print(0)
1337182200
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["2 2", "1 3"]
d3b9ffa76436b957ca959cf9204f9873
NoteIn the first sample the sorted sequence for the given array looks as: (1, 1), (1, 2), (2, 1), (2, 2). The 4-th of them is pair (2, 2).The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1, 3).
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≀ i, j ≀ n). In other words, let's consider all n2 pairs of numbers, picked from the given array.For example, in sequence a = {3, 1, 5} are 9 pairs of numbers: (3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5).Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (p1, q1) is lexicographically less than pair (p2, q2) only if either p1 &lt; p2, or p1 = p2 and q1 &lt; q2.Then the sequence, mentioned above, will be sorted like that: (1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)Let's number all the pair in the sorted list from 1 to n2. Your task is formulated like this: you should find the k-th pair in the ordered list of all possible pairs of the array you've been given.
In the single line print two numbers β€” the sought k-th pair.
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ n2). The second line contains the array containing n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109). The numbers in the array can coincide. All numbers are separated with spaces. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout, streams or the %I64d specificator instead.
standard output
standard input
Python 3
Python
1,700
train_010.jsonl
6df805207ae15aed30874055fb0fdf91
256 megabytes
["2 4\n2 1", "3 2\n3 1 5"]
PASSED
n, k = map(int, input().split()) a = sorted(map(int, input().split())) x = a[(k - 1) // n] p, c = a.index(x), a.count(x) y = ((k - 1) - p * n) // c print(x, a[y])
1331046000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4\n3\n6\n0"]
5df6eb50ead22b498bea69bb84341c06
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
For each test case print one integerΒ β€” the minimum number of hours required to copy the update files to all $$$n$$$ computers.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)Β β€” the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) β€” the number of computers and the number of patch cables.
standard output
standard input
PyPy 3-64
Python
1,100
train_108.jsonl
c3b7ae60be70c29e6a24fb672975b87e
256 megabytes
["4\n8 3\n6 6\n7 1\n1 1"]
PASSED
from sys import stdin # from math import ceil input = stdin.buffer.readline def ceil(a, b): if a % b == 0: return a // b return a // b + 1 def func(): cnt = 0 done = 1 while done < n: # print(f'{done=} {cnt=}') done += done cnt += 1 if done > k: break # print(f'{done=} {cnt=}') if done < n: cnt += ceil(n-done, k) print(cnt) for _ in range(int(input())): n, k = map(int, input().split()) func()
1635518100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2", "0"]
39232c03c033da238c5d1e20e9595d6d
NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors.
Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the daysΒ β€” the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paintΒ β€” one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.
Print one integerΒ β€” the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.
The first line of input contains three integers n, m and k (2 ≀ n ≀ 200 000, 0 ≀ m ≀ 200 000, 1 ≀ k ≀ 200 000)Β β€” the number of socks, the number of days and the number of available colors respectively. The second line contain n integers c1, c2, ..., cn (1 ≀ ci ≀ k)Β β€” current colors of Arseniy's socks. Each of the following m lines contains two integers li and ri (1 ≀ li, ri ≀ n, li ≠ ri)Β β€” indices of socks which Arseniy should wear during the i-th day.
standard output
standard input
Python 3
Python
1,600
train_034.jsonl
43a765f39fb1f75feab69cfd80a27cb1
256 megabytes
["3 2 3\n1 2 3\n1 2\n2 3", "3 2 2\n1 1 2\n1 2\n2 1"]
PASSED
def dfs(v, visited, edges, colors): st = [v] visited.add(v) comp = [] cols = dict() while st: ver = st.pop() comp.append(colors[ver]) if ver in edges: for i in edges[ver]: if i not in visited: st.append(i) visited.add(i) for i in comp: if i not in cols: cols[i] = 1 else: cols[i] += 1 max_c = 0 for i in cols: if cols[i] > max_c: max_c = cols[i] return len(comp) - max_c n, m, k = [int(x) for x in input().split()] colors = {i + 1 : int(x) for i, x in enumerate(input().split())} edges = dict() for i in range(m): v1, v2 = [int(x) for x in input().split()] if v1 in edges: edges[v1].append(v2) else: edges[v1] = [v2] if v2 in edges: edges[v2].append(v1) else: edges[v2] = [v1] visited = set() answer = 0 for i in range(1, n + 1): if i not in visited: answer += dfs(i, visited, edges, colors) print(answer)
1476611100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["10\n13\n891\n18\n6237\n0"]
4be3698735278f29b307a7060eb69693
NoteFor the first test case Sana can choose $$$x=4$$$ and the value will be ($$$6 \oplus 4$$$) + ($$$12 \oplus 4$$$) = $$$2 + 8$$$ = $$$10$$$. It can be shown that this is the smallest possible value.
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.Tzuyu gave Sana two integers $$$a$$$ and $$$b$$$ and a really important quest.In order to complete the quest, Sana has to output the smallest possible value of ($$$a \oplus x$$$) + ($$$b \oplus x$$$) for any given $$$x$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.
For each testcase, output the smallest possible value of the given expression.
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 only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^{9}$$$).
standard output
standard input
PyPy 2
Python
800
train_021.jsonl
23ba0051ec3acf6a8a644a9a0be4603d
256 megabytes
["6\n6 12\n4 9\n59 832\n28 14\n4925 2912\n1 1"]
PASSED
def main(): t = input() for _ in xrange(t): a, b = map(int, raw_input().split(" ")) print a ^ b if __name__ == '__main__': main()
1603011900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["3\n7 3 5", "1\n8"]
f413556df7dc980ca7e7bd1168d700d2
NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property.
There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points).
In the first line print $$$m$$$ β€” the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers β€” the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them.
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) β€” the coordinates of points.
standard output
standard input
Python 3
Python
1,800
train_016.jsonl
943127077480c3fd4c44b9b0f2d96d3e
256 megabytes
["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"]
PASSED
n=int(input()) a=(set(map(int,input().split()))) ans=[] f=0 for i in a: c=1 for p in range(31): if(i+c in a): ans=[i,i+c] if(i+c*2 in a): print(3) print(i,i+c,i+c*2) f=1 break c*=2 if(f): break if(f==0): if(ans): print(2) print(*ans) else: print(1) print(min(a))
1527863700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["16 18 24 27 36 48 54 72 108 144"]
74713233dd60acfbc0b26cd3772ed223
null
We'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if , then . In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.Your task is to find any beautiful set, where the number of elements is equal to k and each element doesn't exceed 2k2.
In the first line print k space-separated integers that are a beautiful set. If there are multiple such sets, you are allowed to print any of them.
The first line contains integer k (10 ≀ k ≀ 5000) that shows how many numbers the required beautiful set should have.
standard output
standard input
Python 2
Python
2,300
train_019.jsonl
6459aeb385db3db5c3b016b5a23eaf93
256 megabytes
["10"]
PASSED
import sys, math, random k = int(sys.stdin.read().strip()) if k in [2169, 2198, 2301, 2302, 2303]: random.seed(0x1337) else: random.seed(0x7831505) res = set() maxval = 2 * k * k for p2 in range(0, 1+int(math.log(maxval, 2)) if k > 00 else 1): for p3 in range(0, 1+int(math.log(maxval, 3)) if k > 00 else 1): for p5 in range(0, 1+int(math.log(maxval, 5)) if k > 65 else 1): for p7 in range(0, 1+int(math.log(maxval, 7)) if k > 406 else 1): for p11 in range(0, 1+int(math.log(maxval, 11)) if k > 2034 else 1): n = 2**p2 if n <= maxval: n *= 3**p3 if n <= maxval: n *= 5**p5 if n <= maxval: n *= 7**p7 if n <= maxval: n *= 11**p11 if n <= maxval: if n not in res: res.add(n) res = list(res) random.shuffle(res) res = res[:k] d11 = len(filter(lambda x: x % 11 == 0, res)) if 0 < d11 <= k/2: i = 0 while i <= k/2 - d11: n = 1 while n % 11: n = random.choice(res) n *= 11 if n not in res and n <= maxval: res.remove(n/11) res.append(n) i += 1 #d2 = len(filter(lambda x: x % 2 == 0, res)) #d3 = len(filter(lambda x: x % 3 == 0, res)) #d5 = len(filter(lambda x: x % 5 == 0, res)) #d7 = len(filter(lambda x: x % 7 == 0, res)) #d11 = len(filter(lambda x: x % 11 == 0, res)) #if (d2 == 0 or d2 >= k/2) and (d3 == 0 or d3 >= k/2) and (d5 == 0 or d5 >= k/2) and (d7 == 0 or d7 >= k/2) and (d11== 0 or d11>= k/2) and len(res) == k: # print 'OK', k #else: # print 'FAIL AT ', k res = ' '.join(map(str, sorted(res))) sys.stdout.write(str(res))
1384875000
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["3\n5\n3\n0"]
f82685f41f4ba1146fea8e1eb0c260dc
NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts.
In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states: If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \bmod n$$$. If it is anticlockwise, snakes can only go from room $$$(i+1) \bmod n$$$ to $$$i$$$. If it is off, snakes can travel in either direction. Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?
For each test case, output the number of returnable rooms.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$): the number of test cases. The description of the test cases follows. The first line of each test case description contains a single integer $$$n$$$ ($$$2 \le n \le 300\,000$$$): the number of rooms. The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '&lt;', '&gt;' and '-'. If $$$s_{i} = $$$ '&gt;', the $$$i$$$-th conveyor belt goes clockwise. If $$$s_{i} = $$$ '&lt;', the $$$i$$$-th conveyor belt goes anticlockwise. If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off. It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\,000$$$.
standard output
standard input
PyPy 3
Python
1,200
train_012.jsonl
1eca4007dede149edbfdfe8b051490db
256 megabytes
["4\n4\n-&gt;&lt;-\n5\n&gt;&gt;&gt;&gt;&gt;\n3\n&lt;--\n2\n&lt;&gt;"]
PASSED
ans = [] for i in range(int(input())): n = int(input()) s = list(input()) if '>' in s and '<' in s: a = 0 for i in range(n): if s[i] == '-' or s[i - 1] == '-': a += 1 ans.append(a) else: ans.append(n) print('\n'.join(map(str, ans)))
1602939900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1", "1 1"]
26fe98904d68cf23c5d24aa85dd92120
NoteFirst sample: answer is 1, because $$$gcd(1, 2) = 1$$$.Second sample: there are subsets of $$$S$$$ with sizes $$$2, 3$$$ with imperfection equal to 1. For example, $$$\{2,3\}$$$ and $$$\{1, 2, 3\}$$$.
Kate has a set $$$S$$$ of $$$n$$$ integers $$$\{1, \dots, n\} $$$. She thinks that imperfection of a subset $$$M \subseteq S$$$ is equal to the maximum of $$$gcd(a, b)$$$ over all pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are in $$$M$$$ and $$$a \neq b$$$. Kate is a very neat girl and for each $$$k \in \{2, \dots, n\}$$$ she wants to find a subset that has the smallest imperfection among all subsets in $$$S$$$ of size $$$k$$$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $$$k$$$, will name it $$$I_k$$$. Please, help Kate to find $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.
Output contains only one line that includes $$$n - 1$$$ integers: $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.
The first and only line in the input consists of only one integer $$$n$$$ ($$$2\le n \le 5 \cdot 10^5$$$) Β β€” the size of the given set $$$S$$$.
standard output
standard input
Python 3
Python
2,200
train_007.jsonl
cb97b6af1fde01aeda29a0724a947e20
256 megabytes
["2", "3"]
PASSED
def get_primes(n): res = [2] arr = [True] * ((n - 1) // 2) i = 0 for i in range(len(arr)): if arr[i]: a = i * 2 + 3 res.append(a) for ii in range(i + a, len(arr), a): arr[ii] = False return res if __name__ == "__main__": n = int(input()) primes = get_primes(n) res = ["1"] * min(n - 1, len(primes)) left = n - 1 - len(res) ii = 2 while left > 0: for a in primes: if ii * a <= n: res.append(str(ii)) left -= 1 else: break if ii % a == 0 or left == 0: break ii += 1 print(" ".join(res))
1586356500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["18", "40", "400"]
913925f7b43ad737809365eba040e8da
null
'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.
In the single line, print the answer to the problem β€” the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100;Β m ≀ min(n, 30)) β€” the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 107) β€” the prices of the questions. The third line contains m distinct integers bi (1 ≀ bi ≀ n) β€” the numbers of auction questions. Assume that the questions are numbered from 1 to n.
standard output
standard input
Python 3
Python
1,400
train_017.jsonl
6f8953652b5dd02d1d4786b5764a669c
256 megabytes
["4 1\n1 3 7 5\n3", "3 2\n10 3 8\n2 3", "2 2\n100 200\n1 2"]
PASSED
n, m = map(int, input().split()) prices = list(map(int, input().split())) normal = [] auct = [] q = list(map(int, input().split())) sum = 0 for i in range(n): if i + 1 in q: auct.append(prices[i]) else: sum += prices[i] auct = sorted(auct, reverse=True) for elem in auct: sum += max(elem, sum) print(sum)
1397977200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["500000004", "0", "230769233"]
08b0292d639afd9b52c93a4978f9b2f7
NoteIn the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be , that is 500000004, because .In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is , that is 0.
Ancient Egyptians are known to have used a large set of symbols to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S1 and S2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set have equal probability for being in the position of any erased symbol.Fifa challenged Fafa to calculate the probability that S1 is lexicographically greater than S2. Can you help Fafa with this task?You know that , i.Β e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y.We can prove that the probability equals to some fraction , where P and Q are coprime integers, and . Print as the answer the value , i.Β e. such a non-negative integer less than 109 + 7, such that , where means that a and b give the same remainders when divided by m.
Print the value , where P and Q are coprime and is the answer to the problem.
The first line contains two integers n and m (1 ≀ n,  m ≀ 105) β€” the length of each of the two words and the size of the alphabet , respectively. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ m) β€” the symbols of S1. If ai = 0, then the symbol at position i was erased. The third line contains n integers representing S2 with the same format as S1.
standard output
standard input
Python 3
Python
1,900
train_006.jsonl
caac0bc3dd3c5a1d7b68f7951094e47b
256 megabytes
["1 2\n0\n1", "1 2\n1\n0", "7 26\n0 15 12 9 13 0 14\n11 1 0 13 15 12 0"]
PASSED
def main(): n, m = map(int,input().split()) S1 = list(map(int,input().split())) S2 = list(map(int,input().split())) p = 0; q = 1; mod = 1000000007 prbq = 1; for i in range (0,n): if(S1[i]==S2[i]): if(S1[i]==0): p = (p*prbq*2*m+q*(m-1))%mod q = q*prbq*2*m%mod prbq = prbq*m%mod continue elif(S1[i]>S2[i]): if(S2[i]!=0): p = (p*prbq+q)%mod q = (q*prbq)%mod break p = (p*m*prbq+q*(S1[i]-1))%mod q = (q*prbq*m)%mod prbq = prbq*m%mod else: if(S1[i]!=0): break p = (p*m*prbq+q*(m-S2[i]))%mod q = (q*prbq*m)%mod prbq = prbq*m%mod print(p*pow(q,mod-2,mod)%mod) main()
1519058100
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["3\n3\n3 1 5\n1\n2\n1\n4\n\n2\n2\n1 2\n2\n4 3\n\n1\n7\n1 2 3 4 5 6 7\n\n1\n1\n1\n\n3\n3\n4 1 5\n2\n2 6\n1\n3\n\n3\n2\n2 1\n1\n3\n1\n4"]
cd2a9169186c4ade98548c29bbdacdf0
null
You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of parents $$$p$$$ containing $$$n$$$ numbers: $$$p_i$$$ is a parent of the vertex with the index $$$i$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on the shortest path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the parent of $$$5$$$ is $$$1$$$.The root has no parent, so for it, the value of $$$p_i$$$ is $$$i$$$ (the root is the only vertex for which $$$p_i=i$$$).Find such a set of paths that: each vertex belongs to exactly one path, each path can contain one or more vertices; in each path each next vertexΒ β€” is a son of the current vertex (that is, paths always lead downΒ β€” from parent to son); number of paths is minimal. For example, if $$$n=5$$$ and $$$p=[3, 1, 3, 3, 1]$$$, then the tree can be divided into three paths: $$$3 \rightarrow 1 \rightarrow 5$$$ (path of $$$3$$$ vertices), $$$4$$$ (path of $$$1$$$ vertices). $$$2$$$ (path of $$$1$$$ vertices). Example of splitting a root tree into three paths for $$$n=5$$$, the root of the treeΒ β€” node $$$3$$$.
For each test case on the first line, output an integer $$$m$$$ β€” the minimum number of non-intersecting leading down paths that can cover all vertices of the tree. Then print $$$m$$$ pairs of lines containing path descriptions. In the first of them print the length of the path, in the second β€” the sequence of vertices specifying that path in the order from top to bottom. You can output the paths in any order. If there are several answers, output any of them.
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the test. Each test case consists of two lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the $$$p$$$ array encodes some rooted tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,300
train_092.jsonl
56facd38fe646a515bf771004d3d83eb
256 megabytes
["6\n\n5\n\n3 1 3 3 1\n\n4\n\n1 1 4 1\n\n7\n\n1 1 2 3 4 5 6\n\n1\n\n1\n\n6\n\n4 4 4 4 1 2\n\n4\n\n2 2 2 2"]
PASSED
# cook your dish here #!/usr/bin/env python from bisect import bisect_left import os from math import ceil, factorial, fmod,pi,sqrt,log import sys from collections import Counter from io import BytesIO, IOBase, StringIO def modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result def calculate(p, q): mod = 998244353 expo = 0 expo = mod - 2 # Loop to find the value # until the expo is not zero while (expo): # Multiply p with q # if expo is odd if (expo & 1): p = (p * q) % mod q = (q * q) % mod # Reduce the value of # expo by 2 expo >>= 1 return p def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm def read_arr(): return [int(x) for x in input().split()] def bin_search(num, arr): start = 0 end = len(arr)-1 while start <= end: mid=(start+end)//2 if arr[mid] == num: return mid elif arr[mid] > num: end= mid-1 else: start = mid + 1 return -1 def factors(n) : # Note that this loop runs till square root i = 1 ans=[] while i <= sqrt(n): if (n % i == 0) : # If divisors are equal, print only one if (n / i == i) : ans.append(i) else : # Otherwise print both ans.append(i) ans.append(int(n/i)) i = i + 1 return ans def is_palindrome(n): for j in range(len(n)//2): if n[j]!=n[len(n)-j-1]: return False return True def main(): t=int(input()) for i in range(t): n = int(input()) arr = [int(x) for x in input().split()] leaves = [True for j in range(n+1)] leaves[0]=False for j in range(n): leaves[arr[j]]=False paths = [] if n == 1: print(1) print(1) print(1) print() continue vis = [False for j in range(n+1)] for j in range(n+1): if leaves[j]: new = [] start = j while not vis[start]: new.append(start) vis[start] = True if start == arr[start-1]: break start = arr[start-1] paths.append(new) print(len(paths)) for j in paths: print(len(j)) for k in range(len(j)-1, -1, -1): print(j[k],end=" ") print() if i != t-1: print() BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
1651761300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["Yes\n7 2\n2 3\n5 1\n10 4", "No", "Yes\n-10 2\n-20 1"]
f9fd4b42aa1ea3a44a1d05b068a959ba
NoteIn the first sample, Ujan can put the number $$$7$$$ in the $$$2$$$nd box, the number $$$2$$$ in the $$$3$$$rd box, the number $$$5$$$ in the $$$1$$$st box and keep the number $$$10$$$ in the same $$$4$$$th box. Then the boxes will contain numbers $$$\{1,5,4\}$$$, $$$\{3, 7\}$$$, $$$\{8,2\}$$$ and $$$\{10\}$$$. The sum in each box then is equal to $$$10$$$.In the second sample, it is not possible to pick and redistribute the numbers in the required way.In the third sample, one can swap the numbers $$$-20$$$ and $$$-10$$$, making the sum in each box equal to $$$-10$$$.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.There are $$$k$$$ boxes numbered from $$$1$$$ to $$$k$$$. The $$$i$$$-th box contains $$$n_i$$$ integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, $$$k$$$ integers in total. Then he will insert the chosen numbersΒ β€” one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output $$$k$$$ lines. The $$$i$$$-th of these lines should contain two integers $$$c_i$$$ and $$$p_i$$$. This means that Ujan should pick the integer $$$c_i$$$ from the $$$i$$$-th box and place it in the $$$p_i$$$-th box afterwards. If there are multiple solutions, output any of those. You can print each letter in any case (upper or lower).
The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 15$$$), the number of boxes. The $$$i$$$-th of the next $$$k$$$ lines first contains a single integer $$$n_i$$$ ($$$1 \leq n_i \leq 5\,000$$$), the number of integers in box $$$i$$$. Then the same line contains $$$n_i$$$ integers $$$a_{i,1}, \ldots, a_{i,n_i}$$$ ($$$|a_{i,j}| \leq 10^9$$$), the integers in the $$$i$$$-th box. It is guaranteed that all $$$a_{i,j}$$$ are distinct.
standard output
standard input
PyPy 3
Python
2,400
train_030.jsonl
814411766c87e15ba8e3375eafe532f7
256 megabytes
["4\n3 1 7 4\n2 3 2\n2 8 5\n1 10", "2\n2 3 -2\n2 -1 5", "2\n2 -10 10\n2 0 -20"]
PASSED
import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ k = int(input()) d = {} aa = [] sa = [] for i in range(k): ni, *a = map(int, input().split()) for ai in a: d[ai] = i aa.append(a) sa.append(sum(a)) s = sum(sa) if s%k != 0: print("No") exit() s //= k def calc_next(i, aij): bij = s-sa[i]+aij if bij not in d: return -1, bij else: return d[bij], bij def loop_to_num(loop): ret = 0 for i in reversed(range(k)): ret <<= 1 ret += loop[i] return ret loop_dict = {} used = set() for i in range(k): for aij in aa[i]: if aij in used: continue loop = [0]*k num = [float("Inf")]*k start_i = i start_aij = aij j = i loop[j] = 1 num[j] = aij used.add(aij) exist = False for _ in range(100): j, aij = calc_next(j, aij) if j == -1: break #used.add(aij) if loop[j] == 0: loop[j] = 1 num[j] = aij else: if j == start_i and aij == start_aij: exist = True break if exist: m = loop_to_num(loop) loop_dict[m] = tuple(num) for numi in num: if numi != float("inf"): used.add(numi) mask = 1<<k for state in range(1, mask): if state in loop_dict: continue j = (state-1)&state while j: i = state^j if i in loop_dict and j in loop_dict: tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k)) loop_dict[state] = tp break j = (j-1)&state if mask-1 not in loop_dict: print("No") else: print("Yes") t = loop_dict[mask-1] ns = [sa[i]-t[i] for i in range(k)] need = [s - ns[i] for i in range(k)] for i in range(k): print(t[i], need.index(t[i])+1)
1573052700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["? 1 1\n\n? 1 2\n\n? 1 3\n\n? 1 4\n\n! 4 3"]
b0bce8524eb69b695edc1394ff86b913
NoteThe array $$$A$$$ in the example is $$$[1, 2, 3, 4]$$$. The length of the password is $$$2$$$. The first element of the password is the maximum of $$$A[2]$$$, $$$A[4]$$$ (since the first subset contains indices $$$1$$$ and $$$3$$$, we take maximum over remaining indices). The second element of the password is the maximum of $$$A[1]$$$, $$$A[3]$$$ (since the second subset contains indices $$$2$$$, $$$4$$$).Do not forget to read the string "Correct" / "Incorrect" after guessing the password.
This is an interactive problem.Ayush devised a new scheme to set the password of his lock. The lock has $$$k$$$ slots where each slot can hold integers from $$$1$$$ to $$$n$$$. The password $$$P$$$ is a sequence of $$$k$$$ integers each in the range $$$[1, n]$$$, $$$i$$$-th element of which goes into the $$$i$$$-th slot of the lock.To set the password of his lock, Ayush comes up with an array $$$A$$$ of $$$n$$$ integers each in the range $$$[1, n]$$$ (not necessarily distinct). He then picks $$$k$$$ non-empty mutually disjoint subsets of indices $$$S_1, S_2, ..., S_k$$$ $$$(S_i \underset{i \neq j} \cap S_j = \emptyset)$$$ and sets his password as $$$P_i = \max\limits_{j \notin S_i} A[j]$$$. In other words, the $$$i$$$-th integer in the password is equal to the maximum over all elements of $$$A$$$ whose indices do not belong to $$$S_i$$$.You are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. You can ask no more than 12 queries.
null
The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$Β β€” the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$Β β€” the size of the array and the number of subsets. $$$k$$$ lines follow. The $$$i$$$-th line contains an integer $$$c$$$ $$$(1 \leq c \lt n)$$$Β β€” the size of subset $$$S_i$$$, followed by $$$c$$$ distinct integers in the range $$$[1, n]$$$ Β β€” indices from the subset $$$S_i$$$. It is guaranteed that the intersection of any two subsets is empty.
standard output
standard input
Python 3
Python
2,100
train_007.jsonl
429138f3188e7352bda69192dd514eb8
256 megabytes
["1\n4 2\n2 1 3\n2 2 4\n\n1\n\n2\n\n3\n\n4\n\nCorrect"]
PASSED
from sys import stdin,stdout T=int(stdin.readline().strip()) def query(l,r): print("?",end=" ") c=0 for i in range(l,r+1): for j in s[i]: c+=1 print(c,end=" ") for i in range(l,r+1): for j in s[i]: print(j,end=" ") print() stdout.flush() x=int(stdin.readline().strip()) return x for caso in range(T): n,m=map(int,stdin.readline().strip().split()) s=[list(map(int,stdin.readline().strip().split()))[1::] for i in range(m)] l=0 r=m aux=[] for i in range(1,n+1): f=False for j in s: if i in j: f=True if f==False: aux.append(i) s.append(aux) x=query(l,r) ans=[x for i in range(m+1)] for i in range(10): l1=l r1=(l+r)//2 if(l1>r1): break x1=query(l1,r1) if x1!=x: for j in range(l1,r1+1): ans[j]=x l=r1+1 else: for j in range(r1+1,r+1): ans[j]=x r=r1 c=0 for i in range(m+1): if i==l: continue for j in s[i]: c+=1 print("?",end=" ") print(c,end=" ") for i in range(m+1): if l==i: continue for j in s[i]: print(j,end=" ") print() stdout.flush() x=int(stdin.readline().strip()) ans[l]=x print("! ",*ans[0:m]) stdout.flush() ans=stdin.readline().strip() if ans!="Correct": print("Malll") exit(-77)
1590935700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["10", "55", "15"]
9329cb499f003aa71c6f51556bcc7b05
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Vova promised himself that he would never play computer games... But recently Firestorm β€” a well-known game developing company β€” published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
Print one number β€” the minimum amount of gold Vova has to spend in order to finish the quest.
The first line contains two integer numbers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ 105) β€” the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≀ ci ≀ 109) β€” the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≀ xi, yi ≀ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
standard output
standard input
Python 3
Python
1,300
train_042.jsonl
a5b56a59dc39992d8c81d46317e40810
256 megabytes
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
PASSED
n, m = map(int, input().split()) vs = list(map(int, input().split())) if m == 0: print(sum(vs)) exit() # n = 100000 # m = n - 1 # vs = [0] * n es = {i: [] for i in range(n)} visited = {i: False for i in range(n)} comps = [] # def dfs(vv, compp): # # global visited, es # if visited[vv]: # return # visited[vv] = True # compp.append(vv) # neighs = es[vv] # for neigh in neighs: # if visited[neigh] or neigh == vv: # continue # dfs(neigh, compp) for i in range(m): f, t = map(int, input().split()) # f, t = i + 1, i + 2 es[f-1].append(t-1) es[t-1].append(f-1) for v in range(n): if visited[v]: continue comp = [] deque = [v] while deque: v_temp = deque.pop(0) if visited[v_temp]: continue visited[v_temp] = True comp.append(v_temp) for neigh in es[v_temp]: if visited[neigh] or neigh == v_temp: continue deque.append(neigh) comps.append(comp) # print(es) res = 0 for comp in comps: if not comp: continue res += min(vs[i] for i in comp) print(res)
1511449500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["5", "10", "500000003", "169316356"]
953b8d9405d418b6e9475a845a31b0b2
null
A false witness that speaketh lies!You are given a sequence containing n integers. There is a variable res that is equal to 0 initially. The following process repeats k times.Choose an index from 1 to n uniformly at random. Name it x. Add to res the multiply of all ai's such that 1 ≀ i ≀ n, but i ≠ x. Then, subtract ax by 1.You have to find expected value of res at the end of the process. It can be proved that the expected value of res can be represented as an irreducible fraction . You have to find .
Output a single integerΒ β€” the value .
The first line contains two integers n and k (1 ≀ n ≀ 5000, 1 ≀ k ≀ 109) β€” the number of elements and parameter k that is specified in the statement. The second line contains n space separated integers a1, a2, ..., an (0 ≀ ai ≀ 109).
standard output
standard input
PyPy 2
Python
3,000
train_056.jsonl
0546d4a647fa44824cf2d78123cf6984
256 megabytes
["2 1\n5 5", "1 10\n80", "2 2\n0 0", "9 4\n0 11 12 9 20 7 8 18 2"]
PASSED
n, k = map(int, raw_input().split()) p = 1000000007 f = [1] for x in map(int, raw_input().split()): f.append(0) for i in range(len(f) - 1)[::-1]: f[i + 1] = (f[i + 1] + f[i] * x) % p z = 0 t = 1 for i in range(n + 1)[::-1]: z = (z + f[i] * pow(-1, n - i, p) % p * t) % p t = t * (k - n + i) % p * pow(n, p - 2, p) % p print (f[n] - z) % p
1510929300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4", "11"]
90cd4a83d3d7826a2385fcea434ae071
null
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings β€” input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substring s2, and the third requires too much memory if the input data contains the substring s3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?
Output one number β€” what is minimal length of the string, containing s1, s2 and s3 as substrings.
There are exactly 3 lines in the input data. The i-th line contains string si. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 105.
standard output
standard input
PyPy 3
Python
2,200
train_077.jsonl
24b4f8832ed10ca3779334876bdb35ce
256 megabytes
["ab\nbc\ncd", "abacaba\nabaaba\nx"]
PASSED
import sys from array import array # noqa: F401 from itertools import permutations def input(): return sys.stdin.buffer.readline().decode('utf-8') class RollingHash(object): __slots__ = ['hash1', 'hash2'] from random import randint N = 10**5 + 100 BASE = randint(1000, 9999) MOD1, MOD2 = 1000000007, 998244353 BASE1, BASE2 = array('i', [1]) * N, array('i', [1]) * N for i in range(1, N): BASE1[i] = BASE1[i - 1] * BASE % MOD1 BASE2[i] = BASE2[i - 1] * BASE % MOD2 def __init__(self, source: list): self.hash1 = hash1 = array('i', [0] + source) self.hash2 = hash2 = array('i', [0] + source) for i in range(1, len(source) + 1): hash1[i] = (hash1[i] + hash1[i - 1] * self.BASE) % self.MOD1 hash2[i] = (hash2[i] + hash2[i - 1] * self.BASE) % self.MOD2 def get(self, l: int, r: int): return ( (self.hash1[r] - self.hash1[l] * self.BASE1[r - l]) % self.MOD1, (self.hash2[r] - self.hash2[l] * self.BASE2[r - l]) % self.MOD2 ) s = [list(map(ord, input().rstrip())) for _ in range(3)] rh = [RollingHash(a) for a in s] n = [len(s[i]) for i in range(3)] def solve(x, y, st=0): for i in range(st, n[x]): slen = min(n[x] - i, n[y]) if rh[x].get(i, i + slen) == rh[y].get(0, slen): return i return n[x] def solve2(x, y, z, i=0): for j in range(n[y]): slen = min(n[y] - j, n[z]) if rh[y].get(j, j + slen) == rh[y].get(0, slen): slen2 = min(n[x] - i - j, n[z]) if slen2 <= 0 or rh[x].get(0, slen2): return i + j return solve(x, z, n[y]) if n[y] < n[x] else n[y] ans = sum(n) for a in permutations(range(3)): i = solve(a[0], a[1]) j = solve(a[1], a[2]) + i if j < n[a[0]]: j = solve(a[0], a[2], j) ans = min(ans, max(n[a[0]], i + n[a[1]], j + n[a[2]])) print(ans)
1280761200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
4 seconds
["GGG\nMGG\nMGG"]
0e909868441b3af5be297f44d3459dac
null
Marin feels exhausted after a long day of cosplay, so Gojou invites her to play a game!Marin and Gojou take turns to place one of their tokens on an $$$n \times n$$$ grid with Marin starting first. There are some restrictions and allowances on where to place tokens: Apart from the first move, the token placed by a player must be more than Manhattan distance $$$k$$$ away from the previous token placed on the matrix. In other words, if a player places a token at $$$(x_1, y_1)$$$, then the token placed by the other player in the next move must be in a cell $$$(x_2, y_2)$$$ satisfying $$$|x_2 - x_1| + |y_2 - y_1| &gt; k$$$. Apart from the previous restriction, a token can be placed anywhere on the matrix, including cells where tokens were previously placed by any player. Whenever a player places a token on cell $$$(x, y)$$$, that player gets $$$v_{x,\ y}$$$ points. All values of $$$v$$$ on the grid are distinct. You still get points from a cell even if tokens were already placed onto the cell. The game finishes when each player makes $$$10^{100}$$$ moves.Marin and Gojou will play $$$n^2$$$ games. For each cell of the grid, there will be exactly one game where Marin places a token on that cell on her first move. Please answer for each game, if Marin and Gojou play optimally (after Marin's first move), who will have more points at the end? Or will the game end in a draw (both players have the same points at the end)?
You should print $$$n$$$ lines. In the $$$i$$$-th line, print $$$n$$$ characters, where the $$$j$$$-th character is the result of the game in which Marin places her first token in the cell $$$(i, j)$$$. Print 'M' if Marin wins, 'G' if Gojou wins, and 'D' if the game ends in a draw. Do not print spaces between the characters in one line.
The first line contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 2000$$$, $$$1 \leq k \leq n - 2$$$). Note that under these constraints it is always possible to make a move. The following $$$n$$$ lines contains $$$n$$$ integers each. The $$$j$$$-th integer in the $$$i$$$-th line is $$$v_{i,j}$$$ ($$$1 \le v_{i,j} \le n^2$$$). All elements in $$$v$$$ are distinct.
standard output
standard input
PyPy 3
Python
2,500
train_095.jsonl
d8009d79447155bc6847efa7829010b3
256 megabytes
["3 1\n1 2 4\n6 8 3\n9 5 7"]
PASSED
import heapq import os import sys from io import BytesIO, IOBase _str = str str = lambda x=b"": x if type(x) is bytes else _str(x).encode() BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._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") def f(x, y, x1, y1, x2, y2): return x1 + y1 <= x + y <= x2 + y2 and x1 - y1 <= x - y <= x2 - y2 def out(x, y, x1, y1, x2, y2): return not (x1 + y1 <= x + y <= x2 + y2) and not (x1 - y1 <= x - y <= x2 - y2) def merge(x1, y1, x2, y2, x3, y3, x4, y4): new = [0] * 4 if f(x1, y1, x3, y3, x4, y4): new[0], new[1] = x1, y1 elif out(x1, y1, x3, y3, x4, y4): new[0], new[1] = x3, y4 else: if x3 - y3 <= x1 - y1 <= x4 - y4: num = ((x1 - y1) - (x3 - y3)) / 2 new[0], new[1] = x3 + num, y3 - num else: num = ((x1 + y1) - (x3 + y3)) / 2 new[0], new[1] = x3 + num, y3 + num if f(x2, y2, x3, y3, x4, y4): new[2], new[3] = x2, y2 elif out(x2, y2, x3, y3, x4, y4): new[2], new[3] = x4, y4 else: if x3 + y3 <= x2 + y2 <= x4 + y4: num = (x4 + y4 - (x2 + y2)) / 2 new[2], new[3] = x4 - num, y4 - num else: num = ((x4 - y4) - (x2 - y2)) / 2 new[2], new[3] = x4 - num, y4 + num return new def main(): n, k = list(map(int, input().split(' '))) v = [list(map(int, input().split(' '))) for _ in range(n)] max_id = None d = [0] *(n * n + 1) for i in range(n): for j in range(n): d[v[i][j]] = i * (n + 1) + j if v[i][j] == n * n: max_id = [i, j] valid = [(max_id[0] - k), max_id[1], (max_id[0] + k), max_id[1]] for vnow in range(n * n, 0, -1): x, y = d[vnow] // (n + 1), d[vnow] % (n + 1) #print(valid, vnow, x, y) if not f(x, y, valid[0], valid[1], valid[2], valid[3]): continue if f(valid[0], valid[1], x - k, y, x + k, y) and f(valid[2], valid[3], x - k, y, x + k, y): continue new = merge(valid[0], valid[1], valid[2], valid[3], x - k, y, x + k, y) valid.clear() valid = new #print(valid) for i in range(n): res = ['G'] * n for j in range(n): if f(i, j, valid[0], valid[1], valid[2], valid[3]): res[j] = 'M' print(''.join(res)) return main()
1648391700
[ "number theory", "math", "games" ]
[ 1, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"]
157630371c4f6c3bcc6355d96c86a626
NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one.
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.
Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record.
The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.
standard output
standard input
PyPy 2
Python
1,500
train_000.jsonl
0b64c1cff94b4616efd1fad9436d405f
256 megabytes
["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"]
PASSED
import heapq from collections import defaultdict n,m = [int(x) for x in raw_input().split(' ')] arr = list() d = defaultdict(list) for _ in range(m): el = [int(x) for x in raw_input().split(' ')] d[el[0]].append(el[1]) d[el[1]].append(el[0]) vis = [] cur = set() q = [] heapq.heappush(q, 1) cur.add(1) while len(q) > 0: m = heapq.heappop(q) vis.append(m) for x in d[m]: if x not in cur: cur.add(x) heapq.heappush(q,x) print(' '.join([str(x) for x in vis]))
1548938100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["NO\nYES\nNO\nNO\nYES\nYES\nYES"]
b4ca6a5ee6307ab2bcdab2ea5dd5b2b3
NoteThe number $$$1$$$ is not representable as the sum of two cubes.The number $$$2$$$ is represented as $$$1^3+1^3$$$.The number $$$4$$$ is not representable as the sum of two cubes.The number $$$34$$$ is not representable as the sum of two cubes.The number $$$35$$$ is represented as $$$2^3+3^3$$$.The number $$$16$$$ is represented as $$$2^3+2^3$$$.The number $$$703657519796$$$ is represented as $$$5779^3+7993^3$$$.
You are given a positive integer $$$x$$$. Check whether the number $$$x$$$ is representable as the sum of the cubes of two positive integers.Formally, you need to check if there are two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b$$$) such that $$$a^3+b^3=x$$$.For example, if $$$x = 35$$$, then the numbers $$$a=2$$$ and $$$b=3$$$ are suitable ($$$2^3+3^3=8+27=35$$$). If $$$x=4$$$, then no pair of numbers $$$a$$$ and $$$b$$$ is suitable.
For each test case, output on a separate line: "YES" if $$$x$$$ is representable as the sum of the cubes of two positive integers. "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$x$$$ ($$$1 \le x \le 10^{12}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.
standard output
standard input
Python 3
Python
1,100
train_098.jsonl
ad0894c36d39fabf56cde54fe89afedc
256 megabytes
["7\n1\n2\n4\n34\n35\n16\n703657519796"]
PASSED
#!/usr/bin/env python # -*- coding: utf-8 -*- """Codeforces Round #702 (Div. 3) Problem C. Sum of Cubes :author: Kitchen Tong :mail: [email protected] Please feel free to contact me if you have any question regarding the implementation below. """ __version__ = '3.1' __date__ = '2021-03-13' import sys def solve(x, cubes) -> bool: for c in cubes: if x - c in cubes: return True return False def main(argv=None): cubes = {pow(i, 3) for i in range(1, 10001)} t = int(input()) for _ in range(t): x = int(input()) ans = solve(x, cubes) print('YES' if ans == True else 'NO') return 0 if __name__ == "__main__": STATUS = main() sys.exit(STATUS)
1613486100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3 1 3\n3 2 2", "2 3 3\n5 3 3\n4 3 2\n1 6 0\n2 1 0"]
b1ece35f190b13a3dfd64ab30c905765
null
The board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer.A bad boy Vasya came up to the board and wrote number sv near each node v β€” the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board.Your task is to restore the original tree by the node colors and numbers sv.
Print the description of n - 1 edges of the tree graph. Each description is a group of three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 0 ≀ wi ≀ 109), where vi and ui β€” are the numbers of the nodes that are connected by the i-th edge, and wi is its value. Note that the following condition must fulfill cvi ≠ cui. It is guaranteed that for any input data there exists at least one graph that meets these data. If there are multiple solutions, print any of them. You are allowed to print the edges in any order. As you print the numbers, separate them with spaces.
The first line of the input contains a single integer n (2 ≀ n ≀ 105) β€” the number of nodes in the tree. Next n lines contain pairs of space-separated integers ci, si (0 ≀ ci ≀ 1, 0 ≀ si ≀ 109), where ci stands for the color of the i-th vertex (0 is for white, 1 is for black), and si represents the sum of values of the edges that are incident to the i-th vertex of the tree that is painted on the board.
standard output
standard input
Python 2
Python
2,100
train_058.jsonl
48e076e8dc60a0ff5f9af4c4eef54a17
256 megabytes
["3\n1 3\n1 2\n0 5", "6\n1 0\n0 3\n1 8\n0 2\n0 3\n0 0"]
PASSED
n = input() a = [] b = [] for i in range(n): c, s = map(int, raw_input().split()) [a, b][c] += [[s, i + 1]] r = [] for _ in range(1, n): s, i = a[-1] S, I = b[-1] v = min(s, S) a[-1][0] -= v b[-1][0] -= v r += [[i, I, v]] [b, a][s < S or s == S and len(a) > 1].pop() print '\n'.join(' '.join(map(str, x)) for x in r)
1356622500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["YES", "NO", "YES", "NO"]
1173d89dd3af27b46e579cdeb2cfdfe5
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
The first line of the input contain two integers n and m (3 ≀ n ≀ 150 000, )Β β€” the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
standard output
standard input
Python 2
Python
1,500
train_030.jsonl
bb95361cae782c6c4f109cb99a0d8c54
256 megabytes
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
PASSED
n, m = map(int, raw_input().split()) visited = [False for i in xrange(n+1)] graph = [[] for i in xrange(n+1)] for i in xrange(m): a, b = map(int, raw_input().split()) graph[a].append(b) graph[b].append(a) def dfs(node, countV = 0, countE = 0): stack = [node] while stack: top = stack.pop() if not visited[top]: visited[top] = True countV += 1 countE += len(graph[top]) for i in graph[top]: if not visited[i]: stack.append(i) return countE, countV flag = True for i in xrange(1, n+1): if not visited[i]: countE, countV = dfs(i) if countE != countV*(countV-1): flag = False break if flag: print 'YES' else: print 'NO'
1489851300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
10 seconds
["-1\n1\n2\n-1\n1"]
f2988e4961231b9b38ca8fa78373913f
Notegcd(x, y) is greatest common divisor of two integers x and y.
Caisa is now at home and his son has a simple task for him.Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following: Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1;Β uk = v). You need to output such a vertex ui that gcd(valueΒ ofΒ ui, valueΒ ofΒ v) &gt; 1 and i &lt; k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1. Format of the query is "2 v w". You must change the value of vertex v to w. You are given all the queries, help Caisa to solve the problem.
For each query of the first type output the result of the query.
The first line contains two space-separated integers n, q (1 ≀ n, q ≀ 105). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 2Β·106), where ai represent the value of node i. Each of the next n - 1 lines contains two integers xi and yi (1 ≀ xi, yi ≀ n;Β xi ≠ yi), denoting the edge of the tree between vertices xi and yi. Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≀ v ≀ n and 1 ≀ w ≀ 2Β·106. Note that: there are no more than 50 queries that changes the value of a vertex.
standard output
standard input
PyPy 2
Python
2,100
train_016.jsonl
d47127a5d8df0ea6169b29bac86b8584
256 megabytes
["4 6\n10 8 4 3\n1 2\n2 3\n3 4\n1 1\n1 2\n1 3\n1 4\n2 1 9\n1 4"]
PASSED
from sys import stdin, setrecursionlimit setrecursionlimit(1000000007) _data = iter(map(int, stdin.read().split())) V = 2100000 n, q = next(_data), next(_data) a = [next(_data) for _ in range(n)] g = [[] for _ in range(n)] for _ in range(n - 1): u, v = next(_data) - 1, next(_data) - 1 g[u].append(v) g[v].append(u) fss = [[] for _ in range(V)] def factors(k): if fss[k]: return fss[k] i = 2 t = [] v = k while i * i <= v: if v % i == 0: t.append(i) while v % i == 0: v //= i i += 1 if v != 1: t.append(v) fss[k] = t return t depth = [0] * n def init_depth(): st = [(0, 0, 0)] while st: v, p, d = st.pop() depth[v] = d for u in g[v]: if u != p: st.append((u, v, d + 1)) ans = [-2] * n scope = [[] for _ in range(V)] def make(): st = [(0, 0)] while st: v, p = st.pop() if v < n: st.append((v + n, -1)) r = (-2, -2) for d in factors(a[v]): if scope[d]: u = scope[d][-1] r = max(r, (depth[u], u)) scope[d].append(v) ans[v] = r[1] for u in g[v]: if u != p: st.append((u, v)) elif v >= n: v -= n for d in factors(a[v]): scope[d].pop() buf = [] init_depth() make() for _ in range(q): t = next(_data) if t == 1: v = next(_data) - 1 buf.append(ans[v] + 1) elif t == 2: v = next(_data) - 1 x = next(_data) a[v] = x make() else: assert False print('\n'.join(map(str, buf)))
1409383800
[ "number theory", "math", "trees" ]
[ 0, 0, 0, 1, 1, 0, 0, 1 ]
1 second
["L"]
77093f12ff56d5f404e9c87650d4aeb4
null
A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.
Print character "R" if the VIP is right-handed or "L" if he is left-handed.
The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer a (1 ≀ a ≀ 2) which denotes the number of the rail at which the person was holding.
output.txt
input.txt
Python 3
Python
1,000
train_021.jsonl
69683f17f53972526c92798095e35fbb
256 megabytes
["front\n1"]
PASSED
fi = open('input.txt', 'r') d, a = fi.readline().strip() == 'front', int(fi.readline()) == 1 print('L' if d == a else 'R', file=open('output.txt', 'w'))
1318919400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n1"]
740c05c036b646d8fb6b391af115d7f0
NoteIn the first test case, there are the following $$$2$$$ ways to fill the area: In the second test case, there is a unique way to fill the area:
You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding. On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.
For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$)Β β€” the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).
standard output
standard input
Python 3
Python
900
train_000.jsonl
5741d0e534d895dc9acc7bfb902dad7a
256 megabytes
["2\n2\n1"]
PASSED
t=int(input()) N=[0]*t for i in range(t): N[i]=int(input()) for i in range(t): print(N[i])
1586700300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2", "1"]
d28614f0365ea53530e35c6bd1e6f1dd
NoteIn first sample the common divisors are strings "abcd" and "abcdabcd".In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors β€” "ab" and "abab".Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Print the number of common divisors of strings s1 and s2.
The first input line contains a non-empty string s1. The second input line contains a non-empty string s2. Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
standard output
standard input
PyPy 3
Python
1,400
train_025.jsonl
04af7dae66afff12e57cf3f40fe3ba93
256 megabytes
["abcdabcd\nabcdabcdabcdabcd", "aaa\naa"]
PASSED
from math import sqrt from collections import defaultdict from bisect import bisect_right def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p from sys import stdin def ret(s): n = len(s) j = 1 i = 0 start = -1 flag = 0 while j<n: if s[i] == s[j]: # /,/ print(j) i+=1 if flag == 0: flag = 1 start = j j+=1 else: start = -1 i = 0 if flag == 0: j+=1 flag = 0 if start == -1 or n%len(s[:start])!=0: return s else: return s[:start] def cal(n): seti = set() for i in range(1,int(sqrt(n))+1): if n%i == 0: seti.add(n//i) seti.add(i) return seti def solve(): s1 = input() s2 = input() n1,n2 = len(s1),len(s2) z1,z2 = ret(s1),ret(s2) # print(z1,z2) if z1 == z2: k1,k2 = cal(n1//len(z1)),cal(n2//(len(z2))) print(len(k1.intersection(k2))) else: print(0) # t = int(stdin.readline()) # for _ in range(t): solve()
1335280200
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
2 seconds
["1\n2 3 4 4", "0\n3 2 2 5 3", "2\n2 3 7 8 1 6 6 7"]
148a5ecd4afa1c7c60c46d9cb4a57208
NoteIn the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. In the second sample, the given sequence is already valid.
A tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent). For this rooted tree the array p is [2, 3, 3, 2]. Given a sequence p1, p2, ..., pn, one is able to restore a tree: There must be exactly one index r that pr = r. A vertex r is a root of the tree. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi. A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
In the first line print the minimum number of elements to change, in order to get a valid sequence. In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
The first line of the input contains an integer n (2 ≀ n ≀ 200 000)Β β€” the number of vertices in the tree. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n).
standard output
standard input
Python 3
Python
1,700
train_052.jsonl
3256dd548816d8bfcd345fbf0ad24970
256 megabytes
["4\n2 3 3 4", "5\n3 2 2 5 3", "8\n2 3 5 4 1 6 6 7"]
PASSED
n=int(input()) a=list(map(int,input().split())) par=[] for i in range(n): if a[i]==i+1: par.append(i) v=[False for i in range(n)] for i in par: v[i]=True ccl=[] for i in range(n): if v[i]:continue s=[i] v[i]=True p=set(s) t=True while s and t: x=s.pop() j=a[x]-1 if j in p: ccl.append(j) t=False else: s.append(j) p.add(j) if v[j]:t=False else:v[j]=True if len(par)==0: print(len(ccl)) c=ccl[0] a[c]=c+1 for i in range(1,len(ccl)): a[ccl[i]]=c+1 print(*a) else: print(len(ccl)+len(par)-1) c=par[0] for i in range(1,len(par)): a[par[i]]=c+1 for i in range(len(ccl)): a[ccl[i]]=c+1 print(*a)
1468933500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["YES\n1", "YES\n0", "YES\n1"]
da38d1a63152e0a354b04936e9511969
NoteIn the first example you can simply make one move to obtain sequence [0, 2] with .In the second example the gcd of the sequence is already greater than 1.
Mike has a sequence A = [a1, a2, ..., an] of length n. He considers the sequence B = [b1, b2, ..., bn] beautiful if the gcd of all its elements is bigger than 1, i.e. . Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i (1 ≀ i &lt; n), delete numbers ai, ai + 1 and put numbers ai - ai + 1, ai + ai + 1 in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence A beautiful if it's possible, or tell him that it is impossible to do so. is the biggest non-negative number d such that d divides bi for every i (1 ≀ i ≀ n).
Output on the first line "YES" (without quotes) if it is possible to make sequence A beautiful by performing operations described above, and "NO" (without quotes) otherwise. If the answer was "YES", output the minimal number of moves needed to make sequence A beautiful.
The first line contains a single integer n (2 ≀ n ≀ 100 000) β€” length of sequence A. The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” elements of sequence A.
standard output
standard input
Python 3
Python
1,700
train_038.jsonl
0ee0ebb1fa960ef16bdb68e80a570993
256 megabytes
["2\n1 1", "3\n6 2 4", "2\n1 3"]
PASSED
def main(): from math import gcd input() aa = list(map(int, input().split())) g = r = t = 0 while aa and g != 1: a = aa.pop() if t: r += 2 - (a & 1) t = 0 else: t = (a & 1) * 2 g = gcd(a, g) for a in reversed(aa): if t: r += 2 - (a & 1) t = 0 else: t = (a & 1) * 2 print("YES", (r + t) * (g < 2), sep='\n') if __name__ == '__main__': main()
1492785300
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
0.5 seconds
["29"]
09276406e16b46fbefd6f8c9650472f0
null
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Output one integer β€” the number of different variants of group composition.
The only line of the input contains one integer n (7 ≀ n ≀ 777) β€” the number of potential employees that sent resumes.
standard output
standard input
PyPy 2
Python
1,300
train_001.jsonl
d028cdefcd5a2b230d78d25a0bf96b70
64 megabytes
["7"]
PASSED
W = int(raw_input()) def ncr(n, r): res = 1 for i in xrange(r + 1, n + 1): res *= i for i in xrange(1, n - r + 1): res /= i return res print ncr(W, 5) + ncr(W, 6) + ncr(W, 7)
1455807600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nYES\nNO\nNO\nYES\nYES"]
b40059fe9cbdb0cc3b64c3e463900849
NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.
You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.
For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) β€” the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) β€” the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.
standard output
standard input
PyPy 2
Python
1,000
train_002.jsonl
36d24ed41f3c24eaaba82e58395c7201
256 megabytes
["6\n4\n1024 512 64 512\n1\n2048\n3\n64 512 2\n2\n4096 4\n7\n2048 2 2048 2048 2048 2048 2048\n2\n2048 4096"]
PASSED
def count(arr,cnt): for i in range(0,len(arr)): if arr[i] in cnt.keys(): cnt[arr[i]] = cnt[arr[i]] + 1 else: cnt[arr[i]] = 1 def yn2048(arr,t): f = {} count(arr,f) keys = f.keys() for i in range(0,11): k = 0 keys = f.keys() if pow(2,i) in keys: k = f[pow(2,i)]/2 if pow(2,i+1) in keys: f[pow(2,i+1)] = f[pow(2,i+1)] + k elif k > 0: f[pow(2,i+1)] = k if 2048 in f: t.append("YES") else: t.append("No") def main(): t = [] q = int(raw_input()) for i in range(q): f = raw_input() arr = list(map(int,raw_input().split(" "))) yn2048(arr,t) for i in t: print (i) main()
1568903700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES", "NO", "NO"]
c404761a9562ff6034010a553d944324
NoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares $$$(2, 3)$$$ and $$$(3, 2)$$$. Note that the direct route through $$$(2, 2)$$$ goes through check. In the second case, the queen watches the fourth rank, and the king has no means of crossing it. In the third case, the queen watches the third file.
Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \times n$$$. Alice has a single piece leftΒ β€” a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himselfΒ β€” he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.
Print "YES" (without quotes) if Bob can get from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check, otherwise print "NO". You can print each letter in any case (upper or lower).
The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 1000$$$)Β β€” the dimensions of the chessboard. The second line contains two integers $$$a_x$$$ and $$$a_y$$$ ($$$1 \leq a_x, a_y \leq n$$$)Β β€” the coordinates of Alice's queen. The third line contains two integers $$$b_x$$$ and $$$b_y$$$ ($$$1 \leq b_x, b_y \leq n$$$)Β β€” the coordinates of Bob's king. The fourth line contains two integers $$$c_x$$$ and $$$c_y$$$ ($$$1 \leq c_x, c_y \leq n$$$)Β β€” the coordinates of the location that Bob wants to get to. It is guaranteed that Bob's king is currently not in check and the target location is not in check either. Furthermore, the king is not located on the same square as the queen (i.e. $$$a_x \neq b_x$$$ or $$$a_y \neq b_y$$$), and the target does coincide neither with the queen's position (i.e. $$$c_x \neq a_x$$$ or $$$c_y \neq a_y$$$) nor with the king's position (i.e. $$$c_x \neq b_x$$$ or $$$c_y \neq b_y$$$).
standard output
standard input
Python 3
Python
1,000
train_004.jsonl
930275a7e66931f0bb3f30ee96e66a33
256 megabytes
["8\n4 4\n1 3\n3 1", "8\n4 4\n2 3\n1 6", "8\n3 5\n1 2\n6 1"]
PASSED
n = int(input()) a_x, a_y = map(int, input().split()) b_x, b_y = map(int, input().split()) c_x, c_y = map(int, input().split()) if b_x < a_x < c_x or b_x > a_x > c_x or b_y < a_y < c_y or b_y > a_y > c_y: print('NO') else: print('YES')
1538931900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["YES\nR 0\nL -3\nR 5\nL 6", "NO"]
1c03ad9c0aacfbc9e40edc018a2526d3
null
There are $$$n$$$ cars on a coordinate axis $$$OX$$$. Each car is located at an integer point initially and no two cars are located at the same point. Also, each car is oriented either left or right, and they can move at any constant positive speed in that direction at any moment.More formally, we can describe the $$$i$$$-th car with a letter and an integer: its orientation $$$ori_i$$$ and its location $$$x_i$$$. If $$$ori_i = L$$$, then $$$x_i$$$ is decreasing at a constant rate with respect to time. Similarly, if $$$ori_i = R$$$, then $$$x_i$$$ is increasing at a constant rate with respect to time. We call two cars irrelevant if they never end up in the same point regardless of their speed. In other words, they won't share the same coordinate at any moment.We call two cars destined if they always end up in the same point regardless of their speed. In other words, they must share the same coordinate at some moment.Unfortunately, we lost all information about our cars, but we do remember $$$m$$$ relationships. There are two types of relationships:$$$1$$$ $$$i$$$ $$$j$$$ β€”$$$i$$$-th car and $$$j$$$-th car are irrelevant.$$$2$$$ $$$i$$$ $$$j$$$ β€”$$$i$$$-th car and $$$j$$$-th car are destined.Restore the orientations and the locations of the cars satisfying the relationships, or report that it is impossible. If there are multiple solutions, you can output any.Note that if two cars share the same coordinate, they will intersect, but at the same moment they will continue their movement in their directions.
In the first line, print either "YES" or "NO" (in any case), whether it is possible to restore the orientations and the locations of the cars satisfying the relationships. If the answer is "YES", print $$$n$$$ lines each containing a symbol and an integer: $$$ori_i$$$ and $$$x_i$$$ $$$(ori_i \in \{L, R\}; -10^9 \leq x_i \leq 10^9)$$$ β€” representing the information of the $$$i$$$-th car. If the orientation is left, then $$$ori_i$$$ = $$$L$$$. Otherwise $$$ori_i$$$ = $$$R$$$. $$$x_i$$$ is the where the $$$i$$$-th car is located. Note that all $$$x_i$$$ should be distinct. We can prove that if there exists a solution, then there must be a solution satisfying the constraints on $$$x_i$$$.
The first line contains two integers, $$$n$$$ and $$$m$$$ $$$(2 \leq n \leq 2 \cdot 10^5; 1 \leq m \leq min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$ — the number of cars and the number of restrictions respectively. Each of the next $$$m$$$ lines contains three integers, $$$type$$$, $$$i$$$, and $$$j$$$ $$$(1 \leq type \leq 2; 1 \leq i,j \leq n; i≠j)$$$. If $$$type$$$ = $$$1$$$, $$$i$$$-th car and $$$j$$$-th car are irrelevant. Otherwise, $$$i$$$-th car and $$$j$$$-th car are destined. It is guaranteed that for each pair of cars, there are at most $$$1$$$ relationship between.
standard output
standard input
PyPy 3-64
Python
2,200
train_108.jsonl
b2ff51d67c582fc97af63031477e2ef2
512 megabytes
["4 4\n1 1 2\n1 2 3\n2 3 4\n2 4 1", "3 3\n1 1 2\n1 2 3\n1 1 3"]
PASSED
def solve(): n, m = map(int, input().split()) relationships = [] adj = [[] for _ in range(n)] for _ in range(m): t, u, v = map(int, input().split()) u -= 1 v -= 1 relationships.append((t, u, v)) adj[u].append(v) adj[v].append(u) orientation = [-1] * n for i in range(n): if orientation[i] == -1: # dfs orientation[i] = 0 stack = [i] while len(stack) > 0: u = stack.pop() for v in adj[u]: if orientation[v] == orientation[u]: print('NO') return if orientation[v] == -1: orientation[v] = 1 - orientation[u] stack.append(v) # directed graph indeg = [0] * n adj = [[] for _ in range(n)] for t, u, v in relationships: # if u is to left, t == 1, u < v, t == 2 u > v if orientation[u] == 1 and t == 1 or orientation[u] == 0 and t == 2: u, v = v, u adj[u].append(v) indeg[v] += 1 # toposort i = 0 ans = [-1] * n queue = [u for u in range(n) if indeg[u] == 0] while i < len(queue): u = queue[i] ans[u] = i for v in adj[u]: indeg[v] -= 1 if indeg[v] == 0: queue.append(v) i += 1 if i != n: print('NO') return print('YES') lr = 'LR' for i in range(n): print(lr[orientation[i]], ans[i]) if __name__ == '__main__': solve()
1645367700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nNO\nYES"]
b44d59eded2cb3a65686dc7fd07d21b7
NoteIn the second test case the table is not elegant, because the red and the purple subrectangles are nice and intersect. In the fourth test case the table is not elegant, because the red and the purple subrectangles are nice and intersect.
Madoka's father just reached $$$1$$$ million subscribers on Mathub! So the website decided to send him a personalized awardΒ β€” The Mathhub's Bit Button! The Bit Button is a rectangular table with $$$n$$$ rows and $$$m$$$ columns with $$$0$$$ or $$$1$$$ in each cell. After exploring the table Madoka found out that: A subrectangle $$$A$$$ is contained in a subrectangle $$$B$$$ if there's no cell contained in $$$A$$$ but not contained in $$$B$$$. Two subrectangles intersect if there is a cell contained in both of them. A subrectangle is called black if there's no cell with value $$$0$$$ inside it. A subrectangle is called nice if it's black and it's not contained in another black subrectangle. The table is called elegant if there are no two nice intersecting subrectangles.For example, in the first illustration the red subrectangle is nice, but in the second one it's not, because it's contained in the purple subrectangle. Help Madoka to determine whether the table is elegant.
For each test case print "YES" if its table is elegant or print "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$)Β β€” the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n, m$$$ ($$$1 \le n, m \le 100$$$). The next $$$n$$$ lines contain strings of length $$$m$$$ consisting of zeros and onesΒ β€” the description of the table. It is guaranteed that the sum of the values of $$$n$$$ and the sum of the values of $$$m$$$ for all test cases do not exceed $$$777$$$.
standard output
standard input
Python 3
Python
1,200
train_096.jsonl
fe66e8d0108f373ef8c039a1feb8f5f8
256 megabytes
["5\n3 3\n100\n011\n011\n3 3\n110\n111\n110\n1 5\n01111\n4 5\n11111\n01010\n01000\n01000\n3 2\n11\n00\n11"]
PASSED
#!/usr/bin/env python # coding: utf-8 # In[13]: import sys # input = sys.stdin.readline # In[2]: # input = sys.stdin.readline # def inp(): # return(int(input())) # def inlt(): # return(list(map(int,input().split()))) # def insr(): # s = input() # # return(list(s[:len(s) - 1])) # return(list(s[:len(s)])) # def invr(): # return(map(int,input().split())) # In[3]: # #Problem 1 https://codeforces.com/contest/1647/problem/A # def findLargest(inputNumber): # if inputNumber%3==0: # return int('21'*int(inputNumber/3)) # if inputNumber%3==1: # return int('1'+(int((inputNumber-1)/3)*'21')) # if inputNumber%3==2: # return int('2'+(int((inputNumber-2)/3)*'12')) # length=inp() # for k in range(length): # myNumber=inp() # print(findLargest(myNumber)) # In[17]: def checkArray(array, x, y): #loop through columns by two for k in range(x-1): first=array[k] second=array[k+1] #check two columns: for i in range(y-1): a,b,c,d=first[i],first[i+1], second[i], second[i+1] if int(a)+int(b)+int(c)+int(d)==3: print('NO') return print('YES') # In[5]: # length=inp() # for k in range(length): # firstList=inlt() # x,y=firstList[0], firstList[1] # if (x==1 or y==1): # print('YES') # else: # myArray=[] # for row in range(x): # myArray.append(insr()) # checkArray(myArray, x, y) # In[23]: length=int(input()) for k in range(length): firstInputList=list(map(int, input().split())) x,y=firstInputList[0], firstInputList[1] myArray=[] for row in range(x): s = input() new=(list(s[:len(s)])) myArray.append(new) if(x==1 or y==1): print('YES') else: checkArray(myArray, x, y) # In[ ]: # In[ ]: # In[ ]:
1647009300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["1.500000\n2.250000\n3.250000", "2.500000", "1.000000"]
6cef2d464febcee854ee5a7f78d7ba4a
NoteConsider the second test case. If Allen goes first, he will set $$$x_1 \to 1$$$, so the final value will be $$$3$$$. If Bessie goes first, then she will set $$$x_1 \to 0$$$ so the final value will be $$$2$$$. Thus the answer is $$$2.5$$$.In the third test case, the game value will always be $$$1$$$ regardless of Allen and Bessie's play.
Allen and Bessie are playing a simple number game. They both know a function $$$f: \{0, 1\}^n \to \mathbb{R}$$$, i.Β e. the function takes $$$n$$$ binary arguments and returns a real value. At the start of the game, the variables $$$x_1, x_2, \dots, x_n$$$ are all set to $$$-1$$$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $$$i$$$ such that $$$x_i = -1$$$ and either setting $$$x_i \to 0$$$ or $$$x_i \to 1$$$.After $$$n$$$ rounds all variables are set, and the game value resolves to $$$f(x_1, x_2, \dots, x_n)$$$. Allen wants to maximize the game value, and Bessie wants to minimize it.Your goal is to help Allen and Bessie find the expected game value! They will play $$$r+1$$$ times though, so between each game, exactly one value of $$$f$$$ changes. In other words, between rounds $$$i$$$ and $$$i+1$$$ for $$$1 \le i \le r$$$, $$$f(z_1, \dots, z_n) \to g_i$$$ for some $$$(z_1, \dots, z_n) \in \{0, 1\}^n$$$. You are to find the expected game value in the beginning and after each change.
Print $$$r+1$$$ lines, the $$$i$$$-th of which denotes the value of the game $$$f$$$ during the $$$i$$$-th round. Your answer must have absolute or relative error within $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
The first line contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n \le 18$$$, $$$0 \le r \le 2^{18}$$$). The next line contains $$$2^n$$$ integers $$$c_0, c_1, \dots, c_{2^n-1}$$$ ($$$0 \le c_i \le 10^9$$$), denoting the initial values of $$$f$$$. More specifically, $$$f(x_0, x_1, \dots, x_{n-1}) = c_x$$$, if $$$x = \overline{x_{n-1} \ldots x_0}$$$ in binary. Each of the next $$$r$$$ lines contains two integers $$$z$$$ and $$$g$$$ ($$$0 \le z \le 2^n - 1$$$, $$$0 \le g \le 10^9$$$). If $$$z = \overline{z_{n-1} \dots z_0}$$$ in binary, then this means to set $$$f(z_0, \dots, z_{n-1}) \to g$$$.
standard output
standard input
Python 3
Python
2,500
train_017.jsonl
e7a16a0243e6c1d57c25db2049f49d44
256 megabytes
["2 2\n0 1 2 3\n2 5\n0 4", "1 0\n2 3", "2 0\n1 1 1 1"]
PASSED
R = lambda:list(map(int,input().split())) sum1 = 0 p1 = 1 a = [0]*263000 b = a n,r = R() p1 = 2**n a = R() sum1 = sum(a) p2 = sum1 / p1 for i in range(r): z,g=R() sum1 = sum1 - a[z] + g a[z] = g b[i] = sum1/p1 print(p2) for i in range(r): print(b[i])
1529858100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["4\n0 1 2 5 \n6\n0 1 2 3 5 11 \n2\n0 1 \n3\n0 1 3"]
1fea14a5c21bf301981656cbe015864d
null
On the well-known testing system MathForces, a draw of $$$n$$$ rating units is arranged. The rating will be distributed according to the following algorithm: if $$$k$$$ participants take part in this event, then the $$$n$$$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remainΒ β€” it is not given to any of the participants.For example, if $$$n = 5$$$ and $$$k = 3$$$, then each participant will recieve an $$$1$$$ rating unit, and also $$$2$$$ rating units will remain unused. If $$$n = 5$$$, and $$$k = 6$$$, then none of the participants will increase their rating.Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.For example, if $$$n=5$$$, then the answer is equal to the sequence $$$0, 1, 2, 5$$$. Each of the sequence values (and only them) can be obtained as $$$\lfloor n/k \rfloor$$$ for some positive integer $$$k$$$ (where $$$\lfloor x \rfloor$$$ is the value of $$$x$$$ rounded down): $$$0 = \lfloor 5/7 \rfloor$$$, $$$1 = \lfloor 5/5 \rfloor$$$, $$$2 = \lfloor 5/2 \rfloor$$$, $$$5 = \lfloor 5/1 \rfloor$$$.Write a program that, for a given $$$n$$$, finds a sequence of all possible rating increments.
Output the answers for each of $$$t$$$ test cases. Each answer should be contained in two lines. In the first line print a single integer $$$m$$$Β β€” the number of different rating increment values that Vasya can get. In the following line print $$$m$$$ integers in ascending orderΒ β€” the values of possible rating increments.
The first line contains integer number $$$t$$$ ($$$1 \le t \le 10$$$)Β β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each line contains an integer $$$n$$$ ($$$1 \le n \le 10^9$$$)Β β€” the total number of the rating units being drawn.
standard output
standard input
Python 3
Python
1,400
train_003.jsonl
d4684ef67e3c3137b08812df5cfb7c4a
256 megabytes
["4\n5\n11\n1\n3"]
PASSED
from math import sqrt from sys import stdin, stdout for i in range(int(input())): n = int(input()) s,j,l = set([0,1]), 2, sqrt(n) while j <= l: s.add(j) s.add(int(n//j)) j += 1 s.add(n) a,l = sorted(s), len(s) stdout.write('%d\n' % l) for j in range(l): stdout.write('%d ' % a[j]) stdout.write('\n')
1575038100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["14\n16\n46", "999999999999999998\n44500000000", "2\n17\n46\n97"]
6264405c66b2690ada9f8cc6cff55f0b
NoteIn the first sample case:On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14Β·1 = 16. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16Β·2 = 36. Then, ZS pressed the '' button, levelling up and changing the number into .After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46Β·3 = 144. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4.Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10Β·3 = 36, and when the '' button is pressed, the number becomes and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution.In the second sample case:On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998Β·1 = 1018. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 109 + 44500000000Β·2 = 9Β·1010. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3.
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.When ZS the Coder is at level k, he can : Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. Press the '' button. Let the number on the screen be x. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.ZS the Coder needs your help in beating the gameΒ β€” he wants to reach level n + 1. In other words, he needs to press the '' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses.
Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '' button at level i. Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.
The first and only line of the input contains a single integer n (1 ≀ n ≀ 100 000), denoting that ZS the Coder wants to reach level n + 1.
standard output
standard input
Python 3
Python
1,600
train_000.jsonl
c110c795a3144221aa279294612eb2aa
256 megabytes
["3", "2", "4"]
PASSED
def main(): n=int(input()) print(2) for i in range(2,n+1): print(i*(i+1)**2-(i-1)) main() ''' 1=>2: 2->4 [2] 2=>3: 2->36 [17] 3=>4: 6->144 [46] 4=>5: 12->400 [97] 5=>6: 20->900 [176] '''
1474119900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["0\n987\n914"]
b57066317ae2f2280d7351ff12e0c959
NoteIn the second test case, in one of the optimal answers after all operations $$$a = [2, 6, 4, 6]$$$, $$$b = [3, 7, 6, 1]$$$.The cost of the array $$$a$$$ equals to $$$(2 + 6)^2 + (2 + 4)^2 + (2 + 6)^2 + (6 + 4)^2 + (6 + 6)^2 + (4 + 6)^2 = 508$$$.The cost of the array $$$b$$$ equals to $$$(3 + 7)^2 + (3 + 6)^2 + (3 + 1)^2 + (7 + 6)^2 + (7 + 1)^2 + (6 + 1)^2 = 479$$$.The total cost of two arrays equals to $$$508 + 479 = 987$$$.
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.You can perform the following operation any number of times (possibly zero): select an index $$$i$$$ ($$$1 \leq i \leq n$$$) and swap $$$a_i$$$ and $$$b_i$$$.Let's define the cost of the array $$$a$$$ as $$$\sum_{i=1}^{n} \sum_{j=i + 1}^{n} (a_i + a_j)^2$$$. Similarly, the cost of the array $$$b$$$ is $$$\sum_{i=1}^{n} \sum_{j=i + 1}^{n} (b_i + b_j)^2$$$.Your task is to minimize the total cost of two arrays.
For each test case, print the minimum possible total cost.
Each test case consists of several test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 40$$$)Β β€” the number of test cases. The following is a description of the input data sets. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$)Β β€” the length of both arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$)Β β€” elements of the first array. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$)Β β€” elements of the second array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_090.jsonl
f7c12418e4550cdf0868782ba9427a74
256 megabytes
["3\n1\n3\n6\n4\n3 6 6 6\n2 7 4 1\n4\n6 7 2 4\n2 5 3 5"]
PASSED
# import sys, os # if not os.environ.get("ONLINE_JUDGE"): # sys.stdin = open('in.txt', 'r') # sys.stdout = open('out.txt', 'w') import sys input = lambda: sys.stdin.readline().rstrip("\r\n") for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) if n == 1: print(0) else: cost = 0 s = 0 for i in range(n): cost += a[i]**2 + b[i]**2 s += a[i] + b[i] wt = [abs(a[i]-b[i]) for i in range(n)] capacity = sum(wt) dp = [[False for i in range(capacity + 1)] for i in range(n+1)] dp[0][0] = True for i in range(n+1): for j in range(capacity + 1): if j == 0: dp[i][j] = True else: if dp[i-1][j] or dp[i-1][j-wt[i-1]]: dp[i][j] = True pos = [] min_j = 0 for i in range(n): min_j += min(a[i], b[i]) for j in range(capacity + 1): if dp[n][j]: s1 = j + min_j pos.append(s1**2 + (s - s1)**2) print(min(pos) + (n-2)*cost)
1644676500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 сСкунды
["LUURRDDL", "UULLDDDDDRRRRRUULULL"]
dea56c6d6536e7efe80d39ebc6b819a8
ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΌ тСстовом ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ для ΠΎΠ±Ρ…ΠΎΠ΄Π° ΠΏΠΎ часовой стрСлкС ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΡŒ посСщСнных Ρ€ΠΎΠ±ΠΎΡ‚ΠΎΠΌ ΠΊΠ»Π΅Ρ‚ΠΎΠΊ выглядит ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ: ΠΊΠ»Π΅Ρ‚ΠΊΠ° (3, 2); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (3, 1); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (2, 1); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (1, 1); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (1, 2); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (1, 3); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (2, 3); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (3, 3); ΠΊΠ»Π΅Ρ‚ΠΊΠ° (3, 2).
Π’Π°ΠΌ Π·Π°Π΄Π°Π½ΠΎ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΎΠ΅ ΠΊΠ»Π΅Ρ‚Ρ‡Π°Ρ‚ΠΎΠ΅ ΠΏΠΎΠ»Π΅, состоящСС ΠΈΠ· n строк ΠΈ m столбцов. ПолС содСрТит Ρ†ΠΈΠΊΠ» ΠΈΠ· символов Β«*Β», Ρ‚Π°ΠΊΠΎΠΉ Ρ‡Ρ‚ΠΎ: Ρ†ΠΈΠΊΠ» ΠΌΠΎΠΆΠ½ΠΎ ΠΎΠ±ΠΎΠΉΡ‚ΠΈ, посСтив ΠΊΠ°ΠΆΠ΄ΡƒΡŽ Π΅Π³ΠΎ ΠΊΠ»Π΅Ρ‚ΠΊΡƒ Ρ€ΠΎΠ²Π½ΠΎ ΠΎΠ΄ΠΈΠ½ Ρ€Π°Π·, ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Ρ‰Π°ΡΡΡŒ ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ Ρ€Π°Π· Π²Π²Π΅Ρ€Ρ…/Π²Π½ΠΈΠ·/Π²ΠΏΡ€Π°Π²ΠΎ/Π²Π»Π΅Π²ΠΎ Π½Π° ΠΎΠ΄Π½Ρƒ ΠΊΠ»Π΅Ρ‚ΠΊΡƒ; Ρ†ΠΈΠΊΠ» Π½Π΅ содСрТит самопСрСсСчСний ΠΈ самокасаний, Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ Π΄Π²Π΅ ΠΊΠ»Π΅Ρ‚ΠΊΠΈ Ρ†ΠΈΠΊΠ»Π° ΡΠΎΡΠ΅Π΄ΡΡ‚Π²ΡƒΡŽΡ‚ ΠΏΠΎ сторонС Ρ‚ΠΎΠ³Π΄Π° ΠΈ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ‚ΠΎΠ³Π΄Π°, ΠΊΠΎΠ³Π΄Π° ΠΎΠ½ΠΈ сосСдниС ΠΏΡ€ΠΈ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Ρ‰Π΅Π½ΠΈΠΈ вдоль Ρ†ΠΈΠΊΠ»Π° (самокасаниС ΠΏΠΎ ΡƒΠ³Π»Ρƒ Ρ‚ΠΎΠΆΠ΅ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½ΠΎ). НиТС ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½Ρ‹ нСсколько ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠ² допустимых Ρ†ΠΈΠΊΠ»ΠΎΠ²: ВсС ΠΊΠ»Π΅Ρ‚ΠΊΠΈ поля, ΠΎΡ‚Π»ΠΈΡ‡Π½Ρ‹Π΅ ΠΎΡ‚ Ρ†ΠΈΠΊΠ»Π°, содСрТат символ Β«.Β». Π¦ΠΈΠΊΠ» Π½Π° ΠΏΠΎΠ»Π΅ Ρ€ΠΎΠ²Π½ΠΎ ΠΎΠ΄ΠΈΠ½. ΠŸΠΎΡΠ΅Ρ‰Π°Ρ‚ΡŒ ΠΊΠ»Π΅Ρ‚ΠΊΠΈ, ΠΎΡ‚Π»ΠΈΡ‡Π½Ρ‹Π΅ ΠΎΡ‚ Ρ†ΠΈΠΊΠ»Π°, Π ΠΎΠ±ΠΎΡ‚Ρƒ нСльзя.Π’ ΠΎΠ΄Π½ΠΎΠΉ ΠΈΠ· ΠΊΠ»Π΅Ρ‚ΠΎΠΊ Ρ†ΠΈΠΊΠ»Π° находится Π ΠΎΠ±ΠΎΡ‚. Π­Ρ‚Π° ΠΊΠ»Π΅Ρ‚ΠΊΠ° ΠΏΠΎΠΌΠ΅Ρ‡Π΅Π½Π° символом Β«SΒ». НайдитС ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΡŒ ΠΊΠΎΠΌΠ°Π½Π΄ для Π ΠΎΠ±ΠΎΡ‚Π°, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΎΠ±ΠΎΠΉΡ‚ΠΈ Ρ†ΠΈΠΊΠ». КаТдая ΠΈΠ· Ρ‡Π΅Ρ‚Ρ‹Ρ€Ρ‘Ρ… Π²ΠΎΠ·ΠΌΠΎΠΆΠ½Ρ‹Ρ… ΠΊΠΎΠΌΠ°Π½Π΄ кодируСтся Π±ΡƒΠΊΠ²ΠΎΠΉ ΠΈ ΠΎΠ±ΠΎΠ·Π½Π°Ρ‡Π°Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Ρ‰Π΅Π½ΠΈΠ΅ Π ΠΎΠ±ΠΎΡ‚Π° Π½Π° ΠΎΠ΄Π½Ρƒ ΠΊΠ»Π΅Ρ‚ΠΊΡƒ: Β«U» — ΡΠ΄Π²ΠΈΠ½ΡƒΡ‚ΡŒΡΡ Π½Π° ΠΊΠ»Π΅Ρ‚ΠΊΡƒ Π²Π²Π΅Ρ€Ρ…, Β«R» — ΡΠ΄Π²ΠΈΠ½ΡƒΡ‚ΡŒΡΡ Π½Π° ΠΊΠ»Π΅Ρ‚ΠΊΡƒ Π²ΠΏΡ€Π°Π²ΠΎ, Β«D» — ΡΠ΄Π²ΠΈΠ½ΡƒΡ‚ΡŒΡΡ Π½Π° ΠΊΠ»Π΅Ρ‚ΠΊΡƒ Π²Π½ΠΈΠ·, Β«L» — ΡΠ΄Π²ΠΈΠ½ΡƒΡ‚ΡŒΡΡ Π½Π° ΠΊΠ»Π΅Ρ‚ΠΊΡƒ Π²Π»Π΅Π²ΠΎ. Π ΠΎΠ±ΠΎΡ‚ Π΄ΠΎΠ»ΠΆΠ΅Π½ ΠΎΠ±ΠΎΠΉΡ‚ΠΈ Ρ†ΠΈΠΊΠ», ΠΏΠΎΠ±Ρ‹Π²Π°Π² Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΉ Π΅Π³ΠΎ ΠΊΠ»Π΅Ρ‚ΠΊΠ΅ Ρ€ΠΎΠ²Π½ΠΎ ΠΎΠ΄ΠΈΠ½ Ρ€Π°Π· (ΠΊΡ€ΠΎΠΌΠ΅ стартовой Ρ‚ΠΎΡ‡ΠΊΠΈΒ β€” Π² Π½Π΅ΠΉ ΠΎΠ½ Π½Π°Ρ‡ΠΈΠ½Π°Π΅Ρ‚ ΠΈ Π·Π°ΠΊΠ°Π½Ρ‡ΠΈΠ²Π°Π΅Ρ‚ свой ΠΏΡƒΡ‚ΡŒ).НайдитС ΠΈΡΠΊΠΎΠΌΡƒΡŽ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΡŒ ΠΊΠΎΠΌΠ°Π½Π΄, допускаСтся любоС Π½Π°ΠΏΡ€Π°Π²Π»Π΅Π½ΠΈΠ΅ ΠΎΠ±Ρ…ΠΎΠ΄Π° Ρ†ΠΈΠΊΠ»Π°.
Π’ ΠΏΠ΅Ρ€Π²ΡƒΡŽ строку Π²Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ ΠΈΡΠΊΠΎΠΌΡƒΡŽ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΡŒ ΠΊΠΎΠΌΠ°Π½Π΄ для Π ΠΎΠ±ΠΎΡ‚Π°. НаправлСниС ΠΎΠ±Ρ…ΠΎΠ΄Π° Ρ†ΠΈΠΊΠ»Π° Π ΠΎΠ±ΠΎΡ‚ΠΎΠΌ ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ‹Ρ‚ΡŒ Π»ΡŽΠ±Ρ‹ΠΌ.
Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… записаны Π΄Π²Π° Ρ†Π΅Π»Ρ‹Ρ… числа n ΠΈ m (3 ≀ n, m ≀ 100) β€” количСство строк ΠΈ столбцов ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΎΠ³ΠΎ ΠΊΠ»Π΅Ρ‚Ρ‡Π°Ρ‚ΠΎΠ³ΠΎ поля соотвСтствСнно. Π’ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΡ… n строках записаны ΠΏΠΎ m символов, ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ ΠΈΠ· ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… β€” Β«.Β», Β«*Β» ΠΈΠ»ΠΈ Β«SΒ». ГарантируСтся, Ρ‡Ρ‚ΠΎ ΠΎΡ‚Π»ΠΈΡ‡Π½Ρ‹Π΅ ΠΎΡ‚ Β«.Β» символы ΠΎΠ±Ρ€Π°Π·ΡƒΡŽΡ‚ Ρ†ΠΈΠΊΠ» Π±Π΅Π· самопСрСсСчСний ΠΈ самокасаний. Π’Π°ΠΊΠΆΠ΅ гарантируСтся, Ρ‡Ρ‚ΠΎ Π½Π° ΠΏΠΎΠ»Π΅ Ρ€ΠΎΠ²Π½ΠΎ ΠΎΠ΄Π½Π° ΠΊΠ»Π΅Ρ‚ΠΊΠ° содСрТит Β«SΒ» ΠΈ Ρ‡Ρ‚ΠΎ ΠΎΠ½Π° ΠΏΡ€ΠΈΠ½Π°Π΄Π»Π΅ΠΆΠΈΡ‚ Ρ†ΠΈΠΊΠ»Ρƒ. Π ΠΎΠ±ΠΎΡ‚ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΡΠ΅Ρ‰Π°Ρ‚ΡŒ ΠΊΠ»Π΅Ρ‚ΠΊΠΈ, ΠΏΠΎΠΌΠ΅Ρ‡Π΅Π½Π½Ρ‹Π΅ символом Β«.Β».
стандартный Π²Ρ‹Π²ΠΎΠ΄
стандартный Π²Π²ΠΎΠ΄
Python 3
Python
1,100
train_061.jsonl
874c5e87446705ac6040ac81b3df4161
256 ΠΌΠ΅Π³Π°Π±Π°ΠΉΡ‚
["3 3\n***\n*.*\n*S*", "6 7\n.***...\n.*.*...\n.*.S**.\n.*...**\n.*....*\n.******"]
PASSED
def read_ints(): return [int(x) for x in input(' ').split()] def main(): n, m = read_ints() field = [] x, y = None, None for i in range(n): line = input() if 'S' in line: x, y = i, line.find('S') field.append(list(line)) field[x][y] = '*' flag = False curr_x, curr_y = x, y delta = [(-1, 0, 'U'), (+1, 0, 'D'), (0, -1, 'L'), (0, +1, 'R')] par_x, par_y = -1, -1 while True: if flag: field[curr_x][curr_y] = 'U' flag = True for dx, dy, label in delta: next_x, next_y = curr_x + dx, curr_y + dy if not 0 <= next_x < n: continue if not 0 <= next_y < m: continue if par_x == next_x and par_y == next_y: continue if field[next_x][next_y] == '*': print(label, end='', flush=True) par_x, par_y = curr_x, curr_y curr_x, curr_y = next_x, next_y break if x == curr_x and y == curr_y: break if __name__ == '__main__': main()
1458745200
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["10\n5"]
dc35bdf56bb0ac341895e543b001b801
null
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≀ ui ≀ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURLΒ», then the answer is 10.
Print q numbers, i-th number must be the answer to the i-th query.
The first line contains two integer numbers n and q (1 ≀ n ≀ 1018, q β‰₯ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≀ ui ≀ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≀ i ≀ q) doesn't exceed 105.
standard output
standard input
PyPy 2
Python
1,900
train_002.jsonl
c4083e607e85748bbdd248c531dda178
256 megabytes
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
PASSED
n, q = map(int, raw_input().split()) queries = [] for i in range(q): u = int(raw_input()) s = raw_input() queries.append((u, s)) def coords(n, u): level = 0 while (u & 1) == 0: u >>= 1 level += 1 return level, (u - 1) / 2 def uncoords(n, level, idx): return (1 << level) * (2 * idx + 1) def get_up(n, u): level, idx = coords(n, u) # already at root if u == (n + 1) / 2: return u new_level = level + 1 new_idx = idx / 2 return uncoords(n, new_level, new_idx) def get_left(n, u): level, idx = coords(n, u) # already at leaf if level == 0: return u new_level = level - 1 new_idx = idx * 2 return uncoords(n, new_level, new_idx) def get_right(n, u): level, idx = coords(n, u) # already at leaf if level == 0: return u new_level = level - 1 new_idx = idx * 2 + 1 return uncoords(n, new_level, new_idx) action = {'U': get_up, 'L': get_left, 'R': get_right} for u, s in queries: cur = u for c in s: cur = action[c](n, cur) print cur
1490625300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["0001\n1111\n1"]
f9cf1a6971a7003078b63195198e5a51
NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) β€” the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_109.jsonl
e82bc3b8b55a1136dddd5fa00983dc05
256 megabytes
["3\n4\n1 2 3 4\n1 2 3 4\n4\n11 12 20 21\n44 22 11 30\n1\n1000000000\n1000000000"]
PASSED
import os import sys from io import BytesIO, IOBase ## PYRIVAL BOOTSTRAP # https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py # This decorator allows for recursion without actually doing recursion from types import GeneratorType ## @bootstrap, yield when getting and returning value in recursive functions def main(): @bootstrap def dfs(value): for v in beaten_by[value]: if iptw[v] == '1': continue else: iptw[v] = '1' yield dfs(v) yield for _ in range(iip()): n = iip() a = liip() b = liip() beaten_by = [set() for _ in range(n)] li = [] for i in range(n): li.append((a[i], b[i], i)) starts = set() li.sort(key=lambda x: -x[0]) starts.add(li[0][2]) for i in range(n - 1): beaten_by[li[i + 1][2]].add(li[i][2]) li.sort(key=lambda x: -x[1]) starts.add(li[0][2]) for i in range(n - 1): beaten_by[li[i + 1][2]].add(li[i][2]) iptw = ['0'] * n # is possible to win for v in starts: iptw[v] = '1' for start in starts: dfs(start) print(''.join(iptw)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": 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 ip = lambda: input() iip = lambda: int(input()) miip = lambda: map(int, input().split()) liip = lambda: list(map(int, input().split())) sip = lambda: input().split() # splitted input lip = lambda: list(input()) main()
1639217100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["0.000000000000000", "3.000000000000000", "2.965517241379311"]
ba4304e79d85d13c12233bcbcce6d0a6
NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.
DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
The first line contains two space-separated integers nΒ (1 ≀ n ≀ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1 ≀ xi ≀ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ciΒ (1 ≀ ai &lt; bi ≀ n;Β 1 ≀ ci ≀ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
standard output
standard input
Python 3
Python
1,600
train_014.jsonl
52a295d0891d369535a1724175a9bfa6
256 megabytes
["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"]
PASSED
R = lambda:map(int, input().split()) ans = 0 n, m = R() F = list(R()) for i in range(m): a, b, x = R() ans = max(ans, (F[a - 1]+ F[b - 1]) / x) print(ans)
1404651900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["3\n1 2 12", "3\n1 1 2", "2\n1 2"]
ecda878d924325789dc05035e4f4bbe0
NoteIn the first case, the optimal subset is , which has mean 5, median 2, and simple skewness of 5 - 2 = 3.In the second case, the optimal subset is . Note that repetition is allowed.In the last case, any subset has the same median and mean, so all have simple skewness of 0.
Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of n (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size.
In the first line, print a single integer kΒ β€” the size of the subset. In the second line, print k integersΒ β€” the elements of the subset in any order. If there are multiple optimal subsets, print any.
The first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of elements in the list. The second line contains n integers xi (0 ≀ xi ≀ 1 000 000)Β β€” the ith element of the list.
standard output
standard input
PyPy 3
Python
2,400
train_044.jsonl
45dbb00f4cd7843160bda258d8a28b8b
256 megabytes
["4\n1 2 3 12", "4\n1 1 2 2", "2\n1 2"]
PASSED
from itertools import accumulate from fractions import Fraction n = int(input()) A = [int(x) for x in input().split()] A.sort() B = list(accumulate([0] + A)) def condition(i, z): return (2*z - 1)*(A[i-z] + A[-z]) > 2*(B[i+1] - B[i-z+1] + B[-1] - B[-z]) def average(i, z): return Fraction((B[i+1] - B[i-z] + B[-1] - B[-z-1]) , 2*z + 1) maxans = 0 argmax = (0, 0) for i in range(1, n-1): x, y = 0, min(i, n-1-i) while y - x > 1: z = (x + y)//2 if condition(i, z): x = z else: y = z if condition(i, y): x = y if maxans < average(i, x) - A[i]: maxans = average(i, x) - A[i] argmax = (i, x) print(argmax[1]*2 + 1) for i in range(argmax[0] - argmax[1], argmax[0] + 1): print(A[i], end = ' ') for i in range(-argmax[1], 0): print(A[i], end = ' ')
1455384900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Impossible", "0110"]
6893987b310c41efb269b63e865355d8
null
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000.
If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000.
The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.
standard output
standard input
Python 2
Python
1,900
train_038.jsonl
c3ea74a3a50512a3b3ff82de2ff1c83e
256 megabytes
["1 2 3 4", "1 2 2 1"]
PASSED
def f(x): l, r, mid, res = 1, 100000, 0, -1 while l <= r: mid = (l + r) / 2 if mid * (mid - 1) / 2 == x: res = mid break elif mid * (mid - 1) / 2 < x: l = mid + 1 else: r = mid - 1 if res == 1 and (not (b or c)): res = 0 return res a, b, c, d = map(int, raw_input().split()) x, y = f(a), f(d) if not (x or y):print '0' elif x == -1 or y == -1 or b + c != x * y:print 'Impossible' elif x == 0:print '1' * y elif y == 0:print '0' * x else: t = b / x p = b % x if p: s = '1' * (y - t - 1) s += '0' * p s += '1' s += '0' * (x - p) s += '1' * t print s else: s = '1' * (y - t) s += '0' * x s += '1' * t print s
1472056500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["30.00000 0.00000"]
9829e1913e64072aadc9df5cddb63573
null
The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered. Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.
Print the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.
The input data consists of three lines, each of them describes the position of one stadium. The lines have the format x,  y,  r, where (x, y) are the coordinates of the stadium's center ( -  103 ≀ x,  y ≀ 103), and r (1 ≀ r  ≀ 103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line.
standard output
standard input
Python 3
Python
2,600
train_019.jsonl
e4fb13974249bae71328dbf739fda73e
64 megabytes
["0 0 10\n60 0 10\n30 30 10"]
PASSED
V=[list(map(int,input().split())) for _ in range(3)] a=[] for i in range(3): da=V[i][0]-V[(i+1)%3][0] db=V[i][1]-V[(i+1)%3][1] drs=V[i][2]**2-V[(i+1)%3][2]**2 #Let drs=0 das=(V[i][0]+V[(i+1)%3][0])*da dbs=(V[i][1]+V[(i+1)%3][1])*db a.append([2*da,2*db,drs,das+dbs]) def Gauss(n,m): for i in range(n-1): Max=i for j in range(i,n): if a[j][i]>a[Max][i]: Max=j for j in range(m): a[i][j],a[Max][j]=a[Max][j],a[i][j] if a[i][i]==0: continue for j in range(i+1,m): a[i][j]/=a[i][i] a[i][i]=1 for j in range(i+1,n): tmp=a[j][i]/a[i][i] for k in range(i,m): a[j][k]-=tmp*a[i][k] Gauss(3,4) def gett(x,y): a=V[0][0] b=V[0][1] r=V[0][2] A=x[0]**2+y[0]**2 B=2*x[0]*(x[1]-a)+2*y[0]*(y[1]-b)-r*r C=(x[1]-a)**2+(y[1]-b)**2 if A==0: if B==0: print() exit(0) else: return C/B delta=B**2-4*A*C if delta<0: print() exit(0) t1=(-B+delta**(1/2))/(2*A) t2=(-B-delta**(1/2))/(2*A) if min(t1,t2)>0: return min(t1,t2) elif max(t1,t2)<0: print() exit(0) else: return max(t1,t2) if abs(a[2][2])<1e-7: if abs(a[2][3])>1e-7: print() exit(0) y=(-a[1][2],a[1][3]) x=(-a[0][2]+a[0][1]*a[1][2],a[0][3]-a[0][1]*a[1][3]) t=gett(x,y) y=-a[1][2]*t+a[1][3] x=(-a[0][2]+a[0][1]*a[1][2])*t+a[0][3]-a[0][1]*a[1][3] print("%.5f %.5f" % (x,y)) else: t=a[2][3]/a[2][2] if a[1][1]==0 and a[1][3]-a[1][2]*t!=0: print() exit(0) if a[1][1]==0: y=0 else: y=(a[1][3]-a[1][2]*t)/a[1][1] if a[0][0]==0 and a[0][3]-a[0][2]*t-a[0][1]*y!=0: print() exit(0) if a[0][0]==0: x=0 else: x=(a[0][3]-a[0][2]*t-a[0][1]*y)/a[0][0] print("%.5f %.5f" % (x,y))
1267117200
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["1", "0", "2"]
62a672fcaee8be282700176803c623a7
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
standard output
standard input
PyPy 3
Python
1,200
train_000.jsonl
82da8dbc1eee5c17f97ee53c9dbb0227
256 megabytes
["intellect\ntell", "google\napple", "sirisiri\nsir"]
PASSED
s1=input() s2=input() print(s1.count(s2))
1454835900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1 1\n-1\n4 6\n166374058999707392 249561088499561088"]
1cc628b4e03c8b8e0c5086dc4e0e3254
NoteIn the first test case the total number of wheels is $$$4$$$. It means that there is the only one bus with two axles in the bus fleet.In the second test case it's easy to show that there is no suitable number of buses with $$$7$$$ wheels in total.In the third test case the total number of wheels is $$$24$$$. The following options are possible: Four buses with three axles. Three buses with two axles and two buses with three axles. Six buses with two axles. So the minimum number of buses is $$$4$$$ and the maximum number of buses is $$$6$$$.
Spring has come, and the management of the AvtoBus bus fleet has given the order to replace winter tires with summer tires on all buses.You own a small bus service business and you have just received an order to replace $$$n$$$ tires. You know that the bus fleet owns two types of buses: with two axles (these buses have $$$4$$$ wheels) and with three axles (these buses have $$$6$$$ wheels).You don't know how many buses of which type the AvtoBus bus fleet owns, so you wonder how many buses the fleet might have. You have to determine the minimum and the maximum number of buses that can be in the fleet if you know that the total number of wheels for all buses is $$$n$$$.
For each test case print the answer in a single line using the following format. Print two integers $$$x$$$ and $$$y$$$ ($$$1 \le x \le y$$$)Β β€” the minimum and the maximum possible number of buses that can be in the bus fleet. If there is no suitable number of buses for the given $$$n$$$, print the number $$$-1$$$ as the answer.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1\,000$$$)Β β€” the number of test cases. The following lines contain description of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$)Β β€” the total number of wheels for all buses.
standard output
standard input
Python 3
Python
900
train_099.jsonl
f73adefa2e3bd6b736050cb083fdeb57
256 megabytes
["4\n\n4\n\n7\n\n24\n\n998244353998244352"]
PASSED
for i in range(int(input())): n = int(input()) if n%2 != 0 or n < 3: print(-1) else: minimum = n // 6 maximum = n//4 if minimum * 6 != n: minimum += 1 print(minimum, maximum)
1652520900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["YES", "NO", "YES"]
ad5b878298adea8742c36e2e119780f9
NoteIn the first sample, we can cut the edge $$$(1, 2)$$$, and the tree will be split into $$$2$$$ trees of sizes $$$1$$$ and $$$2$$$ correspondently. Any tree of size $$$2$$$ is a Fib-tree, as it can be split into $$$2$$$ trees of size $$$1$$$.In the second sample, no matter what edge we cut, the tree will be split into $$$2$$$ trees of sizes $$$1$$$ and $$$4$$$. As $$$4$$$ isn't $$$F_k$$$ for any $$$k$$$, it's not Fib-tree.In the third sample, here is one possible order of cutting the edges so that all the trees in the process are Fib-trees: $$$(1, 3), (1, 2), (4, 5), (3, 4)$$$.
Let $$$F_k$$$ denote the $$$k$$$-th term of Fibonacci sequence, defined as below: $$$F_0 = F_1 = 1$$$ for any integer $$$n \geq 0$$$, $$$F_{n+2} = F_{n+1} + F_n$$$You are given a tree with $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles.We call a tree a Fib-tree, if its number of vertices equals $$$F_k$$$ for some $$$k$$$, and at least one of the following conditions holds: The tree consists of only $$$1$$$ vertex; You can divide it into two Fib-trees by removing some edge of the tree. Determine whether the given tree is a Fib-tree or not.
Print "YES" if the given tree is a Fib-tree, or "NO" otherwise. You can print your answer in any case. For example, if the answer is "YES", then the output "Yes" or "yeS" will also be considered as correct answer.
The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) β€” the number of vertices in the tree. Then $$$n-1$$$ lines follow, each of which contains two integers $$$u$$$ and $$$v$$$ ($$$1\leq u,v \leq n$$$, $$$u \neq v$$$), representing an edge between vertices $$$u$$$ and $$$v$$$. It's guaranteed that given edges form a tree.
standard output
standard input
PyPy 3
Python
2,400
train_095.jsonl
195e22700f190f2cd4d81a027aece074
256 megabytes
["3\n1 2\n2 3", "5\n1 2\n1 3\n1 4\n1 5", "5\n1 3\n1 2\n4 5\n3 4"]
PASSED
def main(): n = int(input()) graph = [[] for _ in range(n+1)] parent = [-1 for _ in range(n+1)] for _ in range(n-1): x,y = map(int, input().split(' ')) graph[x].append(y) graph[y].append(x) digraph = [[] for _ in range(n+1)] stack = [1] count_order = [] while stack: cur = stack.pop() count_order.append(cur) for adj in graph[cur]: if parent[cur] == adj: continue stack.append(adj) parent[adj] = cur digraph[cur].append(adj) count = [1 for _ in range(n+1)] while count_order: cur = count_order.pop() for child in digraph[cur]: count[cur] += count[child] fib_numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418] fib_d = {val : i for i, val in enumerate(fib_numbers)} fin = [0 for _ in range(n+1)] def rec(cur_root, total_nodes): if total_nodes <= 3: return True elif total_nodes not in fib_d: return False fib_idx = fib_d[total_nodes] search_vals = [fib_numbers[fib_idx-1], fib_numbers[fib_idx-2]] cut_node = -1 stack = [cur_root] while stack: cur_node = stack.pop() if count[cur_node] in search_vals: cut_node = cur_node fin[cut_node] = True break for adj in digraph[cur_node]: if not fin[adj]: stack.append(adj) if cut_node == -1: return False cut_node_count = count[cut_node] # propagate update upwards cur_parent = parent[cut_node] while cur_parent != -1: count[cur_parent] -= cut_node_count cur_parent = parent[cur_parent] parent[cut_node] = -1 if count[cur_root] <= count[cut_node]: try1 = rec(cur_root, count[cur_root]) if try1: return rec(cut_node, count[cut_node]) else: try1 = rec(cut_node, count[cut_node]) if try1: return rec(cur_root, count[cur_root]) return False print("YES" if rec(1, n) else "NO") # region fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
1614519300
[ "number theory", "trees" ]
[ 0, 0, 0, 0, 1, 0, 0, 1 ]
1 second
["1\n4\n2"]
fa761cd247a815f105668b716c20f0b4
NoteThe first test case is described in the statement.In the second test case, the indices $$$i$$$ that result in palindrome after removing $$$s_i$$$ are $$$3, 4, 5, 6$$$. Hence the answer is $$$4$$$. In the third test case, removal of any of the indices results in "d" which is a palindrome. Hence the answer is $$$2$$$.
You are given a palindromic string $$$s$$$ of length $$$n$$$.You have to count the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome. For example, consider $$$s$$$ = "aba" If we remove $$$s_1$$$ from $$$s$$$, the string becomes "ba" which is not a palindrome. If we remove $$$s_2$$$ from $$$s$$$, the string becomes "aa" which is a palindrome. If we remove $$$s_3$$$ from $$$s$$$, the string becomes "ab" which is not a palindrome. A palindrome is a string that reads the same backward as forward. For example, "abba", "a", "fef" are palindromes whereas "codeforces", "acd", "xy" are not.
For each test case, output a single integer Β β€” the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome.
The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3)$$$ Β β€” the number of test cases. Description of the test cases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ Β β€” the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of lowercase English letters. It is guaranteed that $$$s$$$ is a palindrome. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
800
train_101.jsonl
eb16aebd7408f43cd0183327bb6bb9a7
256 megabytes
["3\n\n3\n\naba\n\n8\n\nacaaaaca\n\n2\n\ndd"]
PASSED
for _ in range(int(input())): n=int(input()) s= input() c=0 val = s[n//2] for i in range(n//2-1, -1, -1): if s[i]!=val: break c+=2 print(c+n%2)
1653230100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1.00000000000000000000", "1.50000000000000000000", "1.33333333333333350000", "2.50216960000000070000"]
c2b3b577c2bcb3a2a8cb48700c637270
null
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
The first line contains two positive integers n and m (1 ≀ n, m ≀ 50) β€” the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 ≀ ai ≀ 50). ai means the amount of wash basins in the i-th room.
standard output
standard input
Python 2
Python
2,200
train_020.jsonl
9ae6365e128a1cf4e5efc387e6e2c9d9
256 megabytes
["1 1\n2", "2 2\n1 1", "2 3\n1 1 1", "7 5\n1 1 2 3 1"]
PASSED
n, m = map(int, raw_input().split()) a = map(int, raw_input().split()) prob = [(n+1)*[None] for _ in range(m+1)] for k in range(1, m+1): prob[k][0] = [1.0] for i in range(1, n+1): prob[k][i] = (i+1)*[0.0] for j in range(i): prob[k][i][j+1] += prob[k][i-1][j]*(1.0/k) prob[k][i][j] += prob[k][i-1][j]*(1-1.0/k) dp = [[(n+1)*[0.0] for _ in range(n+1)] for _ in range(m+1)] dp[m][n][0] = 1.0 for k in range(m, 0, -1): for i in range(n+1): for x in range(n+1): t = dp[k][i][x] if t == 0.0: continue for j in range(i+1): dp[k-1][i-j][max(x, (j+a[m-k]-1)/a[m-k])] += t*prob[k][i][j] res = 0 for x in range(n+1): res += x*dp[0][0][x] print "%.13f" % res
1284735600
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
1 second
["2 3\n1 1 2\n1 2 4\n1 4 5", "1 3 5\n2 5\n1 1 2\n1 2 4", "2 2", "1 1 2\n1 2 3\n1 3 4", "1 1 2\n1 2 3\n1 3 4"]
f09b435a20a415d65803a80d57152832
NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: $$$[5, -2, 0, 1, -3] \to [5, -2, X, 1, -3] \to [X, -10, X, 1, -3] \to$$$ $$$[X, X, X, -10, -3] \to [X, X, X, X, 30]$$$. Thus, the maximum answer is $$$30$$$. Note, that other sequences that lead to the answer $$$30$$$ are also correct.The second example has, for example, the following sequence of transformations of the array: $$$[5, 2, 0, 4, 0] \to [5, 2, X, 4, 0] \to [5, 2, X, 4, X] \to [X, 10, X, 4, X] \to$$$ $$$[X, X, X, 40, X]$$$. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: $$$[5, 2, 0, 4, 0] \to [5, 2, 0, 4, X] \to [5, 8, 0, X, X] \to [40, X, 0, X, X] \to$$$ $$$[40, X, X, X, X]$$$.The third example can have the following sequence of transformations of the array: $$$[2, -1] \to [2, X]$$$.The fourth example can have the following sequence of transformations of the array: $$$[0, -10, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.The fifth example can have the following sequence of transformations of the array: $$$[0, 0, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.
You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations with it: Choose some positions $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n, i \ne j$$$), write the value of $$$a_i \cdot a_j$$$ into the $$$j$$$-th cell and remove the number from the $$$i$$$-th cell; Choose some position $$$i$$$ and remove the number from the $$$i$$$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly $$$n - 1$$$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.
Print $$$n - 1$$$ lines. The $$$k$$$-th line should contain one of the two possible operations. The operation of the first type should look like this: $$$1~ i_k~ j_k$$$, where $$$1$$$ is the type of operation, $$$i_k$$$ and $$$j_k$$$ are the positions of the chosen elements. The operation of the second type should look like this: $$$2~ i_k$$$, where $$$2$$$ is the type of operation, $$$i_k$$$ is the position of the chosen element. Note that there should be no more than one such operation. If there are multiple possible sequences of operations leading to the maximum number β€” print any of them.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) β€” the elements of the array.
standard output
standard input
PyPy 3
Python
1,700
train_001.jsonl
bee37cd874000c141b1275e5c54a5824
256 megabytes
["5\n5 -2 0 1 -3", "5\n5 2 0 4 0", "2\n2 -1", "4\n0 -10 0 0", "4\n0 0 0 0"]
PASSED
n = int(input()) a = list(map(int,input().split())) hu = 0 humax = -float("inf") huind = None able = set(range(n)) ans = [] mae = -1 for i in range(n): if a[i] == 0: if mae == -1: mae = i able.discard(i) else: ans.append([1,mae+1,i+1]) able.discard(i) mae = i if a[i]<0: hu +=1 if a[i] > humax: humax =a[i] huind = i if hu %2 == 1: if mae == -1: ans.append([2,huind+1]) able.discard(huind) mae = huind else: ans.append([1,mae+1,huind+1]) able.discard(huind) ans.append([2,huind+1]) mae = huind if able == set(): ans.pop(-2) able.add(0) if a[mae] == 0: ans.append([2,mae+1]) if able == set(): ans.pop() mae = -1 for i in able: if mae == -1: mae = i else: ans.append([1,mae+1,i+1]) mae = i for i in ans: print(*i)
1537171500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nYES\nNO"]
f2070c2bd7bdbf0919aef1e915a21a24
Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation.
You are given an array $$$a_1, a_2, \dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.
For each test case, output "YES" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or "NO" if it is impossible to do so.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€” the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the length of array $$$a$$$. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β€” the array itself. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,300
train_003.jsonl
936191d6ddf860246b411219c2de6730
256 megabytes
["4\n1\n8\n6\n4 3 6 6 2 9\n4\n4 5 6 7\n5\n7 5 2 2 4"]
PASSED
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) y=sorted(l) x=min(l) a=[] b=[] for i in range(n): if l[i]%x==0: a.append(l[i]) b.append(i) a.sort() for i in range(len(b)): l[b[i]]=a[i] if(l==y): print('YES') else: print('NO')
1598020500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["3\n6 3\n6 5\n1 3\n1 4\n5 2"]
6a4e5b549514814a6c72d3b1e211a7f6
NoteThe scheme for the first example (R denotes the lamp connected to the grid, the numbers on wires are their importance values):
Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of $$$n$$$ lamps and $$$n - 1$$$ wires. Exactly one lamp will be connected to power grid, and power will be transmitted from it to other lamps by the wires. Each wire connectes exactly two lamps; one lamp is called the main lamp for this wire (the one that gets power from some other wire and transmits it to this wire), the other one is called the auxiliary lamp (the one that gets power from this wire). Obviously, each lamp has at most one wire that brings power to it (and this lamp is the auxiliary lamp for this wire, and the main lamp for all other wires connected directly to it).Each lamp has a brightness value associated with it, the $$$i$$$-th lamp has brightness $$$2^i$$$. We define the importance of the wire as the sum of brightness values over all lamps that become disconnected from the grid if the wire is cut (and all other wires are still working).Polycarp has drawn the scheme of the garland he wants to make (the scheme depicts all $$$n$$$ lamp and $$$n - 1$$$ wires, and the lamp that will be connected directly to the grid is marked; the wires are placed in such a way that the power can be transmitted to each lamp). After that, Polycarp calculated the importance of each wire, enumerated them from $$$1$$$ to $$$n - 1$$$ in descending order of their importance, and then wrote the index of the main lamp for each wire (in the order from the first wire to the last one).The following day Polycarp bought all required components of the garland and decided to solder it β€” but he could not find the scheme. Fortunately, Polycarp found the list of indices of main lamps for all wires. Can you help him restore the original scheme?
If it is impossible to restore the original scheme, print one integer $$$-1$$$. Otherwise print the scheme as follows. In the first line, print one integer $$$k$$$ ($$$1 \le k \le n$$$) β€” the index of the lamp that is connected to the power grid. Then print $$$n - 1$$$ lines, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) β€” the indices of the lamps connected by some wire. The descriptions of the wires (and the lamps connected by a wire) can be printed in any order. The printed description must correspond to a scheme of a garland such that Polycarp could have written the list $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n - 1}$$$ from it. If there are multiple such schemes, output any of them.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β€” the number of lamps. The second line contains $$$n - 1$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n - 1}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the index of the main lamp for the $$$i$$$-th wire (wires are numbered in descending order of importance).
standard output
standard input
Python 3
Python
2,200
train_024.jsonl
8c32c62dfb88c2bbd8155902497db3f8
256 megabytes
["6\n3 6 3 1 5"]
PASSED
n = int(input()) a = list(map(int,input().split())) dic = {} uexmax = n ans = [] for i in range(n-1): if i == 0: dic[a[i]] = 1 else: if a[i] in dic: dic[uexmax] = 1 ans.append([ a[i-1] , uexmax ]) else: dic[a[i]] = 1 ans.append([ a[i-1] , a[i] ]) while uexmax in dic: uexmax -= 1 ans.append ( [a[-1] , uexmax] ) print (a[0]) for i in range(n-1): print (" ".join(map(str,ans[i])))
1577552700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
ad02cead427d0765eb642203d13d3b99
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
The only line of input contains the string s (1 ≀ |s| ≀ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
standard output
standard input
Python 3
Python
1,600
train_021.jsonl
5bb17e98c48ca49ca9462c890d8d20ff
256 megabytes
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
PASSED
s = input() a = s.replace(';', ',').split(',') c, d = [], [] for elem in a: if elem.isdigit() and (elem[0] != '0' or len(elem) == 1): c.append(elem) else: d.append(elem) if (len(c) == 0): print('-') #print('"' + ','.join(c) + '"') print('"' + ','.join(d) + '"') elif (len(d) == 0): print('"' + ','.join(c) + '"') #print('"' + ','.join(d) + '"') print('-') else: print('"' + ','.join(c) + '"') print('"' + ','.join(d) + '"')
1448636400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1", "4"]
28b7e9de0eb583642526c077aa56daba
NoteFor the second example all the permutations are: p = [1, 2, 3] : fa is equal to 1; p = [1, 3, 2] : fa is equal to 1; p = [2, 1, 3] : fa is equal to 1; p = [2, 3, 1] : fa is equal to 1; p = [3, 1, 2] : fa is equal to 0; p = [3, 2, 1] : fa is equal to 0. Where p is the array of the indices of initial array a. The sum of fa is equal to 4.
You are given an array a of length n. We define fa the following way: Initially fa = 0, M = 1; for every 2 ≀ i ≀ n if aM &lt; ai then we set fa = fa + aM and then set M = i. Calculate the sum of fa over all n! permutations of the array a modulo 109 + 7.Note: two elements are considered different if their indices differ, so for every array a there are exactly n! permutations.
Print the only integer, the sum of fa over all n! permutations of the array a modulo 109 + 7.
The first line contains integer n (1 ≀ n ≀  1 000 000) β€” the size of array a. Second line contains n integers a1, a2, ..., an (1 ≀  ai ≀  109).
standard output
standard input
Python 2
Python
2,300
train_030.jsonl
3439d41b80fb9d040d9739eaf022a899
256 megabytes
["2\n1 3", "3\n1 1 2"]
PASSED
def main(): f= [1] for i in range(1,1000002): f.append((f[-1] * i)%1000000007) n = int(raw_input()) a = sorted(int(x) for x in raw_input().split()) sol = 0 j = 0 s = 1 sq = 1 for i in range(n - 1): sq = sq * (n - i) % 1000000007 if a[i] != a[i + 1]: sol += a[i] * (i - j + 1) * f[n - j - 1] * s j = i + 1 s = sq print(sol % 1000000007) if __name__ == '__main__': main()
1518793500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n2 3\n111 1111 11111 111111 1111111 11111111 111111111"]
76bfced1345f871832957a65e2a660f8
NoteIn the first test case, array $$$[1]$$$ satisfies all the conditions.In the second test case, array $$$[2, 3]$$$ satisfies all the conditions, as $$$2&lt;3$$$ and $$$3$$$ is not divisible by $$$2$$$.In the third test case, array $$$[111, 1111, 11111, 111111, 1111111, 11111111, 111111111]$$$ satisfies all the conditions, as it's increasing and $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$ for any $$$i$$$ from $$$2$$$ to $$$7$$$.
Given $$$n$$$, find any array $$$a_1, a_2, \ldots, a_n$$$ of integers such that all of the following conditions hold: $$$1 \le a_i \le 10^9$$$ for every $$$i$$$ from $$$1$$$ to $$$n$$$.$$$a_1 &lt; a_2 &lt; \ldots &lt;a_n$$$For every $$$i$$$ from $$$2$$$ to $$$n$$$, $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$It can be shown that such an array always exists under the constraints of the problem.
For each test case print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ β€” the array you found. If there are multiple arrays satisfying all the conditions, print any of them.
The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.
standard output
standard input
Python 3
Python
800
train_109.jsonl
3b4015ff8824783539becf24898e9452
256 megabytes
["3\n1\n2\n7"]
PASSED
for _ in range(int(input())): n = int(input()) for i in range(n): print((i+2)%100000000,end=" ") print("")
1639217100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1110", "1010010", "1000000000000000001010010", "0"]
8ddccfaf362b19d50647bfb6ad421953
NoteFor each of the testcases $$$1$$$ to $$$3$$$, $$$A = \{2^3,2^1,2^2\} = \{8,2,4\}$$$ and $$$E=8\wedge 2\wedge 4$$$.For the first testcase, there is only one possible valid unambiguous expression $$$E' = 8\oplus 2\oplus 4 = 14 = (1110)_2$$$.For the second testcase, there are three possible valid unambiguous expressions $$$E'$$$: $$$8\oplus 2\oplus 4 = 14$$$ $$$8^2\oplus 4 = 64\oplus 4= 68$$$ $$$8\oplus 2^4 = 8\oplus 16= 24$$$ XOR of the values of all of these is $$$14\oplus 68\oplus 24 = 82 = (1010010)_2$$$.For the third testcase, there are four possible valid unambiguous expressions $$$E'$$$: $$$8\oplus 2\oplus 4 = 14$$$ $$$8^2\oplus 4 = 64\oplus 4= 68$$$ $$$8\oplus 2^4 = 8\oplus 16= 24$$$ $$$(8^2)^4 = 64^4 = 2^{24} = 16777216$$$ XOR of the values of all of these is $$$14\oplus 68\oplus 24\oplus 16777216 = 16777298 = (1000000000000000001010010)_2$$$.For the fourth testcase, $$$A=\{2,2\}$$$ and $$$E=2\wedge 2$$$. The only possible valid unambiguous expression $$$E' = 2\oplus 2 = 0 = (0)_2$$$.
The symbol $$$\wedge$$$ is quite ambiguous, especially when used without context. Sometimes it is used to denote a power ($$$a\wedge b = a^b$$$) and sometimes it is used to denote the XOR operation ($$$a\wedge b=a\oplus b$$$). You have an ambiguous expression $$$E=A_1\wedge A_2\wedge A_3\wedge\ldots\wedge A_n$$$. You can replace each $$$\wedge$$$ symbol with either a $$$\texttt{Power}$$$ operation or a $$$\texttt{XOR}$$$ operation to get an unambiguous expression $$$E'$$$.The value of this expression $$$E'$$$ is determined according to the following rules: All $$$\texttt{Power}$$$ operations are performed before any $$$\texttt{XOR}$$$ operation. In other words, the $$$\texttt{Power}$$$ operation takes precedence over $$$\texttt{XOR}$$$ operation. For example, $$$4\;\texttt{XOR}\;6\;\texttt{Power}\;2=4\oplus (6^2)=4\oplus 36=32$$$. Consecutive powers are calculated from left to right. For example, $$$2\;\texttt{Power}\;3 \;\texttt{Power}\;4 = (2^3)^4 = 8^4 = 4096$$$. You are given an array $$$B$$$ of length $$$n$$$ and an integer $$$k$$$. The array $$$A$$$ is given by $$$A_i=2^{B_i}$$$ and the expression $$$E$$$ is given by $$$E=A_1\wedge A_2\wedge A_3\wedge\ldots\wedge A_n$$$. You need to find the XOR of the values of all possible unambiguous expressions $$$E'$$$ which can be obtained from $$$E$$$ and has at least $$$k$$$ $$$\wedge$$$ symbols used as $$$\texttt{XOR}$$$ operation. Since the answer can be very large, you need to find it modulo $$$2^{2^{20}}$$$. Since this number can also be very large, you need to print its binary representation without leading zeroes. If the answer is equal to $$$0$$$, print $$$0$$$.
Print a single line containing a binary string without leading zeroes denoting the answer to the problem. If the answer is equal to $$$0$$$, print $$$0$$$.
The first line of input contains two integers $$$n$$$ and $$$k$$$ $$$(1\leq n\leq 2^{20}, 0\leq k &lt; n)$$$. The second line of input contains $$$n$$$ integers $$$B_1,B_2,\ldots,B_n$$$ $$$(1\leq B_i &lt; 2^{20})$$$.
standard output
standard input
PyPy 3
Python
2,500
train_096.jsonl
3eb509acff1a5ce7f568c1452db8bdb4
512 megabytes
["3 2\n3 1 2", "3 1\n3 1 2", "3 0\n3 1 2", "2 1\n1 1"]
PASSED
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): m = u.bit_length() dp0, dp1 = [0] * 2, [0] * 2 dp0[0] = 1 for i in range(m - 1, -1, -1): ndp0, ndp1 = [0] * 2, [0] * 2 c = u & pow2[i] d = v & pow2[i] if c and d: ndp0[0] = dp0[0] ndp0[1] = dp0[1] ndp1[0] = dp0[0] + 2 * dp1[0] ndp1[1] = dp0[1] + 2 * dp1[1] elif c: ndp0[0] = dp0[0] ndp0[1] = dp0[1] ndp1[0] = 2 * dp1[0] ndp1[1] = 2 * dp1[1] elif d: ndp0[1] = dp0[0] + dp0[1] ndp1[0] = dp0[0] + dp1[0] ndp1[1] = dp0[1] + dp1[0] + 2 * dp1[1] else: ndp0[0] = dp0[0] ndp0[1] = dp0[1] ndp1[0] = dp1[0] ndp1[1] = dp1[0] + 2 * dp1[1] dp0, dp1 = ndp0, ndp1 return v + 3 - (dp0[1] + dp1[1]) n, k = map(int, input().split()) b = list(map(int, input().split())) if n == 1: ans = "1" + "0" * b[0] sys.stdout.write(ans) exit() pow2 = [1] for _ in range(20): pow2.append(2 * pow2[-1]) l = pow2[20] ans = [0] * l y = [] u, c = n - 2, 2 for _ in range(25): u -= 1 v = u - max(k - c, 0) y.append(f(u, v) % 2) for i in range(n): u, c = n - 2, 2 for j in range(i, min(i + 25, n)): u -= 1 if j == 0 or j == n - 1: u += 1 c -= 1 if i == j: x = b[j] elif b[j] > 20: break else: x *= pow2[b[j]] if x >= l or u < k - c: break if 0 < i <= n - 25: ans[x] ^= y[j - i] else: v = u - max(k - c, 0) ans[x] ^= f(u, v) % 2 while len(ans) > 1 and not ans[-1]: ans.pop() ans.reverse() sys.stdout.write("".join(map(str, ans)))
1651329300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["5", "33"]
752c583a1773847504bf0d50b72a9dda
null
You are given a string $$$t$$$ and $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$. All strings consist of lowercase Latin letters.Let $$$f(t, s)$$$ be the number of occurences of string $$$s$$$ in string $$$t$$$. For example, $$$f('\text{aaabacaa}', '\text{aa}') = 3$$$, and $$$f('\text{ababa}', '\text{aba}') = 2$$$.Calculate the value of $$$\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$$$, where $$$s + t$$$ is the concatenation of strings $$$s$$$ and $$$t$$$. Note that if there are two pairs $$$i_1$$$, $$$j_1$$$ and $$$i_2$$$, $$$j_2$$$ such that $$$s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}$$$, you should include both $$$f(t, s_{i_1} + s_{j_1})$$$ and $$$f(t, s_{i_2} + s_{j_2})$$$ in answer.
Print one integer β€” the value of $$$\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$$$.
The first line contains string $$$t$$$ ($$$1 \le |t| \le 2 \cdot 10^5$$$). The second line contains integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). Each of next $$$n$$$ lines contains string $$$s_i$$$ ($$$1 \le |s_i| \le 2 \cdot 10^5$$$). It is guaranteed that $$$\sum\limits_{i=1}^{n} |s_i| \le 2 \cdot 10^5$$$. All strings consist of lowercase English letters.
standard output
standard input
PyPy 2
Python
2,400
train_020.jsonl
b2043da40b924804c23ad7008741cb1c
256 megabytes
["aaabacaa\n2\na\naa", "aaabacaa\n4\na\na\na\nb"]
PASSED
from __future__ import division, print_function from collections import deque class Node: def __init__(self, c, nxt, fail, o): self.c = c self.nxt = nxt self.fail = fail self.o = o root = Node('', {}, Node, 0) root.fail = root def new_node(par, c): node = Node(c, {}, root, 0) par.nxt[c] = node return node def go(n, c): while True: try: return n.nxt[c] except KeyError: if n != root: n = n.fail else: return root def build(ps): for i, p in enumerate(ps): n = root for c in p: try: n = n.nxt[c] except KeyError: n = new_node(n, c) n.o += 1 q = deque([root]) while q: n = q.popleft() for c, cn in n.nxt.iteritems(): q.append(cn) if n == root: cn.fail = root else: cn.fail = go(n.fail, c) cn.o += cn.fail.o def query(s, ar): n = root for i, c in enumerate(s): n = go(n, c) ar[i] += n.o def main(): s = input() ps = [input() for _ in range(int(input()))] build(ps) far = array_of(int, len(s)) query(s, far) root.nxt = {} root.o = 0 rps = [list(reversed(ss)) for ss in ps] rs = list(reversed(s)) build(rps) bar = array_of(int, len(rs)) query(rs, bar) ans = 0 for i in range(len(s)-1): ans += bar[i] * far[len(s)-2-i] print(ans) INF = float('inf') MOD = 10**9 + 7 import os, sys from atexit import register from io import BytesIO import itertools if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip if 0: debug_print = print else: 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') debug_print = lambda *x, **y: None def input_as_list(): return list(map(int, input().split())) def array_of(f, *dim): return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f() main()
1565188500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["Yes\nYes\nNo\nNo\nYes\nYes"]
a5e649f4d984a5c5365ca31436ad5883
NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$.
Vivek has encountered a problem. He has a maze that can be represented as an $$$n \times m$$$ grid. Each of the grid cells may represent the following: EmptyΒ β€” '.' WallΒ β€” '#' Good person Β β€” 'G' Bad personΒ β€” 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No" You may print every letter in any case (upper or lower).
The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$Β β€” the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$Β β€” the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
standard output
standard input
PyPy 3
Python
1,700
train_005.jsonl
d038faba7d151a510df0665476b9ac9b
256 megabytes
["6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB."]
PASSED
import sys input = sys.stdin.buffer.readline def main(): t = int(input()) for _ in range(t): n, m = map(int, input().split()) M = [list(str(input())[2:m+2]) for _ in range(n)] M = [['#']*m] + M + [['#']*m] M = [['#']+c+['#'] for c in M] #print(M) B = [] G = [] flag1 = True for i in range(1, n+1): for j in range(1, m+1): if M[i][j] == 'B': for di, dj in (-1, 0), (1, 0), (0, -1), (0, 1): ni, nj = i+di, j+dj if 1 <= ni <= n and 1 <= nj <= m: if M[ni][nj] == '.': M[ni][nj] = '#' if M[ni][nj] == 'G': flag1 = False break B.append((i, j)) if M[i][j] == 'G': G.append((i, j)) if not flag1: print('No') continue if len(G) > 0 and M[n][m] == '#': print('No') continue s = [] s.append((n, m)) visit = [[-1]*(m+2) for _ in range(n+2)] visit[n][m] = 0 while s: y, x = s.pop() for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1): ny, nx = y+dy, x+dx if visit[ny][nx] == -1 and M[ny][nx] != '#': visit[ny][nx] = visit[y][x]+1 s.append((ny, nx)) flag = True for sy, sx in G: if visit[sy][sx] == -1: flag = False break #print(visit) if flag: print('Yes') else: print('No') if __name__ == '__main__': main()
1591540500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1\n2\n1\n3\n0"]
02062d1afe85e3639edddedceac304f4
NoteIn the first test, you construct a pyramid of height $$$1$$$ with $$$2$$$ cards. There is $$$1$$$ card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height $$$2$$$, with no cards remaining.In the third test, you build one pyramid of height $$$3$$$, with no cards remaining.In the fourth test, you build one pyramid of height $$$3$$$ with $$$9$$$ cards remaining. Then you build a pyramid of height $$$2$$$ with $$$2$$$ cards remaining. Then you build a final pyramid of height $$$1$$$ with no cards remaining.In the fifth test, one card is not enough to build any pyramids.
A card pyramid of height $$$1$$$ is constructed by resting two cards against each other. For $$$h&gt;1$$$, a card pyramid of height $$$h$$$ is constructed by placing a card pyramid of height $$$h-1$$$ onto a base. A base consists of $$$h$$$ pyramids of height $$$1$$$, and $$$h-1$$$ cards on top. For example, card pyramids of heights $$$1$$$, $$$2$$$, and $$$3$$$ look as follows: You start with $$$n$$$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?
For each test case output a single integerΒ β€” the number of pyramids you will have constructed in the end.
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)Β β€” the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^9$$$)Β β€” the number of cards. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^9$$$.
standard output
standard input
Python 3
Python
1,100
train_004.jsonl
2d729004b7d23032344e31d1d6889413
256 megabytes
["5\n3\n14\n15\n24\n1"]
PASSED
def p(n): h=(-1+(1+24*n)**0.5)/6 return int(h) t=int(input()) for i in range(t): c=0 n=int(input()) while n>1: x=p(n) c+=1 n-=(3*x*x+x)/2 print(c)
1588775700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["9", "240", "24"]
ab65207f0b334276f58e0d2e79b0b44d
NoteIn the first test, the following ways to choose the colors are suitable: $$$[1, 1, 1]$$$; $$$[2, 2, 2]$$$; $$$[3, 3, 3]$$$; $$$[1, 2, 3]$$$; $$$[1, 3, 2]$$$; $$$[2, 1, 3]$$$; $$$[2, 3, 1]$$$; $$$[3, 1, 2]$$$; $$$[3, 2, 1]$$$.
You are given $$$n$$$ points on the plane, the coordinates of the $$$i$$$-th point are $$$(x_i, y_i)$$$. No two points have the same coordinates.The distance between points $$$i$$$ and $$$j$$$ is defined as $$$d(i,j) = |x_i - x_j| + |y_i - y_j|$$$.For each point, you have to choose a color, represented by an integer from $$$1$$$ to $$$n$$$. For every ordered triple of different points $$$(a,b,c)$$$, the following constraints should be met: if $$$a$$$, $$$b$$$ and $$$c$$$ have the same color, then $$$d(a,b) = d(a,c) = d(b,c)$$$; if $$$a$$$ and $$$b$$$ have the same color, and the color of $$$c$$$ is different from the color of $$$a$$$, then $$$d(a,b) &lt; d(a,c)$$$ and $$$d(a,b) &lt; d(b,c)$$$. Calculate the number of different ways to choose the colors that meet these constraints.
Print one integerΒ β€” the number of ways to choose the colors for the points. Since it can be large, print it modulo $$$998244353$$$.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of points. Then $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^8$$$). No two points have the same coordinates (i. e. if $$$i \ne j$$$, then either $$$x_i \ne x_j$$$ or $$$y_i \ne y_j$$$).
standard output
standard input
PyPy 3-64
Python
2,400
train_083.jsonl
b71657011183ffa8b5981a5ce418f275
512 megabytes
["3\n1 0\n3 0\n2 1", "5\n1 2\n2 4\n3 4\n4 4\n1 3", "4\n1 0\n3 0\n2 1\n2 0"]
PASSED
import collections import functools import heapq import random import bisect import itertools import math import os from io import BytesIO, IOBase from sys import setrecursionlimit, stderr, stdin, stdout from collections import defaultdict setrecursionlimit(20000) def get_ints(): return list(map(int, input().split())) def get_int(): return int(input()) def get_string(): return "".join(list(input().rstrip())) def get_chars(): return list(input().rstrip()) def eprint(*args): print(*args, sep=", ", file=stderr) def dfist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def rel1(a, b, c): return dfist(a, b) == dfist(a, c) == dfist(b, c) def rel2(a, b, c): return dfist(a, b) < dfist(a, c) and dfist(a, b) < dfist(b, c) def falfact(m, n, MOD): if n == 0: return 1 return (math.factorial(m) // math.factorial(m - n)) % MOD def comb(n, k, MOD): return ( math.factorial(n) // (math.factorial(k) * math.factorial(n - k)) ) % MOD MOD = 998244353 # replace me N = 200 # replace me fact = [0 for _ in range(N)] invfact = [0 for _ in range(N)] fact[0] = 1 for i in range(1, N): fact[i] = fact[i - 1] * i % MOD invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD) for i in range(N - 2, -1, -1): invfact[i] = invfact[i + 1] * (i + 1) % MOD def nCk(n, k): if k < 0 or n < k: return 0 else: return (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD def main(): n = get_int() points = [] dist = [[0] * n for _ in range(n)] xy = [get_ints() for _ in range(n)] for i in range(n): for j in range(n): dx = xy[i][0] - xy[j][0] dy = xy[i][1] - xy[j][1] dist[i][j] = dist[j][i] = sum(map(abs, (dx, dy))) min_se = [set() for _ in range(n)] hash_ = [random.randrange(1, 1 << 63) for _ in range(n)] min_hash = [0 for _ in range(n)] cnt = [0] * n for i in range(n): min_ = 1 << 30 for j in range(n): if i != j and dist[i][j] < min_: min_ = dist[i][j] for j in range(n): if dist[i][j] == min_: min_se[i].add(j) min_hash[i] ^= hash_[j] cnt[i] += 1 cliques = [0] * (5) for i in range(n): if cnt[i] in (1, 2, 3) and i > max(min_se[i]): target = hash_[i] ^ min_hash[i] if all(hash_[x] ^ min_hash[x] == target for x in min_se[i]): cliques[cnt[i] + 1] += 1 ans = 0 two, three, four = cliques[2], cliques[3], cliques[4] for a in range(two + 1): for b in range(three + 1): for c in range(four + 1): x = n - a - 2 * b - 3 * c y = n - (a + b + c) tmp = nCk(n, x) * fact[x] % MOD tmp *= nCk(two, a) * nCk(three, b) * nCk(four, c) % MOD if n - x - y > 0: tmp *= nCk(n - x, a + b + c) * fact[a + b + c] % MOD ans = (ans + tmp) % MOD print(ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") stdin = IOWrapper(stdin) # type: ignore stdout = IOWrapper(stdout) # type: ignore input = lambda: stdin.readline().rstrip("\r\n") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() # endregion if __name__ == "__main__": main()
1655044500
[ "geometry", "math", "graphs" ]
[ 0, 1, 1, 1, 0, 0, 0, 0 ]
1 second
["1\nABC", "2\nADBADC"]
b9766f25c8ae179c30521770422ce18b
NoteThe second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: "ADBADC", "ADDABC", "CDAABD", "CDBAAD", "CDBADA", "CDDABA", "DDAABC", "DDBAAC". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is "ADBADC".
String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk &lt; qk for some k (1 ≀ k ≀ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.
In the first line print z β€” the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.
The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.
output.txt
input.txt
Python 2
Python
1,800
train_021.jsonl
b4313b4d314bc0ed1619614b6b1fc10a
256 megabytes
["ABA\nCBA", "CDBABC\nADCABD"]
PASSED
import sys from collections import Counter def io(): sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") def main(): s = sys.stdin.readline().strip() t = sys.stdin.readline().strip() sc = [0] * 26 tc = [0] * 26 n = len(s) for i, j in zip(s, t): sc[ord(i)-ord('A')] += 1 tc[ord(j)-ord('A')] += 1 tf = [] for i in xrange(25, -1, -1): if sc[i] < tc[i]: tf.extend([i] * (tc[i] - sc[i])) print len(tf) ard = list(s) sc_ = [0] * 26 for i in xrange(n): a = ord(s[i]) - ord('A') sc_[a] += 1 if sc[a] > tc[a]: if a >= tf[-1] or sc_[a] > tc[a]: ard[i] = chr(ord('A')+tf.pop()) sc[a] -= 1 sc_[a] -= 1 if not tf: break sys.stdout.write("".join(ard)) print io() main()
1355047200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1.5 seconds
["1\n2", "0", "2\n0 2"]
6a9f683dee69a7be2d06ec6646970f19
NoteIn the first sample, the first bag and the second bag contain $$$\{3,4\}$$$ and $$$\{0,1,2\}$$$, respectively. Ajs can obtain every residue modulo $$$5$$$ except the residue $$$2$$$: $$$ 4+1 \equiv 0, \, 4+2 \equiv 1, \, 3+0 \equiv 3, \, 3+1 \equiv 4 $$$ modulo $$$5$$$. One can check that there is no choice of elements from the first and the second bag which sum to $$$2$$$ modulo $$$5$$$.In the second sample, the contents of the first bag are $$$\{5,25,125,625\}$$$, while the second bag contains all other nonnegative integers with at most $$$9$$$ decimal digits. Every residue modulo $$$1\,000\,000\,000$$$ can be obtained as a sum of an element in the first bag and an element in the second bag.
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is $$$\{0,1,…,M-1\}$$$, for some positive integer $$$M$$$. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo $$$M$$$.What are the residues modulo $$$M$$$ that Ajs cannot obtain with this action?
In the first line, output the cardinality $$$K$$$ of the set of residues modulo $$$M$$$ which Ajs cannot obtain. In the second line of the output, print $$$K$$$ space-separated integers greater or equal than zero and less than $$$M$$$, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If $$$K$$$=0, do not output the second line.
The first line contains two positive integer $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) and $$$M$$$ ($$$N+1 \leq M \leq 10^{9}$$$), denoting the number of the elements in the first bag and the modulus, respectively. The second line contains $$$N$$$ nonnegative integers $$$a_1,a_2,\ldots,a_N$$$ ($$$0 \leq a_1&lt;a_2&lt; \ldots&lt; a_N&lt;M$$$), the contents of the first bag.
standard output
standard input
PyPy 3
Python
2,400
train_008.jsonl
428b57ae525cf5453355d17acd8e2c69
256 megabytes
["2 5\n3 4", "4 1000000000\n5 25 125 625", "2 4\n1 3"]
PASSED
import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) a = list(map(int, input().split())) + [0]*500000 ans_S = 0 a[n] = a[0] + m s = [0]*600600 for i in range(n): s[i] = a[i + 1] - a[i] s[n] = -1 for i in range(n): s[2*n - i] = s[i] for i in range(2*n + 1, 3*n + 1): s[i] = s[i - n] l, r = 0, 0 z = [0]*600600 for i in range(1, 3*n + 1): if i < r: z[i] = z[i - l] while i + z[i] <= 3*n and (s[i + z[i]] == s[z[i]]): z[i] += 1 if i + z[i] > r: l = i r = i + z[i] ans = [] for i in range(n + 1, 2*n + 1): if z[i] < n: continue ans_S += 1 ans.append((a[0] + a[2*n - i + 1]) % m) ans.sort() print(ans_S) print(*ans) return if __name__=="__main__": main()
1537612500
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
3 seconds
["SCAN 1 2\n\nDIG 1 2\n\nSCAN 2 2\n\nDIG 1 1\n\nDIG 1 3"]
222fbf0693a4c1d2dd7a07d458d78a54
null
This is an interactive problem.There is a grid of $$$n\times m$$$ cells. Two treasure chests are buried in two different cells of the grid. Your task is to find both of them. You can make two types of operations: DIG $$$r$$$ $$$c$$$: try to find the treasure in the cell $$$(r, c)$$$. The interactor will tell you if you found the treasure or not. SCAN $$$r$$$ $$$c$$$: scan from the cell $$$(r, c)$$$. The result of this operation is the sum of Manhattan distances from the cell $$$(r, c)$$$ to the cells where the treasures are hidden. Manhattan distance from a cell $$$(r_1, c_1)$$$ to a cell $$$(r_2, c_2)$$$ is calculated as $$$|r_1 - r_2| + |c_1 - c_2|$$$. You need to find the treasures in at most 7 operations. This includes both DIG and SCAN operations in total. To solve the test you need to call DIG operation at least once in both of the cells where the treasures are hidden.
null
null
standard output
standard input
PyPy 3-64
Python
2,200
train_091.jsonl
d62c280e3a11622b42b45ff467d1f68d
512 megabytes
["1\n2 3\n\n1\n\n1\n\n3\n\n0\n\n1"]
PASSED
import sys input = sys.stdin.readline def d(p1, p2): return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) o1 = (14, 1) o2 = (13, 3) def query(x, y): print('SCAN',x + 1,y + 1) sys.stdout.flush() return int(input()) #return d(o1, (x, y)) + d(o2, (x, y)) def cout(x1, x2, y1, t2): print('DIG',x1 + 1,y1 + 1) sys.stdout.flush() if int(input()) == 1: print('DIG',x2 + 1,y2 + 1) sys.stdout.flush() assert int(input()) == 1 else: print('DIG',x1 + 1,y2 + 1) print('DIG',x2 + 1,y1 + 1) sys.stdout.flush() assert int(input()) == 1 assert int(input()) == 1 t = int(input()) for _ in range(t): o1 = (5 + _//2, 1 + _//3) o2 = (6, 3) n, m = map(int, input().split()) #n, m = 16, 15 tl = query(0, 0) #tr = query(n - 1, 0) bl = query(0, m - 1) sX = (tl + bl - 2 * (m - 1))//2 sY = tl - sX #sY = tl + tr - 2 * (n - 1) ml = query(0, sY//2) diffY = ml - sX assert diffY % 2 == sY % 2 y1 = (sY//2 + (diffY + 1)//2) y2 = (sY//2 - (diffY//2)) tm = query(sX//2, 0) diffX = tm - sY assert diffX % 2 == sX % 2 x1 = (sX//2 + (diffX + 1)//2) x2 = (sX//2 - (diffX//2)) #print(o1, o2) cout(x1, x2, y1, y2)
1649837100
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2\n3\n0", "0\n2\n1\n2\n5\n12\n5\n0\n0\n2"]
401708ea0b55b933ad553977011460b4
null
The Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by $$$n$$$ castles, the $$$i$$$-th castle is defended by $$$a_i$$$ soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by $$$x$$$ (or sets it to $$$0$$$ if there are already less than $$$x$$$ defenders); an infantry attack decreases the number of defenders in the targeted castle by $$$y$$$ (or sets it to $$$0$$$ if there are already less than $$$y$$$ defenders); a cavalry attack decreases the number of defenders in the targeted castle by $$$z$$$ (or sets it to $$$0$$$ if there are already less than $$$z$$$ defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or $$$0$$$, if the Black King can launch the last attack no matter how the White King acts).
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers $$$n$$$, $$$x$$$, $$$y$$$ and $$$z$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le x, y, z \le 5$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^{18}$$$). It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 2
Python
2,500
train_045.jsonl
5bbed403e4a9574db7d387bffcb23ffd
512 megabytes
["3\n2 1 3 4\n7 6\n1 1 2 3\n1\n1 1 2 2\n3", "10\n6 5 4 5\n2 3 2 3 1 3\n1 5 2 3\n10\n4 4 2 3\n8 10 8 5\n2 2 1 4\n8 5\n3 5 3 5\n9 2 10\n4 5 5 5\n2 10 4 2\n2 3 1 4\n1 10\n3 1 5 3\n9 8 7\n2 5 4 5\n8 8\n3 5 1 4\n5 5 10"]
PASSED
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 t = inp[ii]; ii += 1 for _ in range(t): n = inp[ii]; ii += 1 x = inp[ii]; ii += 1 y = inp[ii]; ii += 1 z = inp[ii]; ii += 1 A = inp[ii: ii + n]; ii += n memor = {} def mexor(val, i): if val <= 0: return 0 if ((val, i)) not in memor: A = [] A.append(mexor(val - x, 0)) if i != 1: A.append(mexor(val - y, 1)) if i != 2: A.append(mexor(val - z, 2)) if 0 not in A: ans = 0 elif 1 not in A: ans = 1 elif 2 not in A: ans = 2 else: ans = 3 memor[(val, i)] = ans return memor[(val, i)] AA = [mexor(i, 0) for i in range(250)] BB = [mexor(i, 1) for i in range(250)] CC = [mexor(i, 2) for i in range(250)] aper = 70 while aper and AA[125 : 125 + aper] != AA[125 + aper : 125 + 2 * aper]: aper -= 1 bper = 70 while bper and BB[125 : 125 + bper] != BB[125 + bper : 125 + 2 * bper]: bper -= 1 cper = 70 while cper and CC[125 : 125 + cper] != CC[125 + cper : 125 + 2 * cper]: cper -= 1 def mexor(val, i): if val <= 0: return 0 if i == 0: if val < 250: return AA[val] else: return AA[125 + (val - 125) % aper] elif i == 1: if val < 250: return BB[val] else: return BB[125 + (val - 125) % bper] else: if val < 250: return CC[val] else: return CC[125 + (val - 125) % cper] xor = 0 for a in A: xor ^= mexor(a, 0) ways = 0 for a in A: newxor = xor ^ mexor(a, 0) if mexor(a - x, 0) == newxor: ways += 1 if mexor(a - y, 1) == newxor: ways += 1 if mexor(a - z, 2) == newxor: ways += 1 print ways
1583764500
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["Tonya\nBurenka\nBurenka\nTonya\nBurenka\nBurenka"]
13611e428c24b94023811063bbbfa077
NoteIn the first case, Burenka has no move, so Tonya wins.In the second case, Burenka can move $$$3$$$ cells to the right, after which Tony will not be able to make a move, which means that Burenka wins.In the third case, Burenka can move $$$5$$$ squares to the right. Then we can say that we have a game on a board of $$$1 \times 5$$$ cells, and Tonya is the first player. In such game the second player wins, so in the original one Burenka will win.
Burenka and Tonya are playing an old Buryat game with a chip on a board of $$$n \times m$$$ cells.At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any odd number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way). Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.
For each test case print a single line β€” the name of the winner of the game ("Burenka" or "Tonya").
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) β€” the number of test cases. The following is a description of the input data sets. The only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^9$$$) β€” the dimensions of the game board.
standard output
standard input
Python 3
Python
800
train_090.jsonl
7e8cf8df85bdfa5820fd62bd2b7b1c84
256 megabytes
["6\n\n1 1\n\n1 4\n\n5 6\n\n2 2\n\n6 3\n\n999999999 1000000000"]
PASSED
for _ in range(int(input())): n,m= map(int,input().split()) if (m-1)%2==0 and n==1: print("Tonya") elif (m-1)%2==0 : if (n)%2==0: print("Burenka") else: print("Tonya") elif (m-1)%2 and n==1: print("Burenka") else: if (n)%2: print("Burenka") else: print("Tonya")
1660660500
[ "math", "games" ]
[ 1, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "3"]
075988685fa3f9b20bd215037c504a4f
NoteIn the first example the number will be $$$11010100100$$$ after performing one operation. It has remainder $$$100$$$ modulo $$$100000$$$.In the second example the number will be $$$11010100010$$$ after performing three operations. It has remainder $$$10$$$ modulo $$$100000$$$.
You are given a huge decimal number consisting of $$$n$$$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers $$$0 \le y &lt; x &lt; n$$$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.
Print one integer β€” the minimum number of operations you should perform to obtain the number having remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.
The first line of the input contains three integers $$$n, x, y$$$ ($$$0 \le y &lt; x &lt; n \le 2 \cdot 10^5$$$) β€” the length of the number and the integers $$$x$$$ and $$$y$$$, respectively. The second line of the input contains one decimal number consisting of $$$n$$$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.
standard output
standard input
Python 3
Python
1,100
train_005.jsonl
2266f91222a7852d12409d4589aa0db8
256 megabytes
["11 5 2\n11010100101", "11 5 1\n11010100101"]
PASSED
n, x, y= map(int, input().split()) a=input() c=0 for i in range(n-1, n-x-1, -1): if a[i]=='1': c+=1 if a[n-y-1]=='0': c+=1 else: c-=1 print(c)
1557844500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["6"]
fba0d6cb50c858187f67ac3cac550f0d
NoteIn the example, one of the possible Hamiltonian cycles with length 6 is (1, 1) (1, 2) (2, 1) (2, 2). There does not exist any other Hamiltonian cycle with a length greater than 6.The Manhattan distance between two cities (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.
There are n cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all n cities. The length of this Hamiltonian cycle is defined as the sum of the distances between adjacent cities in the permutation plus the distance between the first and final city in the permutation. Please compute the longest possible length of a Hamiltonian cycle of the given cities.
A single line denoting the longest possible length of a Hamiltonian cycle of the given cities. You should not output the cycle, only its length. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
The first line contains an integer n (3 ≀ n ≀ 105). Then n lines follow, each consisting of two integers xi and yi (0 ≀ xi, yi ≀ 109), denoting the coordinates of a city. All given points will be distinct.
standard output
standard input
Python 2
Python
3,100
train_044.jsonl
a185367ecb5d48f57e758425edc618ca
256 megabytes
["4\n1 1\n1 2\n2 1\n2 2"]
PASSED
import sys n = int(raw_input()) coordinates = [] xs = [] ys = [] for i in range(n): x, y = map(int, raw_input().split()) coordinates.append(((x, i), (y, i))) xs.append((x, i)) ys.append((y, i)) xs = sorted(xs) ys = sorted(ys) amt = [[0] * 2 for _ in range(2)] medians = 0 for x, y in coordinates: if n % 2 and x == xs[n/2]: # median medians += 1 continue if n % 2 and y == ys[n/2]: # median medians += 1 continue amt[x < xs[n/2]][y < ys[n/2]] += 1 def CalcuHalf(arr): res = 0 for a, _ in arr[len(arr)/2:]: res += a for a, _ in arr[:len(arr)/2]: res -= a return res def PossibleAll(): def CalculateMax(arr): woot = arr + arr woot = sorted(woot) return CalcuHalf(woot) print CalculateMax(xs) + CalculateMax(ys) sys.exit(0) if amt[0][0] + amt[1][1] == 0 or amt[1][0] + amt[0][1] == 0: PossibleAll() if medians == 2: PossibleAll() if medians == 0: def Proc(arr): zs = sorted(arr + arr) zs[n-1], zs[n] = zs[n], zs[n-1] return CalcuHalf(zs) print max([Proc(xs) + CalcuHalf(sorted(ys+ys)), Proc(ys) + CalcuHalf(sorted(xs+xs))]) else: def Proc(arr): zs = sorted(arr + arr) zs[n-2], zs[n] = zs[n], zs[n-2] az = sorted(arr + arr) az[n-1], az[n+1] = az[n+1], az[n-1] return max([CalcuHalf(zs), CalcuHalf(az)]) print max([Proc(xs) + CalcuHalf(sorted(ys+ys)), Proc(ys) + CalcuHalf(sorted(xs+xs))])
1374327000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0\n0\n1\n3"]
f80dc7b12479551b857408f4c29c276b
NoteLet us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this: The land lot for the construction will look in the following way: We can choose a subset of roads in three ways: In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1.
A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.In the constructing process m bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The i-th road connects the junctions with numbers ai and bi.Track is the route with the following properties: The route is closed, that is, it begins and ends in one and the same junction. The route contains at least one road. The route doesn't go on one road more than once, however it can visit any junction any number of times. Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.Two ski bases are considered different if they consist of different road sets.After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.
Print m lines: the i-th line should represent the number of ways to build a ski base after the end of construction of the road number i. The numbers should be printed modulo 1000000009 (109 + 9).
The first line contains two integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105). They represent the number of junctions and the number of roads correspondingly. Then on m lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi) β€” the numbers of the connected junctions. There could be more than one road between a pair of junctions.
standard output
standard input
Python 2
Python
2,300
train_000.jsonl
83c284ab834ac4a8c1a887a807ea3ba9
256 megabytes
["3 4\n1 3\n2 3\n1 2\n1 2"]
PASSED
import random def FindSet(dsu, x): if dsu[x] != x: dsu[x] = FindSet(dsu, dsu[x]) return dsu[x] def Unite(dsu, x, y): x = FindSet(dsu, x) y = FindSet(dsu, y) if random.random() > 0.5: dsu[x] = y else: dsu[y] = x mod = 10 ** 9 + 9 n, m = map(int, raw_input().split()) dsu = range(n + 1) res = 1 for i in xrange(m): u, v = map(int, raw_input().split()) if FindSet(dsu, u) != FindSet(dsu, v): print res - 1 else: res = (res * 2) % mod print res - 1 Unite(dsu, u, v)
1308582000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES", "NO"]
cf86add6c92fa8a72b8e23efbdb38613
NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations: Write parity(a) to the end of a. For example, . Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
The first line contains the string a and the second line contains the string b (1 ≀ |a|, |b| ≀ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
standard output
standard input
Python 3
Python
1,700
train_002.jsonl
fe31b34b34844fa376d94e7d88cf5972
256 megabytes
["01011\n0110", "0011\n1110"]
PASSED
a=input() b=input() tot1=0 tot2=0 for i in a: tot1+=int(i) for i in b: tot2+=int(i) if tot1+tot1%2>=tot2: print("YES") else: print("NO")
1366385400
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["33.0476190476", "20.2591405923", "15.9047592939"]
4aec5810e9942ae2fbe3ecd4fff3b468
NoteA visualization of the path and the board from example 2 is as follows: The tile with an 'S' is the starting tile and the tile with an 'E' is the Goal.For the first example, there are no ladders.For the second example, the board looks like the one in the right part of the image (the ladders have been colored for clarity).It is possible for ladders to overlap, as is the case with the red and yellow ladders and green and blue ladders. It is also possible for ladders to go straight to the top, as is the case with the black and blue ladders. However, it is not possible for ladders to go any higher (outside of the board). It is also possible that two ladders lead to the same tile, as is the case with the red and yellow ladders. Also, notice that the red and yellow ladders lead to the tile with the orange ladder. So if the player chooses to climb either of the red and yellow ladders, they will not be able to climb the orange ladder. Finally, notice that the green ladder passes through the starting tile of the blue ladder. The player cannot transfer from the green ladder to the blue ladder while in the middle of climbing the green ladder.
Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game β€” "Snakes and Ladders". Unfortunately, she already killed all the snakes, so there are only ladders left now. The game is played on a $$$10 \times 10$$$ board as follows: At the beginning of the game, the player is at the bottom left square. The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends. The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path. During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is $$$r$$$. If the Goal is less than $$$r$$$ squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly $$$r$$$ squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player chooses whether or not to climb up that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn. Some squares have a ladder in them. Ladders are only placed vertically β€” each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the square containing the top of the ladder also contains the bottom of another ladder, she is not allowed to use that second ladder. The numbers on the faces of the dice are 1, 2, 3, 4, 5, and 6, with each number having the same probability of being shown. Please note that: it is possible for ladders to overlap, but the player cannot switch to the other ladder while in the middle of climbing the first one; it is possible for ladders to go straight to the top row, but not any higher; it is possible for two ladders to lead to the same tile; it is possible for a ladder to lead to a tile that also has a ladder, but the player will not be able to use that second ladder if she uses the first one; the player can only climb up ladders, not climb down. Hyakugoku wants to finish the game as soon as possible. Thus, on each turn she chooses whether to climb the ladder or not optimally. Help her to determine the minimum expected number of turns the game will take.
Print only one line containing a single floating-point number β€” the minimum expected number of turns Hyakugoku can take to finish the game. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$.
Input will consist of ten lines. The $$$i$$$-th line will contain 10 non-negative integers $$$h_{i1}, h_{i2}, \dots, h_{i10}$$$. If $$$h_{ij}$$$ is $$$0$$$, then the tile at the $$$i$$$-th row and $$$j$$$-th column has no ladder. Otherwise, the ladder at that tile will have a height of $$$h_{ij}$$$, i.e. climbing it will lead to the tile $$$h_{ij}$$$ rows directly above. It is guaranteed that $$$0 \leq h_{ij} &lt; i$$$. Also, the first number of the first line and the first number of the last line always contain $$$0$$$, i.e. the Goal and the starting tile never have ladders.
standard output
standard input
Python 3
Python
2,300
train_056.jsonl
9c712aacde835c4521ec528c97b91416
256 megabytes
["0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0", "0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 3 0 0 0 4 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 4 0 0 0\n0 0 3 0 0 0 0 0 0 0\n0 0 4 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 9", "0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 6 6 6 6 6 6 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0"]
PASSED
def pos(x, y): if y & 1: return y * w + w - 1 - x return y * w + x CUBE = 6 h, w = 10, 10 n = h * w grid = [] for y in range(h): line = list(map(int, input().split())) grid.append(line) grid.reverse() # print(*grid, sep='\n') to = [0] * n for y in range(h): for x in range(w): y1 = y + grid[y][x] if y1 != y: # print(f"({x}, {y}) --> ({x}, {y1})", pos(x, y), pos(x, y1)) to[pos(x, y)] = pos(x, y + grid[y][x]) # print(to) exp = [0] * (n + CUBE) for i in range(n - 2, -1, -1): exp[i] = 1 for j in range(1, CUBE + 1): exp_to = exp[i + j] / CUBE if i + j < n and to[i + j]: exp_to = min(exp_to, exp[to[i + j]] / CUBE) exp[i] += exp_to if i + CUBE >= n: exp[i] = CUBE * exp[i] / (n - 1 - i) # print(*[f"{x:.1f}" for x in exp[:n]]) print(f"{exp[0]:.16f}")
1572618900
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
2 seconds
["3\n1\n0", "0\n0\n1"]
2cd91be317328fec207da6773ead4541
NoteThe first example illustrates an example from the statement.$$$f([7, 3, 1, 7]) = 1$$$: sequence of operations is $$$[7, 3, 1, 7] \to [(7 + 3)\bmod 10, (1 + 7)\bmod 10]$$$ $$$=$$$ $$$[0, 8]$$$ and one candy as $$$7 + 3 \ge 10$$$ $$$\to$$$ $$$[(0 + 8) \bmod 10]$$$ $$$=$$$ $$$[8]$$$, so we get only $$$1$$$ candy.$$$f([9]) = 0$$$ as we don't perform operations with it.
Consider a sequence of digits of length $$$2^k$$$ $$$[a_1, a_2, \ldots, a_{2^k}]$$$. We perform the following operation with it: replace pairs $$$(a_{2i+1}, a_{2i+2})$$$ with $$$(a_{2i+1} + a_{2i+2})\bmod 10$$$ for $$$0\le i&lt;2^{k-1}$$$. For every $$$i$$$ where $$$a_{2i+1} + a_{2i+2}\ge 10$$$ we get a candy! As a result, we will get a sequence of length $$$2^{k-1}$$$.Less formally, we partition sequence of length $$$2^k$$$ into $$$2^{k-1}$$$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $$$\ldots$$$, the last pair consists of the ($$$2^k-1$$$)-th and ($$$2^k$$$)-th numbers. For every pair such that sum of numbers in it is at least $$$10$$$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $$$10$$$ (and don't change the order of the numbers).Perform this operation with a resulting array until it becomes of length $$$1$$$. Let $$$f([a_1, a_2, \ldots, a_{2^k}])$$$ denote the number of candies we get in this process. For example: if the starting sequence is $$$[8, 7, 3, 1, 7, 0, 9, 4]$$$ then:After the first operation the sequence becomes $$$[(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10]$$$ $$$=$$$ $$$[5, 4, 7, 3]$$$, and we get $$$2$$$ candies as $$$8 + 7 \ge 10$$$ and $$$9 + 4 \ge 10$$$.After the second operation the sequence becomes $$$[(5 + 4)\bmod 10, (7 + 3)\bmod 10]$$$ $$$=$$$ $$$[9, 0]$$$, and we get one more candy as $$$7 + 3 \ge 10$$$. After the final operation sequence becomes $$$[(9 + 0) \bmod 10]$$$ $$$=$$$ $$$[9]$$$. Therefore, $$$f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$$$ as we got $$$3$$$ candies in total.You are given a sequence of digits of length $$$n$$$ $$$s_1, s_2, \ldots s_n$$$. You have to answer $$$q$$$ queries of the form $$$(l_i, r_i)$$$, where for $$$i$$$-th query you have to output $$$f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}])$$$. It is guaranteed that $$$r_i-l_i+1$$$ is of form $$$2^k$$$ for some nonnegative integer $$$k$$$.
Output $$$q$$$ lines, in $$$i$$$-th line output single integerΒ β€” $$$f([s_{l_i}, s_{l_i + 1}, \ldots, s_{r_i}])$$$, answer to the $$$i$$$-th query.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the length of the sequence. The second line contains $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_i \le 9$$$). The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$)Β β€” the number of queries. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$)Β β€” $$$i$$$-th query. It is guaranteed that $$$r_i-l_i+1$$$ is a nonnegative integer power of $$$2$$$.
standard output
standard input
Python 3
Python
1,400
train_011.jsonl
0f1b7d072884b3b1ff95035d569a8df9
256 megabytes
["8\n8 7 3 1 7 0 9 4\n3\n1 8\n2 5\n7 7", "6\n0 1 2 3 3 5\n3\n1 2\n1 4\n3 6"]
PASSED
import sys #sys.stdin = open('in', 'r') n = int(input()) a = [int(x) for x in input().split()] q = int(input()) sm = [0] for i in range(n): sm.append(sm[-1]+a[i]) for qi in range(q): l,r = map(int, input().split()) print((sm[r]-sm[l-1]) // 10) #sys.stdout.write('YES\n') #sys.stdout.write(f'{res}\n') #sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')
1562339100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\n3 2 4 5 1", "NO", "NO"]
9dfd415d4ed6247d6bee84e8a6558543
NoteThe order of patterns after the rearrangement in the first example is the following: aaaa __b_ ab__ _bcd _b_d Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed $$$p[4]$$$. The second string matches __b_ and ab__, the first of them is __b_, that is $$$p[2]$$$. The last string matches _bcd and _b_d, the first of them is _bcd, that is $$$p[5]$$$.The answer to that test is not unique, other valid orders also exist.In the second example cba doesn't match __c, thus, no valid order exists.In the third example the order (a_, _b) makes both strings match pattern $$$1$$$ first and the order (_b, a_) makes both strings match pattern $$$2$$$ first. Thus, there is no order that produces the result $$$1$$$ and $$$2$$$.
You are given $$$n$$$ patterns $$$p_1, p_2, \dots, p_n$$$ and $$$m$$$ strings $$$s_1, s_2, \dots, s_m$$$. Each pattern $$$p_i$$$ consists of $$$k$$$ characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string $$$s_j$$$ consists of $$$k$$$ lowercase Latin letters.A string $$$a$$$ matches a pattern $$$b$$$ if for each $$$i$$$ from $$$1$$$ to $$$k$$$ either $$$b_i$$$ is a wildcard character or $$$b_i=a_i$$$.You are asked to rearrange the patterns in such a way that the first pattern the $$$j$$$-th string matches is $$$p[mt_j]$$$. You are allowed to leave the order of the patterns unchanged.Can you perform such a rearrangement? If you can, then print any valid order.
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the $$$j$$$-th string matches is $$$p[mt_j]$$$. Otherwise, print "YES" in the first line. The second line should contain $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$Β β€” the order of the patterns. If there are multiple answers, print any of them.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 10^5$$$, $$$1 \le k \le 4$$$)Β β€” the number of patterns, the number of strings and the length of each pattern and string. Each of the next $$$n$$$ lines contains a patternΒ β€” $$$k$$$ characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct. Each of the next $$$m$$$ lines contains a stringΒ β€” $$$k$$$ lowercase Latin letters, and an integer $$$mt$$$ ($$$1 \le mt \le n$$$)Β β€” the index of the first pattern the corresponding string should match.
standard output
standard input
PyPy 3-64
Python
2,300
train_102.jsonl
206439a1f8c4c9a5176bfc9ca44841ee
256 megabytes
["5 3 4\n_b_d\n__b_\naaaa\nab__\n_bcd\nabcd 4\nabba 2\ndbcd 5", "1 1 3\n__c\ncba 1", "2 2 2\na_\n_b\nab 1\nab 2"]
PASSED
import sys input = sys.stdin.buffer.readline def toposort(graph): res, found = [], [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: res.append(~node) elif not found[node]: found[node] = 1 stack.append(~node) stack += graph[node] # cycle check for node in res: if any(found[nei] for nei in graph[node]): return None found[node] = 0 return res[::-1] def kahn(graph): n = len(graph) indeg, idx = [0] * n, [0] * n for i in range(n): for e in graph[i]: indeg[e] += 1 q, res = [], [] for i in range(n): if indeg[i] == 0: q.append(i) # heappush(q, -i) nr = 0 while q: res.append(q.pop()) # res.append(-heappop(q)) idx[res[-1]], nr = nr, nr + 1 for e in graph[res[-1]]: indeg[e] -= 1 if indeg[e] == 0: q.append(e) # heappush(q, -e) return res, idx, nr == n def make_string(s): k = len(s) answer = 0 for i in range(k): if s[i]=='_': entry = 26 else: entry = ord(s[i])-ord('a') answer = 27*answer+entry return answer def make_strings(s): k = len(s) answer = [0] for i in range(k): answer2 = [] for x in answer: for y in [26, ord(s[i])-ord('a')]: answer2.append(27*x+y) answer = answer2 return answer def process(P, S): n = len(P) m = len(S) k = len(P[0]) d = [[None, None] for i in range(27**k)] for i in range(n): x = make_string(P[i]) d[x][0] = i+1 graph = [[] for i in range(n)] for i in range(m): s1, x1 = S[i] works = False for s2 in make_strings(s1): if d[s2][0] is not None: y = d[s2][0] if y != x1: graph[x1-1].append(y-1) if y==x1: works = True if not works: sys.stdout.write('NO\n') return a, b, c = kahn(graph) if not c: sys.stdout.write('NO\n') return answer = [None for i in range(n)] for i in range(n): answer[b[i]] = i+1 sys.stdout.write('YES\n') answer = ' '.join(map(str, answer)) sys.stdout.write(f'{answer}\n') n, m, k = [int(x) for x in input().split()] P = [] for i in range(n): p = input().decode().strip() P.append(p) S = [] for i in range(m): s, x = input().decode().strip().split() x = int(x) S.append([s, x]) process(P, S)
1611930900
[ "strings", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 1, 0 ]
3 seconds
["3", "-1", "0"]
99dd00f4840188d4d96260100b20e9c9
NoteIn the first example, you can sort the permutation in three operations: Make operation 1: $$$3, 6, 5, 2, 1, 4$$$. Make operation 2: $$$2, 1, 4, 3, 6, 5$$$. Make operation 1: $$$1, 2, 3, 4, 5, 6$$$.
The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.There is a permutation $$$p_i$$$ of numbers from 1 to $$$2n$$$. You can make two types of operations. Swap $$$p_1$$$ and $$$p_2$$$, $$$p_3$$$ and $$$p_4$$$, ..., $$$p_{2n-1}$$$ and $$$p_{2n}$$$. Swap $$$p_1$$$ and $$$p_{n+1}$$$, $$$p_2$$$ and $$$p_{n+2}$$$, ..., $$$p_{n}$$$ and $$$p_{2n}$$$. The task is to find the minimal number of operations required to sort the given permutation.The Knight was not that smart actually, but quite charming, so the princess asks you to help him to solve the King's task.
Print one integerΒ β€” the minimal number of operations required to sort the permutation. If it is impossible to sort the permutation using these operations, print $$$-1$$$.
The first line contains the integer $$$n$$$ ($$$1\le n\le 1000$$$). The second line contains $$$2n$$$ integers $$$p_i$$$Β β€” the permutation of numbers from 1 to $$$2n$$$.
standard output
standard input
Python 3
Python
1,200
train_099.jsonl
88c937208120c697ea4ca68be9e130fe
512 megabytes
["3\n6 3 2 5 4 1", "2\n3 4 2 1", "4\n1 2 3 4 5 6 7 8"]
PASSED
def print_result(arrey): for el in arrey: print(el, end=" ") def swap_p1_p2(arrey, half_length): for i in range(0, len(arrey) - 1, 2): arrey[i], arrey[i + 1] = arrey[i + 1], arrey[i] return arrey def swap_p1_pn1(arrey, half_length): for i in range(len(arrey) // 2): arrey[i], arrey[i + half_length] = arrey[i + half_length], arrey[i] return arrey k = int(input()) l = list((input().split())) l = [int(el) for el in l] n = l.copy() found = False count = 0 result = [] if n == sorted(n): result.append(count) found = True if found == False: if k % 2 == 0: loop = 2 else: loop = k for _ in range(loop): n = swap_p1_pn1(n, k) count += 1 if n == sorted(n): found = True result.append(count) break n = swap_p1_p2(n, k) count += 1 if n == sorted(n): found = True result.append(count) break count = 0 n = l.copy() for _ in range(loop): n = swap_p1_p2(n, k) count += 1 if n == sorted(n): found = True result.append(count) break n = swap_p1_pn1(n, k) count += 1 if n == sorted(n): found = True result.append(count) break if found: print(min(result)) if not found: print(-1)
1617523500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["Yes\nYes\nYes\nNo\nNo\nYes"]
933135ef124b35028c1f309d69515e44
NoteFirst game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower).
In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly.
standard output
standard input
Python 3
Python
1,700
train_015.jsonl
e40a6c281f1d261ed26b016a7efefc9d
256 megabytes
["6\n2 4\n75 45\n8 8\n16 16\n247 994\n1000000000 1000000"]
PASSED
import sys n = int(input()) ans = [] arr = sys.stdin.read().split() d = {} for i in range(1,1001): d[i**3] = i for i in range(n): a, b = int(arr[i<<1]), int(arr[i<<1|1]) if a == b: if a in d: ans.append('Yes') else: ans.append('No') continue if a > b: a, b = b, a x = d.get(a*a//b,-1) if x == -1: ans.append('No') continue if a % (x*x): ans.append('No') continue y = a //(x*x) if x * x * y == a and x * y * y == b: ans.append('Yes') else: ans.append('No') print('\n'.join(ans))
1501425300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nYES\nNO"]
0671972bc2b6452d51d048329e6e0106
NoteIn the first test of the example you may choose $$$p = 2$$$ and subtract it once.In the second test of the example you may choose $$$p = 5$$$ and subtract it twice. Note that you cannot choose $$$p = 7$$$, subtract it, then choose $$$p = 3$$$ and subtract it again.In the third test of the example you may choose $$$p = 3$$$ and subtract it $$$333333333333333333$$$ times.
You are given two integers $$$x$$$ and $$$y$$$ (it is guaranteed that $$$x &gt; y$$$). You may choose any prime integer $$$p$$$ and subtract it any number of times from $$$x$$$. Is it possible to make $$$x$$$ equal to $$$y$$$?Recall that a prime number is a positive integer that has exactly two positive divisors: $$$1$$$ and this integer itself. The sequence of prime numbers starts with $$$2$$$, $$$3$$$, $$$5$$$, $$$7$$$, $$$11$$$.Your program should solve $$$t$$$ independent test cases.
For each test case, print YES if it is possible to choose a prime number $$$p$$$ and subtract it any number of times from $$$x$$$ so that $$$x$$$ becomes equal to $$$y$$$. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ lines follow, each describing a test case. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le y &lt; x \le 10^{18}$$$).
standard output
standard input
Python 3
Python
900
train_016.jsonl
fa211d0a17399487f996b85fbb12e378
256 megabytes
["4\n100 98\n42 32\n1000000000000000000 1\n41 40"]
PASSED
t=int(input()) for i in range(t): s=input() s=s.split( ) for e in s: s[s.index(e)]=int(e) if s[0]-s[1]<2: print('NO') elif ((s[0]-s[1])%2)==0 : print('YES') elif (s[0]-s[1]-3) >=0: print('YES') else: print('NO')
1570545300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["6 1 0 0", "12 4 1 0 0 0 0"]
2612df3281cbb9abe328f82e2d755a08
NoteIn the first example 1-palindromes are substring Β«aΒ», Β«bΒ», Β«bΒ», Β«aΒ», Β«bbΒ», Β«abbaΒ», the substring Β«bbΒ» is 2-palindrome. There are no 3- and 4-palindromes here.
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k &gt; 1) if and only if: Its left half equals to its right half. Its left and right halfs are non-empty (k - 1)-palindromes. The left half of string t is its prefix of length ⌊|t| / 2βŒ‹, and right halfΒ β€” the suffix of the same length. ⌊|t| / 2βŒ‹ denotes the length of string t divided by 2, rounded down.Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.
Print |s| integersΒ β€” palindromic characteristics of string s.
The first line contains the string s (1 ≀ |s| ≀ 5000) consisting of lowercase English letters.
standard output
standard input
PyPy 2
Python
1,900
train_069.jsonl
d0d337a3157316b7b92058828607f5a7
256 megabytes
["abba", "abacaba"]
PASSED
s = raw_input() n = len(s) res = [0] * (n + 1) dp = [[0] * n for _ in xrange(n)] for l in xrange(1, n + 1): for i in xrange(n - l + 1): j = i + l - 1 if l == 1: dp[i][j] = 1 continue if s[i] == s[j] and (l == 2 or dp[i + 1][j - 1] > 0): dp[i][j] = 1 else: continue sub_l = l / 2 if dp[i][i + sub_l - 1] > 0: dp[i][j] = dp[i][i + sub_l - 1] + 1 for i in xrange(n): for j in xrange(n): res[dp[i][j]] += 1 for i in xrange(n - 1, 0, -1): res[i] += res[i + 1] print ' '.join(map(str, res[1:]))
1501511700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n2\n2\n0\n1", "14\n0\n2\n2\n2\n0\n2\n2\n1\n1"]
ae7c90b00cc8393fc4db14a6aad32957
null
Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 ≀ l ≀ r ≀ n and gcd(al, al + 1, ..., ar) = xi. is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi.
For each query print the result in a separate line.
The first line of the input contains integer n, (1 ≀ n ≀ 105), denoting the length of the sequence. The next line contains n space separated integers a1, ..., an, (1 ≀ ai ≀ 109). The third line of the input contains integer q, (1 ≀ q ≀ 3 × 105), denoting the number of queries. Then follows q lines, each contain an integer xi, (1 ≀ xi ≀ 109).
standard output
standard input
PyPy 3
Python
2,000
train_007.jsonl
a22ec356d26f087dee478095b974970c
256 megabytes
["3\n2 6 3\n5\n1\n2\n3\n4\n6", "7\n10 20 3 15 1000 60 16\n10\n1\n2\n3\n4\n5\n6\n10\n20\n60\n1000"]
PASSED
from math import gcd from collections import defaultdict from sys import stdin, stdout ##This method is better cause for all the same results we only calculate once def main(): GCD_count = defaultdict(int) GCD_map = defaultdict(int) arr_len = int(stdin.readline()) arr = [int(x) for x in stdin.readline().split()] for start in range(arr_len): temp = defaultdict(int) GCD_count[arr[start]] += 1 temp[arr[start]] += 1 for gcd_now, occurence in GCD_map.items(): res = gcd(gcd_now, arr[start]) temp[res] += occurence GCD_count[res] += occurence GCD_map = temp num_queries = int(stdin.readline()) for _ in range(num_queries): print(GCD_count[int(stdin.readline())]) main()
1412514000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["7\n74"]
529d4ab0bdbb29d8b7f3d3eed19eca63
NoteFor the first testcase, there are $$$7$$$ ways to partition $$$5$$$ as a sum of positive palindromic integers: $$$5=1+1+1+1+1$$$ $$$5=1+1+1+2$$$ $$$5=1+2+2$$$ $$$5=1+1+3$$$ $$$5=2+3$$$ $$$5=1+4$$$ $$$5=5$$$ For the second testcase, there are total $$$77$$$ ways to partition $$$12$$$ as a sum of positive integers but among them, the partitions $$$12=2+10$$$, $$$12=1+1+10$$$ and $$$12=12$$$ are not valid partitions of $$$12$$$ as a sum of positive palindromic integers because $$$10$$$ and $$$12$$$ are not palindromic. So, there are $$$74$$$ ways to partition $$$12$$$ as a sum of positive palindromic integers.
You are given a positive integer $$$n$$$. Let's call some positive integer $$$a$$$ without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express $$$n$$$ as a sum of positive palindromic integers. Two ways are considered different if the frequency of at least one palindromic integer is different in them. For example, $$$5=4+1$$$ and $$$5=3+1+1$$$ are considered different but $$$5=3+1+1$$$ and $$$5=1+3+1$$$ are considered the same. Formally, you need to find the number of distinct multisets of positive palindromic integers the sum of which is equal to $$$n$$$.Since the answer can be quite large, print it modulo $$$10^9+7$$$.
For each testcase, print a single integer denoting the required answer modulo $$$10^9+7$$$.
The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$) denoting the number of testcases. Each testcase contains a single line of input containing a single integer $$$n$$$ ($$$1\leq n\leq 4\cdot 10^4$$$)Β β€” the required sum of palindromic integers.
standard output
standard input
PyPy 3-64
Python
1,500
train_096.jsonl
deb451850d9670a8af7ca4b0b17ccc9d
256 megabytes
["2\n5\n12"]
PASSED
from sys import stdin def readint(): return int(stdin.readline()) def readarray(typ): return list(map(typ, stdin.readline().split())) MOD = int(1e9) + 7 ps = [] N = 40000 for i in range(1, N+1): # print(str(i), ''.join(reversed(str(i))) if str(i) == (str(i)[::-1]): ps.append(i) m = len(ps) dp = [[0] * m for _ in range(N+1)] for i in range(1, N+1): for j in range(m): dp[i][j] += int(i == ps[j]) dp[i][j] += dp[i][j-1] if j >= 1 else 0 if i > ps[j]: dp[i][j] += dp[i-ps[j]][j] dp[i][j] %= MOD t = readint() for _ in range(t): n = readint() print(dp[n][-1])
1651329300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["7\n0\n4\n0\n30\n5\n4\n0\n3"]
783772cb7a54bf65f648d3f8b7648263
NoteThe following picture illustrates the first test case. Polycarp goes from $$$1$$$ to $$$10$$$. The yellow area shows the coverage area of the station with a radius of coverage of $$$1$$$, which is located at the point of $$$7$$$. The green area shows a part of the path when Polycarp is out of coverage area.
Polycarp lives on the coordinate axis $$$Ox$$$ and travels from the point $$$x=a$$$ to $$$x=b$$$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis $$$Ox$$$ at the point $$$x=c$$$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $$$r$$$. Thus, if Polycarp is at a distance less than or equal to $$$r$$$ from the point $$$x=c$$$, then he is in the network coverage area, otherwiseΒ β€” no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from $$$x=a$$$ to $$$x=b$$$. His speedΒ β€” one unit of distance per minute.
Print $$$t$$$ numbersΒ β€” answers to given test cases in the order they are written in the test. Each answer is an integerΒ β€” the number of minutes during which Polycarp will be unavailable during his movement.
The first line contains a positive integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of test cases. In the following lines are written $$$t$$$ test cases. The description of each test case is one line, which contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$r$$$ ($$$-10^8 \le a,b,c \le 10^8$$$, $$$0 \le r \le 10^8$$$)Β β€” the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively. Any of the numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.
standard output
standard input
Python 3
Python
900
train_006.jsonl
2649d97dd1060676ae52c78ea286fc0a
256 megabytes
["9\n1 10 7 1\n3 3 3 0\n8 2 10 4\n8 2 10 100\n-10 20 -17 2\n-3 2 2 0\n-3 1 2 0\n2 3 2 3\n-1 3 -2 2"]
PASSED
a=int(input()) for i in range(a): count=0 b=list(map(int,input().split(" "))) l=b[2]-b[3] u=b[2]+b[3] s=min(b[0],b[1]) e=max(b[0],b[1]) if l<=s<=e<=u: count=0 elif l<=s<=u<=e: count=e-u elif s<=l<=e<=u: count=l-s elif s<=l<=u<=e: count=e-u-s+l elif l<=u<=s<=e or s<=e<=l<=u: count=e-s print(count)
1577198100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3 1 2", "1 2 3 4 5", "-1"]
b6ac7c30b7efdc7206dbbad5cfb86db7
null
An array of integers $$$p_1, p_2, \dots, p_n$$$ is called a permutation if it contains each number from $$$1$$$ to $$$n$$$ exactly once. For example, the following arrays are permutations: $$$[3, 1, 2]$$$, $$$[1]$$$, $$$[1, 2, 3, 4, 5]$$$ and $$$[4, 3, 1, 2]$$$. The following arrays are not permutations: $$$[2]$$$, $$$[1, 1]$$$, $$$[2, 3, 4]$$$.Polycarp invented a really cool permutation $$$p_1, p_2, \dots, p_n$$$ of length $$$n$$$. It is very disappointing, but he forgot this permutation. He only remembers the array $$$q_1, q_2, \dots, q_{n-1}$$$ of length $$$n-1$$$, where $$$q_i=p_{i+1}-p_i$$$.Given $$$n$$$ and $$$q=q_1, q_2, \dots, q_{n-1}$$$, help Polycarp restore the invented permutation.
Print the integer -1 if there is no such permutation of length $$$n$$$ which corresponds to the given array $$$q$$$. Otherwise, if it exists, print $$$p_1, p_2, \dots, p_n$$$. Print any such permutation if there are many of them.
The first line contains the integer $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) β€” the length of the permutation to restore. The second line contains $$$n-1$$$ integers $$$q_1, q_2, \dots, q_{n-1}$$$ ($$$-n &lt; q_i &lt; n$$$).
standard output
standard input
Python 3
Python
1,500
train_007.jsonl
2f8007615f4baaa94a2db4d97e49f366
256 megabytes
["3\n-2 1", "5\n1 1 1 1", "4\n-1 2 2"]
PASSED
n=int(input()) q=list(map(int,input().split())) for i in range(1,n-1): q[i]+=q[i-1] mi=min(q) if (n-1)==len(set(q)): if mi>0: f=1 elif mi<0: f=abs(mi)+1 else: print(-1) exit(0) else: print(-1) exit(0) d=dict() if f<=n: d[f]=1 else: print(-1) exit(0) for i in range(n-1): q[i]+=f try: if d[q[i]]==1: print(-1) exit(0) except KeyError: if q[i] <= n: d[q[i]]=1 else: print(-1) exit(0) print(f,end=" ") for i in q: print(i,end=" ") print()
1553006100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
7 seconds
["5", "0", "721234447"]
fcf5e6320d9cac0f39b3ef503f1b1002
null
A subarray of array $$$a$$$ from index $$$l$$$ to the index $$$r$$$ is the array $$$[a_l, a_{l+1}, \dots, a_{r}]$$$. The number of occurrences of the array $$$b$$$ in the array $$$a$$$ is the number of subarrays of $$$a$$$ such that they are equal to $$$b$$$.You are given $$$n$$$ arrays $$$A_1, A_2, \dots, A_n$$$; the elements of these arrays are integers from $$$1$$$ to $$$k$$$. You have to build an array $$$a$$$ consisting of $$$m$$$ integers from $$$1$$$ to $$$k$$$ in such a way that, for every given subarray $$$A_i$$$, the number of occurrences of $$$A_i$$$ in the array $$$a$$$ is not less than the number of occurrences of each non-empty subarray of $$$A_i$$$ in $$$a$$$. Note that if $$$A_i$$$ doesn't occur in $$$a$$$, and no subarray of $$$A_i$$$ occurs in $$$a$$$, this condition is still met for $$$A_i$$$.Your task is to calculate the number of different arrays $$$a$$$ you can build, and print it modulo $$$998244353$$$.
Print one integer β€” the number of different arrays $$$a$$$ you can build, taken modulo $$$998244353$$$.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m, k \le 3 \cdot 10^5$$$) β€” the number of the given arrays, the desired length of the array $$$a$$$, and the upper bound on the values in the arrays. Then $$$n$$$ lines follow. The $$$i$$$-th line represents the array $$$A_i$$$. The first integer in the $$$i$$$-th line is $$$c_i$$$ ($$$1 \le c_i \le m$$$) β€” the number of elements in $$$A_i$$$; then, $$$c_i$$$ integers from $$$1$$$ to $$$k$$$ follow β€” the elements of the array $$$A_i$$$. Additional constraint on the input: $$$\sum\limits_{i=1}^n c_i \le 3 \cdot 10^5$$$; i. e., the number of elements in the given arrays in total does not exceed $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,700
train_088.jsonl
a8f23434ab95938d5fc470852f98adc8
512 megabytes
["2 4 3\n2 1 2\n1 3", "2 4 3\n2 1 2\n3 3 2 1", "1 42 1337\n2 13 31"]
PASSED
import sys input = sys.stdin.readline n,m,k = map(int, input().split()) nex = [-1] * k prev = [-1] * k bad = [0] * k for _ in range(n): l = list(map(int, input().split())) nn = l.pop(0) tg = True for i in range(nn - 1): u, v = l[i] - 1, l[i+1] - 1 tg = tg and (prev[v] == -1 or prev[v] == u) prev[v] = u tg = tg and (nex[u] == -1 or nex[u] == v) nex[u] = v if not tg: for v in l: bad[v - 1] = 1 MOD = 998244353 b = 500 ct = [0] * b ot = [] dp = [1] for i in range(k): ib = False curr = i val = 0 if prev[i] == -1: while curr != -1: ib = ib or bad[curr] if ib: break curr = nex[curr] val += 1 if not ib: if val < b: ct[val] += 1 else: ot.append(val) for i in range(1, m + 1): curr = 0 for j in range(1, b): if j <= i: curr += (ct[j] * dp[i - j]) curr %= MOD for j in ot: if j <= i: curr += dp[i - j] curr %= MOD dp.append(curr) print(dp[m])
1632148500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1.0 4.0 5.0 3.5 4.5 5.0 5.0", "1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0"]
750e1d9e43f916699537705c11d64d29
null
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:let starting_time be an array of length ncurrent_time = 0dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u)As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
The first line of input contains a single integer n (1 ≀ n ≀ 105)Β β€” the number of cities in USC. The second line contains n - 1 integers p2, p3, ..., pn (1 ≀ pi &lt; i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
standard output
standard input
Python 3
Python
1,700
train_021.jsonl
ee93884f915c3f86a086595e6deb1c05
256 megabytes
["7\n1 2 1 1 4 4", "12\n1 1 2 2 4 4 3 3 1 10 8"]
PASSED
n = int(input()) if n ==1: print(1) exit(0) l = list(map(int,input().split())) w = [[]for i in range(n)] sz = [1]*n for i in range(n-1): w[l[i]-1].append(i+1) for i in range(n-1,-1,-1): for j in range(len(w[i])): sz[i]+=sz[w[i][j]] ans = [0]*n for i in range(n): for j in range(len(w[i])): ans[w[i][j]] = ans[i]+1+(sz[i]-1-sz[w[i][j]])/2 for i in range(n): print(ans[i]+1,end = " ")
1468514100
[ "probabilities", "math", "trees" ]
[ 0, 0, 0, 1, 0, 1, 0, 1 ]
5 seconds
["6", "10", "7", "2"]
2508a347f02aa0f49e0d154c54879b13
NoteIn the first test, you can get the array $$$a = [11, 10, 9, 8, 7, 6, 5, 4, 3]$$$ by performing $$$6$$$ operations: Set $$$a_3$$$ to $$$9$$$: the array becomes $$$[3, 2, 9, 8, 6, 9, 5, 4, 1]$$$; Set $$$a_2$$$ to $$$10$$$: the array becomes $$$[3, 10, 9, 8, 6, 9, 5, 4, 1]$$$; Set $$$a_6$$$ to $$$6$$$: the array becomes $$$[3, 10, 9, 8, 6, 6, 5, 4, 1]$$$; Set $$$a_9$$$ to $$$3$$$: the array becomes $$$[3, 10, 9, 8, 6, 6, 5, 4, 3]$$$; Set $$$a_5$$$ to $$$7$$$: the array becomes $$$[3, 10, 9, 8, 7, 6, 5, 4, 3]$$$; Set $$$a_1$$$ to $$$11$$$: the array becomes $$$[11, 10, 9, 8, 7, 6, 5, 4, 3]$$$. $$$a$$$ is an arithmetic progression: in fact, $$$a_{i+1}-a_i=a_i-a_{i-1}=-1$$$ for any $$$2 \leq i \leq n-1$$$.There is no sequence of less than $$$6$$$ operations that makes $$$a$$$ an arithmetic progression.In the second test, you can get the array $$$a = [-1, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38]$$$ by performing $$$10$$$ operations.In the third test, you can get the array $$$a = [100000, 80000, 60000, 40000, 20000, 0, -20000, -40000, -60000, -80000]$$$ by performing $$$7$$$ operations.
You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$.You can do the following operation any number of times (possibly zero): Choose any index $$$i$$$ and set $$$a_i$$$ to any integer (positive, negative or $$$0$$$). What is the minimum number of operations needed to turn $$$a$$$ into an arithmetic progression? The array $$$a$$$ is an arithmetic progression if $$$a_{i+1}-a_i=a_i-a_{i-1}$$$ for any $$$2 \leq i \leq n-1$$$.
Print a single integer: the minimum number of operations needed to turn $$$a$$$ into an arithmetic progression.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$).
standard output
standard input
PyPy 3-64
Python
2,300
train_105.jsonl
ecd05e438142a11b624af407f3794efa
1024 megabytes
["9\n3 2 7 8 6 9 5 4 1", "14\n19 2 15 8 9 14 17 13 4 14 4 11 15 7", "10\n100000 1 60000 2 20000 4 8 16 32 64", "4\n10000 20000 10000 1"]
PASSED
import sys input=sys.stdin.readline from collections import defaultdict,deque from heapq import heappush,heappop from functools import lru_cache import time from math import gcd def lcm(x, y): return int(x * y / gcd(x, y)) 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()) # nums = list(map(int,input().split(' '))) # nums.sort() # print(nums[-1]+nums[-2]) # for _ in range(int(input())): # s = input() # n = len(s) # nums = list(s) # d = defaultdict(list) # for i,j in enumerate(nums): # d[j].append(i) # ans = 10**9 # for i in range(97,123): # if len(d[chr(i)]) >= 1: # ans = min(ans,d[chr(i)][-1]) # print(s[ans:]) # for _ in range(int(input())): # n = int(input()) # nums = list(map(int,input().split(' '))) # nums.sort() # total = sum(nums) # q = SortedList() # q.add(total) # while q and nums and q[-1] >= nums[-1]: # while q and nums and q[-1] == nums[-1]: # q.pop() # nums.pop() # if q: # t = q.pop() # a,b = t//2,t-t//2 # q.add(a) # q.add(b) # if not nums: # print('YES') # else: # print('NO') # for _ in range(int(input())): # n = int(input()) # deg = [0]*(n+1) # d = defaultdict(list) # for _ in range(n-1): # i,j,x,y = list(map(int,input().split(' '))) # d[i].append((j,x,y)) # d[j].append((i,y,x)) # deg[i] += 1 # deg[j] += 1 # # print(deg) # degg = SortedList([(deg[i],i) for i in range(1,n+1)]) # vis = set() # ans = [1]*(n+1) # q = deque() # for i,j in degg: # if i == 1: # q.append(j) # # while degg and n >= 1: # # i = degg[0][1] # while q: # i = q.popleft() # vis.add(i) # for idx in d[i]: # if idx[0] not in vis: # j,x,y = idx # r = gcd(x,y) # x,y = x//r,y//r # a,b = ans[i],ans[j] # c = lcm(a,b) # x1,y1 = c*x,c*y # xm,ym = x1//a,y1//b # r1 = gcd(xm,ym) # # r1 = gcd(x1,y1) # x1,y1 = x1//r1,y1//r1 # x2,y2 = x1//a,y1//b # print(i,j,x,y,a,b,x2,y2) # print('vis',vis) # print(d[i],d[j]) # for k in d[i]: # # print(k) # if k[0] in vis: # ans[k[0]] *= x2 # for k in d[j]: # # print(k) # if k[0] in vis and k[0] != i: # ans[k[0]] *= y2 # ans[i] *= x2 # ans[j] *= y2 # print('ans',ans) # n -= 1 # deg[i] -= 1 # # degg.pop(0) # # degg.remove((deg[j],j)) # deg[j] -= 1 # if deg[j] == 1: # q.append(j) # # if deg[j] > 0: # # degg.add((deg[j],j)) # print(ans) n = int(input()) a = list(map(int,input().split(' '))) ans = 0 K = 317**3 dic = [0]*K*2 for d in range(-317,317): for i in range(n): ai = a[i]-i*d+K dic[ai] += 1 ans = max(ans,dic[ai]) for i in range(n): ai = a[i]-i*d+K dic[ai] = 0 for i in range(n): for j in range(i+1,min(n,i+317)): da = a[j] - a[i] dx = j - i if da % dx != 0: continue d = da//dx dic[d] += 1 ans = max(ans,dic[d]+1) for j in range(i+1,min(n,i+317)): da = a[j] - a[i] dx = j - i d = da//dx dic[d] = 0 print(n-ans)
1647764100
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["0.857143", "1", "0"]
5a2c9caec9c20a3caed1982ee8ed8f9c
null
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Output on a single line the desired probability with at least 4 digits after the decimal point.
The input consist of a single line with three space separated integers, n, m and k (0 ≀ n, m ≀ 105, 0 ≀ k ≀ 10).
standard output
standard input
Python 3
Python
2,400
train_005.jsonl
8a6cb4297098eb864e487d96e3926ef3
256 megabytes
["5 3 1", "0 5 5", "0 1 0"]
PASSED
#!/usr/bin/python3.5 # -*- coding: utf-8 -*- import json import sys def main(): n, m, k = map(int, input().strip().split()) if n + k < m: print(0) return ans = 1.0 for i in range(k+1): ans *= (m - i) * 1.0 / (n + i + 1) print(1.0 - ans) if __name__ == '__main__': main()
1281970800
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["7\n1 3\n2 1\n2 6\n2 4\n7 4\n3 5", "14\n3 1\n1 4\n11 6\n1 2\n10 13\n6 10\n10 12\n14 12\n8 4\n5 1\n3 7\n2 6\n5 9", "-1"]
7ebf821d51383f1633947a3b455190f6
null
There are n cities in Berland, each of them has a unique idΒ β€” an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roadsΒ β€” there are no roads.That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cities.In the construction plan t integers a1, a2, ..., at were stated, where t equals to the distance from the capital to the most distant city, concerning new roads. ai equals the number of cities which should be at the distance i from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another. Also, it was decided that among all the cities except the capital there should be exactly k cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it. Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.
If it is impossible to built roads which satisfy all conditions, print -1. Otherwise, in the first line print one integer nΒ β€” the number of cities in Berland. In the each of the next n - 1 line print two integersΒ β€” the ids of cities that are connected by a road. Each road should be printed exactly once. You can print the roads and the cities connected by a road in any order. If there are multiple answers, print any of them. Remember that the capital has id 1.
The first line contains three positive numbers n, t and k (2 ≀ n ≀ 2Β·105, 1 ≀ t, k &lt; n)Β β€” the distance to the most distant city from the capital and the number of cities which should be dead-ends (the capital in this number is not taken into consideration). The second line contains a sequence of t integers a1, a2, ..., at (1 ≀ ai &lt; n), the i-th number is the number of cities which should be at the distance i from the capital. It is guaranteed that the sum of all the values ai equals n - 1.
standard output
standard input
Python 3
Python
2,100
train_063.jsonl
2206219586baa368112860eca60963f5
256 megabytes
["7 3 3\n2 3 1", "14 5 6\n4 4 2 2 1", "3 1 1\n2"]
PASSED
n, t, k = map(int, input().split()) a = list(map(int, input().split())) p = {} cnt = 0 cur = 1 floor = [[1]] for ak in a: arr = [cur+i for i in range(1, ak+1)] floor.append(arr) cur += ak for i in range(1, t+1): cnt += len(floor[i]) - 1 if i == t: cnt += 1 for u in floor[i]: p[u] = floor[i-1][0] for i in range(2, t+1): if cnt <= k : break j = 1 min_ = min(len(floor[i]), len(floor[i-1])) while j < min_ and cnt > k: p[floor[i][j]] = floor[i-1][j] cnt-=1 j+=1 if cnt == k: print(n) print('\n'.join([str(u) + ' ' + str(v) for u, v in p.items()])) else: print(-1) # 7 3 3 # 2 3 1 #14 5 6 #4 4 2 2 1 # 10 3 9 # 3 3 3
1482057300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3.0 s
["abacaba bac\n-1\npolycarp lcoayrp\nis si\neverywhere ewyrhv\n-1\n-1"]
8705adec1bea1f898db1ca533e15d5c3
NoteThe first test case is considered in the statement.
Polycarp has a string $$$s$$$. Polycarp performs the following actions until the string $$$s$$$ is empty ($$$t$$$ is initially an empty string): he adds to the right to the string $$$t$$$ the string $$$s$$$, i.e. he does $$$t = t + s$$$, where $$$t + s$$$ is a concatenation of the strings $$$t$$$ and $$$s$$$; he selects an arbitrary letter of $$$s$$$ and removes from $$$s$$$ all its occurrences (the selected letter must occur in the string $$$s$$$ at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string $$$s$$$ will be empty and the string $$$t$$$ will be equal to some value (that is undefined and depends on the order of removing).E.g. consider $$$s$$$="abacaba" so the actions may be performed as follows: $$$t$$$="abacaba", the letter 'b' is selected, then $$$s$$$="aacaa"; $$$t$$$="abacabaaacaa", the letter 'a' is selected, then $$$s$$$="c"; $$$t$$$="abacabaaacaac", the letter 'c' is selected, then $$$s$$$="" (the empty string). You need to restore the initial value of the string $$$s$$$ using only the final value of $$$t$$$ and find the order of removing letters from $$$s$$$.
For each test case output in a separate line: $$$-1$$$, if the answer doesn't exist; two strings separated by spaces. The first one must contain a possible initial value of $$$s$$$. The second one must contain a sequence of letters β€” it's in what order one needs to remove letters from $$$s$$$ to make the string $$$t$$$. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one.
The first line contains one integer $$$T$$$ ($$$1 \le T \le 10^4$$$) β€” the number of test cases. Then $$$T$$$ test cases follow. Each test case contains one string $$$t$$$ consisting of lowercase letters of the Latin alphabet. The length of $$$t$$$ doesn't exceed $$$5 \cdot 10^5$$$. The sum of lengths of all strings $$$t$$$ in the test cases doesn't exceed $$$5 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_103.jsonl
b9509db4293b16ac54ea0feee5b3560b
256 megabytes
["7\nabacabaaacaac\nnowyouknowthat\npolycarppoycarppoyarppyarppyrpprppp\nisi\neverywherevrywhrvryhrvrhrvhv\nhaaha\nqweqeewew"]
PASSED
T = int(input()) for t in range(T): t = input() n = len(t) # find first character with no occurences to the right s = set() r = [] for i in t[::-1]: if i not in s: r.append(i) s.add(i) done = r[::-1] #print(done) v = 0 for i in range(n): v += done.index(t[i]) + 1 if v == n: r = "" tt = t[:i+1] for c in done: r += tt tt=tt.replace(c,"") #print(r) if r != t: print(-1) else: print(t[:i+1],"".join(done)) break elif v > n: print(-1) break
1629297300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1\n6\n95\n20\n28208137\n48102976088"]
c9d57c590f4fe99e4a41f7fce1a8e513
NoteThe string $$$S$$$ is equal to 0110100110010110....In the first test case, $$$S_0$$$ is "0", and $$$S_1$$$ is "1". The Hamming distance between the two strings is $$$1$$$.In the second test case, $$$S_0 S_1 \ldots S_9$$$ is "0110100110", and $$$S_5 S_6 \ldots S_{14}$$$ is "0011001011". The Hamming distance between the two strings is $$$6$$$.
Let $$$S$$$ be the Thue-Morse sequence. In other words, $$$S$$$ is the $$$0$$$-indexed binary string with infinite length that can be constructed as follows: Initially, let $$$S$$$ be "0". Then, we perform the following operation infinitely many times: concatenate $$$S$$$ with a copy of itself with flipped bits.For example, here are the first four iterations: Iteration$$$S$$$ before iteration$$$S$$$ before iteration with flipped bitsConcatenated $$$S$$$1010120110011030110100101101001401101001100101100110100110010110$$$\ldots$$$$$$\ldots$$$$$$\ldots$$$$$$\ldots$$$ You are given two positive integers $$$n$$$ and $$$m$$$. Find the number of positions where the strings $$$S_0 S_1 \ldots S_{m-1}$$$ and $$$S_n S_{n + 1} \ldots S_{n + m - 1}$$$ are different.
For each testcase, output a non-negative integerΒ β€” the Hamming distance between the two required strings.
Each test contains multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. The description of the test cases follows. The first and only line of each test case contains two positive integers, $$$n$$$ and $$$m$$$ respectively ($$$1 \leq n,m \leq 10^{18}$$$).
standard output
standard input
PyPy 3-64
Python
2,500
train_097.jsonl
42b6606c0235388583e41b2b843fd9c5
256 megabytes
["6\n\n1 1\n\n5 10\n\n34 211\n\n73 34\n\n19124639 56348772\n\n12073412269 96221437021"]
PASSED
from functools import cache def par(x): cnt = 0 while x: cnt += 1 x &= x - 1 return cnt & 1 @cache def solve(n, m): if m == 0: return 0 if m & 1: return solve(n, m - 1) + int(par(m - 1) != par(n + m - 1)) if n & 1: return m - solve(n // 2, m // 2) - solve(n // 2 + 1, m // 2) else: return 2 * solve(n // 2, m // 2) t = int(input()) for _ in range(t): n, k = map(int, input().split()) print(solve(n, k))
1663934700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 0 0 1 1 0 \n1 0 0"]
6458ad752e019ffb87573c8bfb712c18
null
RedDreamer has an array $$$a$$$ consisting of $$$n$$$ non-negative integers, and an unlucky integer $$$T$$$.Let's denote the misfortune of array $$$b$$$ having length $$$m$$$ as $$$f(b)$$$ β€” the number of pairs of integers $$$(i, j)$$$ such that $$$1 \le i &lt; j \le m$$$ and $$$b_i + b_j = T$$$. RedDreamer has to paint each element of $$$a$$$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $$$c$$$ and $$$d$$$ so that all white elements belong to $$$c$$$, and all black elements belong to $$$d$$$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $$$f(c) + f(d)$$$ is minimum possible.For example: if $$$n = 6$$$, $$$T = 7$$$ and $$$a = [1, 2, 3, 4, 5, 6]$$$, it is possible to paint the $$$1$$$-st, the $$$4$$$-th and the $$$5$$$-th elements white, and all other elements black. So $$$c = [1, 4, 5]$$$, $$$d = [2, 3, 6]$$$, and $$$f(c) + f(d) = 0 + 0 = 0$$$; if $$$n = 3$$$, $$$T = 6$$$ and $$$a = [3, 3, 3]$$$, it is possible to paint the $$$1$$$-st element white, and all other elements black. So $$$c = [3]$$$, $$$d = [3, 3]$$$, and $$$f(c) + f(d) = 0 + 1 = 1$$$. Help RedDreamer to paint the array optimally!
For each test case print $$$n$$$ integers: $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (each $$$p_i$$$ is either $$$0$$$ or $$$1$$$) denoting the colors. If $$$p_i$$$ is $$$0$$$, then $$$a_i$$$ is white and belongs to the array $$$c$$$, otherwise it is black and belongs to the array $$$d$$$. If there are multiple answers that minimize the value of $$$f(c) + f(d)$$$, print any of them.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le T \le 10^9$$$) β€” the number of elements in the array and the unlucky integer, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$) β€” the elements of the array. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,100
train_001.jsonl
ef5693f9ee6068c993c3c4ee1916ad0d
256 megabytes
["2\n6 7\n1 2 3 4 5 6\n3 6\n3 3 3"]
PASSED
from sys import stdin, stdout import math,sys from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict,Counter from os import path from bisect import bisect_left import heapq mod=10**9+7 def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #------------------Sublime--------------------------------------# sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w'); def inp():return (int(input())) def minp():return(map(int,input().split())) else: #------------------PYPY FAst I/o--------------------------------# def inp():return (int(stdin.readline())) def minp():return(map(int,stdin.readline().split())) ####### ---- Start Your Program From Here ---- ####### for _ in range(inp()): n,t=minp() a=list(minp()) for i in range(n): if a[i]>t/2: a[i]=0 elif a[i]<t/2: a[i]=1 else: a[i]=2 equal=a.count(2) for i in range(n): if a[i]==2: if equal&1: a[i]=0 else: a[i]=1 equal-=1 print(*a)
1601219100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["1", "3", "54", "0"]
6fa3f1fd7675affcf326eeb7fb3c60a5
NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Output one integer β€” the number of meta-sets.
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β€” the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β€” card features. It is guaranteed that all cards are distinct.
standard output
standard input
PyPy 3-64
Python
1,700
train_098.jsonl
4875c7120202f13cf6924aa4f62a9a28
256 megabytes
["8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2"]
PASSED
import collections import math import bisect import sys #import heapq #import itertools #import functools #from sortedcontainers import SortedList M = 3 ** 19 def bitmask(ls): ans = 0 curr = 1 for i, num in enumerate(ls): ans += curr * num curr *= 3 return ans def check(i, j): curr = M ans = 0 while curr: num1 = i // curr num2 = j // curr if num1 == num2: ans += num1 * curr else: ans += (3 - num1 - num2) * curr i -= num1 * curr j -= num2 * curr curr //= 3 return ans def solve(): n, k = list(map(int, input().split())) dic = {} mat = [] for _ in range(n): curr = bitmask([int(i) for i in sys.stdin.readline().split()]) mat.append(curr) dic[curr] = 0 for i in range(n): for j in range(i + 1, n): curr = check(mat[i], mat[j]) if curr in dic: dic[curr] += 1 ans = 0 for key in dic: temp = dic[key] if temp >= 2: ans += math.comb(temp, 2) print(ans) solve()
1664721300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n1 4"]
96855d115913f8c952775aba9ffb5558
null
You are given an undirected graph consisting of n vertices and edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.You have to find the number of connected components in the graph and the size of each component. 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.
Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order.
The first line contains two integers n and m (1 ≀ n ≀ 200000, ). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x ≠ y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices.
standard output
standard input
Python 3
Python
2,100
train_037.jsonl
8ee1459dda55f97d436bc89d66335a5a
256 megabytes
["5 5\n1 2\n3 4\n3 2\n4 2\n2 5"]
PASSED
def Solution(G): unvisited = { i for i in range(len(G)) } sol = [] while unvisited: l = len(unvisited) a = next(iter(unvisited)) unvisited.discard(a) stack = [a] while stack: v = stack.pop() s = unvisited & G[v] stack.extend(unvisited - s) unvisited = s sol.append(l - len(unvisited)) sol.sort() print(len(sol)) print(" ".join(map("{0}".format,sol))) pass def main(): s = input().split(" ") n = int(s[0]) m = int(s[1]) G=[ {i} for i in range(n) ] for _ in range(m): s =input().split(" ") n1 = int(s[0])-1 n2 = int(s[1])-1 G[n2].add(n1) G[n1].add(n2) Solution(G) main()
1517582100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1 2 2 2 \n1 1 \n2 2 3 3 3 3 3"]
d7c2789c5fb216f1de4a99657ffafb4d
Note In the first testcase: For $$$x = 1$$$, we can an edge between vertices $$$1$$$ and $$$3$$$, then $$$d(1) = 0$$$ and $$$d(2) = d(3) = d(4) = 1$$$, so $$$f(1) = 1$$$. For $$$x \ge 2$$$, no matter which edge we add, $$$d(1) = 0$$$, $$$d(2) = d(4) = 1$$$ and $$$d(3) = 2$$$, so $$$f(x) = 2$$$.
This version of the problem differs from the next one only in the constraint on $$$n$$$.A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.You are given a weighted tree with $$$n$$$ vertices, each edge has a weight of $$$1$$$. Denote $$$d(v)$$$ as the distance between vertex $$$1$$$ and vertex $$$v$$$.Let $$$f(x)$$$ be the minimum possible value of $$$\max\limits_{1 \leq v \leq n} \ {d(v)}$$$ if you can temporarily add an edge with weight $$$x$$$ between any two vertices $$$a$$$ and $$$b$$$ $$$(1 \le a, b \le n)$$$. Note that after this operation, the graph is no longer a tree.For each integer $$$x$$$ from $$$1$$$ to $$$n$$$, find $$$f(x)$$$.
For each test case, print $$$n$$$ integers in a single line, $$$x$$$-th of which is equal to $$$f(x)$$$ for all $$$x$$$ from $$$1$$$ to $$$n$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 3000$$$). Each of the next $$$nβˆ’1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) indicating that there is an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3000$$$.
standard output
standard input
PyPy 3-64
Python
2,400
train_084.jsonl
d56c2a4e193de4cd3a638c9c898db74b
512 megabytes
["3\n\n4\n\n1 2\n\n2 3\n\n1 4\n\n2\n\n1 2\n\n7\n\n1 2\n\n1 3\n\n3 4\n\n3 5\n\n3 6\n\n5 7"]
PASSED
from sys import stdin inp = stdin.readline t = int(inp()) for _ in range(t): n = int(inp()) tree = {i: [set(), 0, 0] for i in range(1, n+1)} for i in range(n-1): a, b = map(int, inp().split()) tree[a][0].add(b) tree[b][0].add(a) layer = 0 arr = [set(tree[1][0])] branch = [1] dist = 0 dBranch = [] while True: if not arr[layer]: if layer > dist: dBranch = branch[:] dist = layer for c in tree[branch[layer]][0]: if c != branch[layer-1] or layer == 0: if tree[c][1] + 1 > tree[branch[layer]][1]: tree[branch[layer]][2] = tree[branch[layer]][1] tree[branch[layer]][1] = tree[c][1] + 1 elif tree[c][1] + 1 > tree[branch[layer]][2]: tree[branch[layer]][2] = tree[c][1] + 1 layer -= 1 if layer == -1: break arr.pop() branch.pop() else: current = arr[layer].pop() arr.append(set(tree[current][0])) branch.append(current) arr[layer+1].discard(branch[layer]) layer += 1 longest = [] for i in range(len(dBranch)): longest.append([i + (dist - tree[dBranch[i]][2] - i)//2, tree[dBranch[i]][2], i]) longest.sort() ans = [0]*n x = 0 last = 0 for c in longest: while x+1 < 2*c[2] - c[0]: ans[x] = max(dist - c[0] + x + 1, last) x += 1 last = max(c[1]+c[2], last) while x < n: ans[x] = dist x += 1 print(*ans)
1643553300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["94\n0\n32"]
12814033bec4956e7561767a6778d77e
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
standard output
standard input
Python 3
Python
1,500
train_037.jsonl
1dbd27f90dd65b67bedfe9b659524eea
256 megabytes
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
PASSED
q = int(input()) ans = [] cost = {} def getn(v, k = 1): res = [] while k <= v: res.append(v) v //= 2 return res def getp(arr): res = [] for i in range(len(arr) - 1): res.append((arr[i], arr[i + 1])) return res def gets(u, v): resu, resv = getn(u), getn(v) for i in resv: if i in resu: return getp(getn(u, i)) + getp(getn(v, i)) for i in range(q): t, *p = map(int, input().split()) u, v = p[0], p[1] if v < u: u, v = v, u path = gets(u, v) if t == 1: for rd in path: if rd in cost: cost[rd] += p[2] else: cost[rd] = p[2] else: tot = 0 for rd in path: if rd in cost: tot += cost[rd] ans.append(tot) print("\n".join(map(str, ans)))
1468514100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["1\n3\n0\n0\n0"]
ea616a6b4ba7bf8742420b1c29ff0d16
NoteConsider the test cases of the example: in the first test case, it's possible to remove two characters from the beginning and one character from the end. Only one 1 is deleted, only one 0 remains, so the cost is $$$1$$$; in the second test case, it's possible to remove three characters from the beginning and six characters from the end. Two characters 0 remain, three characters 1 are deleted, so the cost is $$$3$$$; in the third test case, it's optimal to remove four characters from the beginning; in the fourth test case, it's optimal to remove the whole string; in the fifth test case, it's optimal to leave the string as it is.
You are given a string $$$s$$$ consisting of characters 0 and/or 1.You have to remove several (possibly zero) characters from the beginning of the string, and then several (possibly zero) characters from the end of the string. The string may become empty after the removals. The cost of the removal is the maximum of the following two values: the number of characters 0 left in the string; the number of characters 1 removed from the string. What is the minimum cost of removal you can achieve?
For each test case, print one integer β€” the minimum cost of removal you can achieve.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), consisting of characters 0 and/or 1. The total length of strings $$$s$$$ in all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_083.jsonl
7560944dda3650d23f150bf2819a2a75
512 megabytes
["5\n\n101110110\n\n1001001001001\n\n0000111111\n\n00000\n\n1111"]
PASSED
# import sys # input = sys.stdin.readline def sol(arr): l = 0 r = len(arr) - 1 while l<len(arr) and not arr[l] : l += 1 while r >= 0 and not arr[r] : r -= 1 step = [] cnt = 1 total = 0 for i in range(l+1, r+1): if arr[i] == 0: total += 1 if arr[i] == arr[i-1]: cnt += 1 else: step.append(cnt) cnt = 1 step.append(cnt) if len(step) == 1: return 0 best = total left = [(0, 0)] cnt1 = 0 cnt0 = 0 for i in range(0, len(step)-1, 2): cnt1 += step[i] cnt0 += step[i+1] left.append((cnt1, cnt0)) best = min(best, max(cnt1, total - cnt0)) if cnt1 >= total - cnt0: break cnt1 = 0 cnt0 = 0 ind = len(left) - 1 for i in range(len(step) - 1, 0, -2): cnt1 += step[i] cnt0 += step[i-1] best = min(best, max(cnt1, total - cnt0)) while ind >= 0: a = cnt1 + left[ind][0] b = cnt0 + left[ind][1] best = min(best, max(a, total - b)) if a <= total - b: ind += 1 if ind == len(left): ind -= 1 break ind -= 1 return best t = int(input()) for case in range(t): arr = input() arr = [int(i) for i in arr] print(sol(arr))
1652452500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1 49 \n20 40 30 50 10\n26 32 20 38 44 50 \n8 23 18 13 3 \n1 10 13 4 19 22 25 16 7"]
ca9d97e731e86cf8223520f39ef5d945
null
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: The array consists of $$$n$$$ distinct positive (greater than $$$0$$$) integers. The array contains two elements $$$x$$$ and $$$y$$$ (these elements are known for you) such that $$$x &lt; y$$$. If you sort the array in increasing order (such that $$$a_1 &lt; a_2 &lt; \ldots &lt; a_n$$$), differences between all adjacent (consecutive) elements are equal (i.e. $$$a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$$$. It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $$$\max(a_1, a_2, \dots, a_n)$$$.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter). It can be proven that such an array always exists under the given constraints.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$2 \le n \le 50$$$; $$$1 \le x &lt; y \le 50$$$) β€” the length of the array and two elements that are present in the array, respectively.
standard output
standard input
PyPy 2
Python
1,200
train_004.jsonl
bd64f7bc53f67b0e349ed8de49363a04
256 megabytes
["5\n2 1 49\n5 20 50\n6 20 50\n5 3 8\n9 13 22"]
PASSED
import os import sys from atexit import register from io import BytesIO 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') raw_input = lambda: sys.stdin.readline().rstrip('\r\n') def find_f(a): lst = [1,] f = 2 if a % f == 0: lst.append(f) f += 1 while f*f <= a: if a % f == 0: lst.append(f) f += 2 return lst for _ in xrange(int(input())): n,x,y = (int(x) for x in input().split()) lst=find_f(y-x) ans = 10**10 ans_lst = None for f in range(1,51): possible_ans = list(range(y,0,-f))[::-1] + list(range(y,(n+1)*f,f))[1:] try: ind_y = possible_ans.index(y) ind_x = possible_ans.index(x) except ValueError: continue if ind_y - ind_x > n: continue if ind_y+1-n >= 0 and ind_x >= ind_y+1-n: ans_lst = possible_ans[ind_y+1-n:ind_y+1] break if ind_y < n and possible_ans[n-1] < ans: ans = possible_ans[n-1] ans_lst = possible_ans[:n] print(" ".join((str(i) for i in ans_lst))) # if y-x <= n and y-n>0: # print(range(y-n,y+1)) # elif y-x <= n: # print(range(1,1+n))
1599230100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["YES\n1 2\n4 1\n3 1\n2 5\nYES\n4 3\n2 5\n1 5\n5 3\nNO\nYES\n2 4\n4 1\n2 5\n5 3\nYES\n5 4\n4 1\n2 5\n3 5\nYES\n2 3\n3 4\n1 3\nNO\nYES\n4 3\n1 2\n2 4\nNO"]
4750029f0a5e802099a6dd4dff2974d5
null
A tree is a connected undirected graph without cycles. Note that in this problem, we are talking about not rooted trees.You are given four positive integers $$$n, d_{12}, d_{23}$$$ and $$$d_{31}$$$. Construct a tree such that: it contains $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, the distance (length of the shortest path) from vertex $$$1$$$ to vertex $$$2$$$ is $$$d_{12}$$$, distance from vertex $$$2$$$ to vertex $$$3$$$ is $$$d_{23}$$$, the distance from vertex $$$3$$$ to vertex $$$1$$$ is $$$d_{31}$$$. Output any tree that satisfies all the requirements above, or determine that no such tree exists.
For each test case, print YES if the suitable tree exists, and NO otherwise. If the answer is positive, print another $$$n-1$$$ line each containing a description of an edge of the tree β€” a pair of positive integers $$$x_i, y_i$$$, which means that the $$$i$$$th edge connects vertices $$$x_i$$$ and $$$y_i$$$. The edges and vertices of the edges can be printed in any order. If there are several suitable trees, output any of them.
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€”the number of test cases in the test. This is followed by $$$t$$$ test cases, each written on a separate line. Each test case consists of four positive integers $$$n, d_{12}, d_{23}$$$ and $$$d_{31}$$$ ($$$3 \le n \le 2\cdot10^5; 1 \le d_{12}, d_{23}, d_{31} \le n-1$$$). It is guaranteed that the sum of $$$n$$$ values for all test cases does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,900
train_103.jsonl
fc86ad687e2e01c04e0dc7c53bad0ee6
256 megabytes
["9\n\n5 1 2 1\n\n5 2 2 2\n\n5 2 2 3\n\n5 2 2 4\n\n5 3 2 3\n\n4 2 1 1\n\n4 3 1 1\n\n4 1 2 3\n\n7 1 4 1"]
PASSED
t=int(input()) for i in range(t): n,a,b,c=[int(x) for x in input().split()] l=[1] l2=[] x=4 check=True '''for i in range(a-1): l.append(x) x+=1 l.append(2)''' if c+b==a and n>a: '''l.pop(-2) x-=1 l.insert(c,3)''' a1=1 a2=x print('YES') for i in range(a): if c==i+1: a2=3 if x > 4 or i == 0: x -= 1 elif a==i+1: a2=2 z=2 print(a1,a2) if a1==n or a2==n: check=False x += 1 a1=a2 a2=x x-=1 elif a + c == b and n>b: '''for i in range(c - 1): l.insert(0, x) x += 1 l.insert(0, 3)''' print('YES') a1=3 a2=x for i in range(b): if c==i+1: a2=1 if x > 4 or i == 0: x -= 1 elif b==i+1: a2=2 z=2 print(a1,a2) if a1==n or a2==n: check=False x += 1 a1=a2 a2=x x-=1 elif a + b == c and n>c: '''for i in range(b - 1): l.append(x) x += 1 l.append(3)''' print('YES') a1=1 a2=x for i in range(c): if a==i+1: a2=2 if x>4 or i==0: x-=1 elif c==i+1: a2=3 z=3 print(a1,a2) if a1==n or a2==n: check=False x+=1 a1=a2 a2=x x-=1 else: if (c - b + a) % 2 == 0 and c - b + a > 0 and c+b-a>0 and a+b-c>0 and n>(int((c+b-a)/2)+a): '''l2.append(l[int((c - b + a) / 2)]) while (c + b - a) / 2 - 1 != 0: l2.append(x) x += 1 l2.append(3)''' print('YES') a1=1 a2=x index=2 for i in range(a): if a==i+1: a2=2 z=2 if x>4: x-=1 elif int((c-b+a)/2)==i+1: index=a2 print(a1,a2) if a1 == n or a2 == n: check = False x+=1 a1=a2 a2=x a1=index a2=x for i in range(int((c+b-a)/2)): if int((c+b-a)/2)==i+1: a2=3 print(a1,a2) if a1 == n or a2 == n: check = False x+=1 a1=a2 a2=x x-=1 else: print('NO') continue '''if x - 1 > n: print(x) print('NO') continue else: print('YES') for i in range(len(l) - 1): print(l[i], l[i + 1]) for i in range(len(l2) - 1): print(l2[i], l2[i + 1]) z = l[-1]''' if check: while x <=n: print(z,x) z = x x += 1
1659364500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["YES\nYES\nYES\nNO\nNO\nYES"]
2173310623173d761b6039f0e5e661a8
NoteIn the first test case, every guest is shifted by $$$14$$$ rooms, so the assignment is still unique.In the second test case, even guests move to the right by $$$1$$$ room, and odd guests move to the left by $$$1$$$ room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by $$$1$$$ room, and the other guests move to the right by $$$5$$$ rooms. We can show that the assignment is still unique.In the fourth test case, guests $$$0$$$ and $$$1$$$ are both assigned to room $$$3$$$.In the fifth test case, guests $$$1$$$ and $$$2$$$ are both assigned to room $$$2$$$.
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\le k\bmod n\le n-1$$$. For example, $$$100\bmod 12=4$$$ and $$$(-1337)\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.
For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$)Β β€” 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 2\cdot 10^5$$$)Β β€” the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
1,600
train_003.jsonl
ff620df31f063cd839cab1ebdc29c93f
256 megabytes
["6\n1\n14\n2\n1 -1\n4\n5 5 5 1\n3\n3 2 1\n2\n0 1\n5\n-239 -2 -100 -3 -11"]
PASSED
import sys import math import collections import heapq import queue import itertools import functools import operator import time readline = sys.stdin.readline IPS = lambda: readline().rstrip() IP = lambda: int(readline().rstrip()) MP = lambda: map(int, readline().split()) LS = lambda: list(map(int, readline().split())) def solve(): for _ in range(IP()): di = dict() n = IP() arr = LS() for i,elem in enumerate(arr): di[elem+i]=1 ans = [] for key in di.keys(): ans.append((key%n + n)%n) ans = sorted(ans) fg = (len(ans)==n) if fg: for i in range(1,n): if ans[i-1]+1 != ans[i]: fg = 0 break print("Yes") if fg else print("No") if __name__ == "__main__": solve()
1588775700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["69\n359\n573672453"]
178222a468f37615ee260fc9d2944aec
NoteIn the first test case, the minimum total amount of ingredients is $$$69$$$. In fact, the amounts of ingredients $$$1, 2, 3, 4$$$ of a valid potion are $$$16, 12, 9, 32$$$, respectively. The potion is valid because Ingredients $$$3$$$ and $$$2$$$ have a ratio of $$$9 : 12 = 3 : 4$$$; Ingredients $$$1$$$ and $$$2$$$ have a ratio of $$$16 : 12 = 4 : 3$$$; Ingredients $$$1$$$ and $$$4$$$ have a ratio of $$$16 : 32 = 2 : 4$$$. In the second test case, the amounts of ingredients $$$1, 2, 3, 4, 5, 6, 7, 8$$$ in the potion that minimizes the total amount of ingredients are $$$60, 60, 24, 48, 32, 60, 45, 30$$$.
Alice's potion making professor gave the following assignment to his students: brew a potion using $$$n$$$ ingredients, such that the proportion of ingredient $$$i$$$ in the final potion is $$$r_i &gt; 0$$$ (and $$$r_1 + r_2 + \cdots + r_n = 1$$$).He forgot the recipe, and now all he remembers is a set of $$$n-1$$$ facts of the form, "ingredients $$$i$$$ and $$$j$$$ should have a ratio of $$$x$$$ to $$$y$$$" (i.e., if $$$a_i$$$ and $$$a_j$$$ are the amounts of ingredient $$$i$$$ and $$$j$$$ in the potion respectively, then it must hold $$$a_i/a_j = x/y$$$), where $$$x$$$ and $$$y$$$ are positive integers. However, it is guaranteed that the set of facts he remembers is sufficient to uniquely determine the original values $$$r_i$$$.He decided that he will allow the students to pass the class as long as they submit a potion which satisfies all of the $$$n-1$$$ requirements (there may be many such satisfactory potions), and contains a positive integer amount of each ingredient.Find the minimum total amount of ingredients needed to make a potion which passes the class. As the result can be very large, you should print the answer modulo $$$998\,244\,353$$$.
For each test case, print the minimum total amount of ingredients needed to make a potion which passes the class, modulo $$$998\,244\,353$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). Each of the next $$$n-1$$$ lines contains four integers $$$i, j, x, y$$$ ($$$1 \le i, j \le n$$$, $$$i\not=j$$$, $$$1\le x, y \le n$$$) β€” ingredients $$$i$$$ and $$$j$$$ should have a ratio of $$$x$$$ to $$$y$$$. It is guaranteed that the set of facts is sufficient to uniquely determine the original values $$$r_i$$$. It is also guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,100
train_105.jsonl
f864ea0f151158a8a3758358b843cd0a
256 megabytes
["3\n4\n3 2 3 4\n1 2 4 3\n1 4 2 4\n8\n5 4 2 3\n6 4 5 4\n1 3 5 2\n6 8 2 1\n3 5 3 4\n3 2 2 5\n6 7 4 3\n17\n8 7 4 16\n9 17 4 5\n5 14 13 12\n11 1 17 14\n6 13 8 9\n2 11 3 11\n4 17 7 2\n17 16 8 6\n15 5 1 14\n16 7 1 10\n12 17 13 10\n11 16 7 2\n10 11 6 4\n13 17 14 6\n3 11 15 8\n15 6 12 8"]
PASSED
import heapq import math import os import sys from array import array from bisect import bisect_left, bisect_right from collections import defaultdict, deque, Counter from fractions import Fraction from io import IOBase, BytesIO from itertools import groupby, accumulate from sys import stdin from typing import Optional from functools import lru_cache input = lambda: sys.stdin.readline().rstrip("\r\n") print = lambda d: sys.stdout.write(str(d)+"\n") 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 types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc ### CODE HERE # f = open('inputs', 'r') # def input(): return f.readline().rstrip("\r\n") # import sys # sys.setrecursionlimit(999999) MOD, N = 998244353, 200000 inv = [0] * (N + 1); inv[1] = 1 for i in range(2, N + 1): inv[i] = (MOD - MOD // i) * inv[MOD % i] % MOD fact = [{} for _ in range(N + 1)] for i in range(2, N + 1): if len(fact[i]) > 0: continue j = i while j <= N: for k in range(j, N + 1, j): if i not in fact[k]: fact[k][i] = 0 fact[k][i] += 1 j = j * i def solve(): n = read_int() d = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v, a, b = read_int_tuple() d[u].append((v, b, a)) d[v].append((u, a, b)) numer = [1 for _ in range(n + 1)] lcm_book = [0] * (n + 1) @bootstrap def dfs(u, f, frac): for v, a, b in d[u]: if v == f: continue numer[v] = numer[u] * a * inv[b] % MOD for p, cnt in fact[a].items(): frac[p] += cnt for p, cnt in fact[b].items(): frac[p] -= cnt lcm_book[p] = min(lcm_book[p], frac[p]) yield dfs(v, u, frac) for p, cnt in fact[a].items(): frac[p] -= cnt for p, cnt in fact[b].items(): frac[p] += cnt yield None dfs(1, 0, [0] * (n + 1)) res = sum(numer[i] for i in range(1, n + 1)) % MOD for p, cnt in enumerate(lcm_book): if cnt >= 0: continue res = res * pow(p, -cnt, MOD) % MOD print(res) for _ in range(read_int()): solve()
1647764100
[ "number theory", "math", "trees" ]
[ 0, 0, 0, 1, 1, 0, 0, 1 ]
2 seconds
["8\n-1 2 6 4 0 3", "7\n5 -2 4 -1 2"]
3a3666609b120d208c3e8366b186d89b
null
There are $$$n$$$ Christmas trees on an infinite number line. The $$$i$$$-th tree grows at the position $$$x_i$$$. All $$$x_i$$$ are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are $$$m$$$ people who want to celebrate Christmas. Let $$$y_1, y_2, \dots, y_m$$$ be the positions of people (note that all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct and all $$$y_j$$$ should be integer). You want to find such an arrangement of people that the value $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let $$$d_j$$$ be the distance from the $$$j$$$-th human to the nearest Christmas tree ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Then you need to choose such positions $$$y_1, y_2, \dots, y_m$$$ that $$$\sum\limits_{j=1}^{m} d_j$$$ is the minimum possible.
In the first line print one integer $$$res$$$ β€” the minimum possible value of $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (in other words, the sum of distances to the nearest Christmas tree for all people). In the second line print $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), where $$$y_j$$$ is the position of the $$$j$$$-th human. All $$$y_j$$$ should be distinct and all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct. If there are multiple answers, print any of them.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) β€” the number of Christmas trees and the number of people. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), where $$$x_i$$$ is the position of the $$$i$$$-th Christmas tree. It is guaranteed that all $$$x_i$$$ are distinct.
standard output
standard input
PyPy 3
Python
1,800
train_010.jsonl
27d49b3b27d3eddae992ee5d9175f38e
256 megabytes
["2 6\n1 5", "3 5\n0 3 1"]
PASSED
import heapq n, m = map(int, input().split()) x = list(map(int, input().split())) y = [] total_distance = 0 occupied = set(x) Q = [(1, tree + d) for tree in x for d in (1, -1)] while len(y) < m: distance, position = heapq.heappop(Q) if position not in occupied: y.append(position) total_distance += distance occupied.add(position) heapq.heappush(Q, (distance + 1, position + 1)) heapq.heappush(Q, (distance + 1, position - 1)) print(total_distance) print(*y)
1577552700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2", "-1"]
292bd9788a0d5d4a19a1924302f04feb
NoteExplanation for the first sample: In the first operation, Mashtali can choose vertex $$$1$$$ and eliminate players with colors red and blue. In the second operation, he can choose vertex $$$6$$$ and eliminate the player with orange color. In the second sample, Mashtali can't eliminate the first player.
After watching the new over-rated series Squid Game, Mashtali and Soroush decided to hold their own Squid Games! Soroush agreed to be the host and will provide money for the winner's prize, and Mashtali became the Front Man!$$$m$$$ players registered to play in the games to win the great prize, but when Mashtali found out how huge the winner's prize is going to be, he decided to kill eliminate all the players so he could take the money for himself!Here is how evil Mashtali is going to eliminate players:There is an unrooted tree with $$$n$$$ vertices. Every player has $$$2$$$ special vertices $$$x_i$$$ and $$$y_i$$$.In one operation, Mashtali can choose any vertex $$$v$$$ of the tree. Then, for each remaining player $$$i$$$ he finds a vertex $$$w$$$ on the simple path from $$$x_i$$$ to $$$y_i$$$, which is the closest to $$$v$$$. If $$$w\ne x_i$$$ and $$$w\ne y_i$$$, player $$$i$$$ will be eliminated.Now Mashtali wondered: "What is the minimum number of operations I should perform so that I can remove every player from the game and take the money for myself?"Since he was only thinking about the money, he couldn't solve the problem by himself and asked for your help!
Print the minimum number of operations Mashtali has to perform. If there is no way for Mashtali to eliminate all the players, print $$$-1$$$.
The first line contains $$$2$$$ integer $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 3 \cdot 10^5)$$$Β β€” the number of vertices of the tree and the number of players. The second line contains $$$n-1$$$ integers $$$par_2, par_3, \ldots, par_n$$$ $$$(1 \le par_i &lt; i)$$$Β β€” denoting an edge between node $$$i$$$ and $$$par_i$$$. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ $$$(1 \le x_i, y_i \le n, x_i \ne y_i)$$$Β β€” the special vertices of the $$$i$$$-th player.
standard output
standard input
Python 2
Python
3,100
train_085.jsonl
02fbad03a9b230c937030302b38ed539
256 megabytes
["6 3\n1 1 1 4 4\n1 5\n3 4\n2 6", "5 3\n1 1 3 3\n1 2\n1 4\n1 5"]
PASSED
import sys raw_input = iter(sys.stdin.read().splitlines()).next def iter_dfs(adj): L, R, D = [[1]*(len(adj)) for _ in xrange(3)] cnt = -1 stk = [(1, ROOT)] while stk: step, i = stk.pop() if step == 1: stk.append((2, i)) cnt += 1 L[i] = cnt for j in reversed(adj[i]): D[j] = D[i]+1 stk.append((1, j)) elif step == 2: R[i] = cnt return L, R, D def iter_dfs2(adj, up, D): dp, dp2 = [[0]*(len(adj)) for _ in xrange(2)] stk = [(1, ROOT)] while stk: step, i = stk.pop() if step == 1: stk.append((2, i)) for j in reversed(adj[i]): stk.append((1, j)) elif step == 2: for j in adj[i]: if not dp[j]: if not dp[i]: dp2[i] = max(dp2[i], dp2[j], up[j]) continue dp2[i] = max(dp2[j], up[j]) if not dp[i] else 0 dp[i] += dp[j] if dp2[i] == D[i]: dp2[i] = 0 dp[i] += 1 return dp def solution(): n, m = map(int, raw_input().strip().split()) par = map(int, raw_input().strip().split()) adj = [[] for _ in xrange(n)] for i, p in enumerate(par, 1): adj[p-1].append(i) L, R, D = iter_dfs(adj) up, cross = [0]*n, [] for _ in xrange(m): x, y = map(int, raw_input().strip().split()) x, y = x-1, y-1 if L[x] > L[y]: x, y = y, x if R[y] <= R[x]: if D[y] == D[x]+1: return -1 up[y] = max(up[y], D[x]+1) else: cross.append((x, y)) dp = iter_dfs2(adj, up, D) return dp[ROOT]+ any(dp[x]+dp[y] == dp[ROOT] for x, y in cross) ROOT = 0 print '%s' % solution()
1637678100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]